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 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
e905334869af72025592de586b81650cb3468b8a | sentry/queue/client.py | sentry/queue/client.py | from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
| from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
| Declare queues when broker is instantiated | Declare queues when broker is instantiated
| Python | bsd-3-clause | imankulov/sentry,BuildingLink/sentry,zenefits/sentry,korealerts1/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,ngonzalvez/sentry,mvaled/sentry,Kronuz/django-sentry,ngonzalvez/sentry,looker/sentry,felixbuenemann/sentry,ngonzalvez/sentry,nicholasserra/sentry,camilonova/sentry,jokey2k/sentry,llonchj/sentry,fuziontech/sentry,llonchj/sentry,NickPresta/sentry,boneyao/sentry,SilentCircle/sentry,Kryz/sentry,JamesMura/sentry,SilentCircle/sentry,wujuguang/sentry,JTCunning/sentry,rdio/sentry,1tush/sentry,alexm92/sentry,imankulov/sentry,wujuguang/sentry,jokey2k/sentry,jean/sentry,chayapan/django-sentry,looker/sentry,beeftornado/sentry,chayapan/django-sentry,gg7/sentry,chayapan/django-sentry,JamesMura/sentry,1tush/sentry,zenefits/sentry,ewdurbin/sentry,NickPresta/sentry,alex/sentry,camilonova/sentry,kevinastone/sentry,pauloschilling/sentry,boneyao/sentry,korealerts1/sentry,rdio/sentry,daevaorn/sentry,drcapulet/sentry,TedaLIEz/sentry,Kronuz/django-sentry,wong2/sentry,felixbuenemann/sentry,1tush/sentry,hongliang5623/sentry,looker/sentry,BayanGroup/sentry,BuildingLink/sentry,BuildingLink/sentry,BayanGroup/sentry,kevinlondon/sentry,daevaorn/sentry,looker/sentry,llonchj/sentry,gencer/sentry,fotinakis/sentry,BuildingLink/sentry,korealerts1/sentry,felixbuenemann/sentry,boneyao/sentry,alex/sentry,fuziontech/sentry,nicholasserra/sentry,beeftornado/sentry,SilentCircle/sentry,ifduyue/sentry,gencer/sentry,jean/sentry,pauloschilling/sentry,camilonova/sentry,wong2/sentry,mvaled/sentry,JamesMura/sentry,ewdurbin/sentry,JackDanger/sentry,beeftornado/sentry,BuildingLink/sentry,argonemyth/sentry,zenefits/sentry,alex/sentry,gg7/sentry,jean/sentry,vperron/sentry,NickPresta/sentry,mvaled/sentry,JackDanger/sentry,songyi199111/sentry,vperron/sentry,daevaorn/sentry,ifduyue/sentry,kevinlondon/sentry,BayanGroup/sentry,JackDanger/sentry,kevinastone/sentry,Natim/sentry,zenefits/sentry,pauloschilling/sentry,Natim/sentry,argonemyth/sentry,alexm92/sentry,Natim/sentry,Kronuz/django-sentry,gg7/sentry,hongliang5623/sentry,looker/sentry,daevaorn/sentry,TedaLIEz/sentry,alexm92/sentry,vperron/sentry,ifduyue/sentry,mvaled/sentry,jean/sentry,JamesMura/sentry,hongliang5623/sentry,songyi199111/sentry,argonemyth/sentry,JTCunning/sentry,gencer/sentry,nicholasserra/sentry,ifduyue/sentry,Kryz/sentry,Kryz/sentry,beni55/sentry,TedaLIEz/sentry,kevinlondon/sentry,NickPresta/sentry,mvaled/sentry,drcapulet/sentry,jean/sentry,gencer/sentry,songyi199111/sentry,beni55/sentry,beni55/sentry,SilentCircle/sentry,mvaled/sentry,mitsuhiko/sentry,ewdurbin/sentry,wujuguang/sentry,fotinakis/sentry,drcapulet/sentry,fotinakis/sentry,wong2/sentry,ifduyue/sentry,zenefits/sentry,JTCunning/sentry,rdio/sentry,imankulov/sentry,jokey2k/sentry,gencer/sentry,rdio/sentry,JamesMura/sentry,mitsuhiko/sentry | from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
+ with producers[self.connection].acquire(block=False) as producer:
+ for queue in task_queues:
+ maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
- for queue in task_queues:
- maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
| Declare queues when broker is instantiated | ## Code Before:
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
## Instruction:
Declare queues when broker is instantiated
## Code After:
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
|
950ac9130bafe1fced578bf61d746b047830bfa0 | automata/base/exceptions.py | automata/base/exceptions.py | """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
"""A symbol is not a valid symbol for this automaton."""
pass
class MissingStateError(AutomatonException):
"""A state is missing from the automaton definition."""
pass
class MissingSymbolError(AutomatonException):
"""A symbol is missing from the automaton definition."""
pass
class InitialStateError(AutomatonException):
"""The initial state fails to meet some required condition."""
pass
class FinalStateError(AutomatonException):
"""A final state fails to meet some required condition."""
pass
class RejectionException(AutomatonException):
"""The input was rejected by the automaton after validation."""
pass
| """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
"""A symbol is not a valid symbol for this automaton."""
pass
class MissingStateError(AutomatonException):
"""A state is missing from the automaton definition."""
pass
class MissingSymbolError(AutomatonException):
"""A symbol is missing from the automaton definition."""
pass
class InitialStateError(AutomatonException):
"""The initial state fails to meet some required condition."""
pass
class FinalStateError(AutomatonException):
"""A final state fails to meet some required condition."""
pass
class RejectionException(AutomatonException):
"""The input was rejected by the automaton."""
pass
| Remove "validation" from RejectionException docstring | Remove "validation" from RejectionException docstring
| Python | mit | caleb531/automata | """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
"""A symbol is not a valid symbol for this automaton."""
pass
class MissingStateError(AutomatonException):
"""A state is missing from the automaton definition."""
pass
class MissingSymbolError(AutomatonException):
"""A symbol is missing from the automaton definition."""
pass
class InitialStateError(AutomatonException):
"""The initial state fails to meet some required condition."""
pass
class FinalStateError(AutomatonException):
"""A final state fails to meet some required condition."""
pass
class RejectionException(AutomatonException):
- """The input was rejected by the automaton after validation."""
+ """The input was rejected by the automaton."""
pass
| Remove "validation" from RejectionException docstring | ## Code Before:
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
"""A symbol is not a valid symbol for this automaton."""
pass
class MissingStateError(AutomatonException):
"""A state is missing from the automaton definition."""
pass
class MissingSymbolError(AutomatonException):
"""A symbol is missing from the automaton definition."""
pass
class InitialStateError(AutomatonException):
"""The initial state fails to meet some required condition."""
pass
class FinalStateError(AutomatonException):
"""A final state fails to meet some required condition."""
pass
class RejectionException(AutomatonException):
"""The input was rejected by the automaton after validation."""
pass
## Instruction:
Remove "validation" from RejectionException docstring
## Code After:
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
"""A symbol is not a valid symbol for this automaton."""
pass
class MissingStateError(AutomatonException):
"""A state is missing from the automaton definition."""
pass
class MissingSymbolError(AutomatonException):
"""A symbol is missing from the automaton definition."""
pass
class InitialStateError(AutomatonException):
"""The initial state fails to meet some required condition."""
pass
class FinalStateError(AutomatonException):
"""A final state fails to meet some required condition."""
pass
class RejectionException(AutomatonException):
"""The input was rejected by the automaton."""
pass
|
c3f8860c717a139d396b0d902db989ab7b8369ba | stock_inventory_hierarchical/__openerp__.py | stock_inventory_hierarchical/__openerp__.py |
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_inventory_view.xml",
"wizard/generate_inventory_view.xml"],
"images": ["inventory_form.png",
"inventory_form_actions.png",
"wizard.png"],
'license': 'AGPL-3',
'installable': True
}
|
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_inventory_view.xml",
"wizard/generate_inventory_view.xml"],
"images": ["images/inventory_form.png",
"images/inventory_form_actions.png",
"images/wizard.png"],
'license': 'AGPL-3',
'installable': True
}
| Fix image path in manifest | Fix image path in manifest
| Python | agpl-3.0 | kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse |
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_inventory_view.xml",
"wizard/generate_inventory_view.xml"],
- "images": ["inventory_form.png",
+ "images": ["images/inventory_form.png",
- "inventory_form_actions.png",
+ "images/inventory_form_actions.png",
- "wizard.png"],
+ "images/wizard.png"],
'license': 'AGPL-3',
'installable': True
}
| Fix image path in manifest | ## Code Before:
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_inventory_view.xml",
"wizard/generate_inventory_view.xml"],
"images": ["inventory_form.png",
"inventory_form_actions.png",
"wizard.png"],
'license': 'AGPL-3',
'installable': True
}
## Instruction:
Fix image path in manifest
## Code After:
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_inventory_view.xml",
"wizard/generate_inventory_view.xml"],
"images": ["images/inventory_form.png",
"images/inventory_form_actions.png",
"images/wizard.png"],
'license': 'AGPL-3',
'installable': True
}
|
70a642c0597fb2f929fc83d821c8b1f095ed1328 | proxy/plugins/plugins.py | proxy/plugins/plugins.py | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
packetFunctions[(self.pktType, self.pktSubtype)] = f
class commandHook(object):
"""docstring for commandHook"""
def __init__(self, command):
self.command = command
def __call__(self, f):
global commands
commands[self.command] = f
def onStartHook(f):
global onStart
onStart.append(f)
return f
def onConnectionHook(f):
global onConnection
onConnection.append(f)
return f
def onConnectionLossHook(f):
global onConnectionLoss
onConnectionLoss.append(f)
return f | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
if (self.pktType, self.pktSubtype) not in packetFunctions:
packetFunctions[(self.pktType, self.pktSubtype)] = []
packetFunctions[(self.pktType, self.pktSubtype)].append(f)
class commandHook(object):
"""docstring for commandHook"""
def __init__(self, command):
self.command = command
def __call__(self, f):
global commands
commands[self.command] = f
def onStartHook(f):
global onStart
onStart.append(f)
return f
def onConnectionHook(f):
global onConnection
onConnection.append(f)
return f
def onConnectionLossHook(f):
global onConnectionLoss
onConnectionLoss.append(f)
return f | Allow mutiple hooks for packets | Allow mutiple hooks for packets
| Python | agpl-3.0 | alama/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,cyberkitsune/PSO2Proxy | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
+ if (self.pktType, self.pktSubtype) not in packetFunctions:
- packetFunctions[(self.pktType, self.pktSubtype)] = f
+ packetFunctions[(self.pktType, self.pktSubtype)] = []
+ packetFunctions[(self.pktType, self.pktSubtype)].append(f)
class commandHook(object):
"""docstring for commandHook"""
def __init__(self, command):
self.command = command
def __call__(self, f):
global commands
commands[self.command] = f
def onStartHook(f):
global onStart
onStart.append(f)
return f
def onConnectionHook(f):
global onConnection
onConnection.append(f)
return f
def onConnectionLossHook(f):
global onConnectionLoss
onConnectionLoss.append(f)
return f | Allow mutiple hooks for packets | ## Code Before:
packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
packetFunctions[(self.pktType, self.pktSubtype)] = f
class commandHook(object):
"""docstring for commandHook"""
def __init__(self, command):
self.command = command
def __call__(self, f):
global commands
commands[self.command] = f
def onStartHook(f):
global onStart
onStart.append(f)
return f
def onConnectionHook(f):
global onConnection
onConnection.append(f)
return f
def onConnectionLossHook(f):
global onConnectionLoss
onConnectionLoss.append(f)
return f
## Instruction:
Allow mutiple hooks for packets
## Code After:
packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
if (self.pktType, self.pktSubtype) not in packetFunctions:
packetFunctions[(self.pktType, self.pktSubtype)] = []
packetFunctions[(self.pktType, self.pktSubtype)].append(f)
class commandHook(object):
"""docstring for commandHook"""
def __init__(self, command):
self.command = command
def __call__(self, f):
global commands
commands[self.command] = f
def onStartHook(f):
global onStart
onStart.append(f)
return f
def onConnectionHook(f):
global onConnection
onConnection.append(f)
return f
def onConnectionLossHook(f):
global onConnectionLoss
onConnectionLoss.append(f)
return f |
af91b7c2612fab598ba50c0c0256f7e552098d92 | reportlab/docs/genAll.py | reportlab/docs/genAll.py | """Runs the three manual-building scripts"""
if __name__=='__main__':
import os, sys
d = os.path.dirname(sys.argv[0])
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
if not d: d = '.'
if not os.path.isabs(d):
d = os.path.normpath(os.path.join(os.getcwd(),d))
for p in ('reference/genreference.py',
'userguide/genuserguide.py',
'graphguide/gengraphguide.py',
'../tools/docco/graphdocpy.py'):
os.chdir(d)
os.chdir(os.path.dirname(p))
os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
| import os
def _genAll(d=None,quiet=''):
if not d: d = '.'
if not os.path.isabs(d):
d = os.path.normpath(os.path.join(os.getcwd(),d))
for p in ('reference/genreference.py',
'userguide/genuserguide.py',
'graphguide/gengraphguide.py',
'../tools/docco/graphdocpy.py'):
os.chdir(d)
os.chdir(os.path.dirname(p))
os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
"""Runs the manual-building scripts"""
if __name__=='__main__':
import sys
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
_genAll(os.path.dirname(sys.argv[0]),quiet)
| Allow for use in daily.py | Allow for use in daily.py
| Python | bsd-3-clause | makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile | + import os
+ def _genAll(d=None,quiet=''):
+ if not d: d = '.'
+ if not os.path.isabs(d):
+ d = os.path.normpath(os.path.join(os.getcwd(),d))
+ for p in ('reference/genreference.py',
+ 'userguide/genuserguide.py',
+ 'graphguide/gengraphguide.py',
+ '../tools/docco/graphdocpy.py'):
+ os.chdir(d)
+ os.chdir(os.path.dirname(p))
+ os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
+
- """Runs the three manual-building scripts"""
+ """Runs the manual-building scripts"""
if __name__=='__main__':
- import os, sys
- d = os.path.dirname(sys.argv[0])
+ import sys
+ #need a quiet mode for the test suite
+ if '-s' in sys.argv: # 'silent
+ quiet = '-s'
+ else:
+ quiet = ''
+ _genAll(os.path.dirname(sys.argv[0]),quiet)
- #need a quiet mode for the test suite
- if '-s' in sys.argv: # 'silent
- quiet = '-s'
- else:
- quiet = ''
-
- if not d: d = '.'
- if not os.path.isabs(d):
- d = os.path.normpath(os.path.join(os.getcwd(),d))
- for p in ('reference/genreference.py',
- 'userguide/genuserguide.py',
- 'graphguide/gengraphguide.py',
- '../tools/docco/graphdocpy.py'):
- os.chdir(d)
- os.chdir(os.path.dirname(p))
- os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
- | Allow for use in daily.py | ## Code Before:
"""Runs the three manual-building scripts"""
if __name__=='__main__':
import os, sys
d = os.path.dirname(sys.argv[0])
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
if not d: d = '.'
if not os.path.isabs(d):
d = os.path.normpath(os.path.join(os.getcwd(),d))
for p in ('reference/genreference.py',
'userguide/genuserguide.py',
'graphguide/gengraphguide.py',
'../tools/docco/graphdocpy.py'):
os.chdir(d)
os.chdir(os.path.dirname(p))
os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
## Instruction:
Allow for use in daily.py
## Code After:
import os
def _genAll(d=None,quiet=''):
if not d: d = '.'
if not os.path.isabs(d):
d = os.path.normpath(os.path.join(os.getcwd(),d))
for p in ('reference/genreference.py',
'userguide/genuserguide.py',
'graphguide/gengraphguide.py',
'../tools/docco/graphdocpy.py'):
os.chdir(d)
os.chdir(os.path.dirname(p))
os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
"""Runs the manual-building scripts"""
if __name__=='__main__':
import sys
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
_genAll(os.path.dirname(sys.argv[0]),quiet)
|
e34969db596ff3dfa4bf78efb3f3ccfe771d9ef9 | setup.py | setup.py | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.2'
data_files = [
(
'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ],
),
]
setup(
name=PACKAGE, version=VERSION,
description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.",
packages=[ 'exceptional_middleware' ],
data_files=data_files,
license='MIT',
author='James Aylett',
url = 'http://tartarus.org/james/computers/django/',
)
| try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.4'
package_data = {
'exceptional_middleware': [ 'templates/http_responses/*.html' ],
}
setup(
name=PACKAGE, version=VERSION,
description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.",
packages=[ 'exceptional_middleware' ],
package_data=package_data,
license='MIT',
author='James Aylett',
url = 'http://tartarus.org/james/computers/django/',
)
| Fix templates install. Bump to version 0.4 in the process (which is really my laziness). | Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
| Python | mit | jaylett/django_exceptional_middleware | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
- VERSION = '0.2'
+ VERSION = '0.4'
+ package_data = {
+ 'exceptional_middleware': [ 'templates/http_responses/*.html' ],
+ }
- data_files = [
- (
- 'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ],
- ),
- ]
setup(
name=PACKAGE, version=VERSION,
description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.",
packages=[ 'exceptional_middleware' ],
- data_files=data_files,
+ package_data=package_data,
license='MIT',
author='James Aylett',
url = 'http://tartarus.org/james/computers/django/',
)
| Fix templates install. Bump to version 0.4 in the process (which is really my laziness). | ## Code Before:
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.2'
data_files = [
(
'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ],
),
]
setup(
name=PACKAGE, version=VERSION,
description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.",
packages=[ 'exceptional_middleware' ],
data_files=data_files,
license='MIT',
author='James Aylett',
url = 'http://tartarus.org/james/computers/django/',
)
## Instruction:
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
## Code After:
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.4'
package_data = {
'exceptional_middleware': [ 'templates/http_responses/*.html' ],
}
setup(
name=PACKAGE, version=VERSION,
description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.",
packages=[ 'exceptional_middleware' ],
package_data=package_data,
license='MIT',
author='James Aylett',
url = 'http://tartarus.org/james/computers/django/',
)
|
c6265c2112ee9985af8b6b80fe0bee1811dc6abd | setup.py | setup.py | from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.6',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
author_email='[email protected]',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Optics spectrometers.',
long_description=open('README.md').read(),
requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'],
)
| from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.7',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams',
author_email='[email protected]',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Optics spectrometers.',
long_description=open('README.md').read(),
requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'],
)
| Add author and increase version number | Add author and increase version number
| Python | mit | ap--/python-oceanoptics | from distutils.core import setup
setup(
name='oceanoptics',
- version='0.2.6',
+ version='0.2.7',
- author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
+ author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams',
author_email='[email protected]',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Optics spectrometers.',
long_description=open('README.md').read(),
requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'],
)
| Add author and increase version number | ## Code Before:
from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.6',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
author_email='[email protected]',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Optics spectrometers.',
long_description=open('README.md').read(),
requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'],
)
## Instruction:
Add author and increase version number
## Code After:
from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.7',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams',
author_email='[email protected]',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Optics spectrometers.',
long_description=open('README.md').read(),
requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'],
)
|
5bb9b2c9d5df410c85f4736c17224aeb2f05dd33 | s2v3.py | s2v3.py | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data).
price = float(row[2])
total += price
return total
print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing. | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data).
price = float(row[2])
total += price
return total
print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of + | Update print result to use "," instead of "+" for context text | Update print result to use "," instead of "+" for context text
| Python | mit | alexmilesyounger/ds_basics | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data).
price = float(row[2])
total += price
return total
- print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing.
+ print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of + | Update print result to use "," instead of "+" for context text | ## Code Before:
from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data).
price = float(row[2])
total += price
return total
print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing.
## Instruction:
Update print result to use "," instead of "+" for context text
## Code After:
from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data).
price = float(row[2])
total += price
return total
print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of + |
3ba5b6491bf61e2d2919f05bbf5cef088a754aeb | molecule/default/tests/test_installation.py | molecule/default/tests/test_installation.py |
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if packages installed
"""
assert host.package(name).is_installed
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
else:
assert service.is_running
def test_process(host):
"""
Test process state
"""
assert len(host.process.filter(comm='vsftpd')) == 1
def test_socket(host):
"""
Test ports
"""
assert host.socket('tcp://127.0.0.1:21').is_listening
def test_user(host):
"""
Test ftp user exists
"""
ftp_user = host.user('ftp')
assert ftp_user.exists
assert ftp_user.shell == '/bin/false'
|
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if packages installed
"""
assert host.package(name).is_installed
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
else:
assert service.is_running
def test_process(host):
"""
Test process state
"""
assert len(host.process.filter(comm='vsftpd')) == 1
def test_socket(host):
"""
Test ports
"""
assert host.socket('tcp://127.0.0.1:21').is_listening
def test_user(host):
"""
Test ftp user exists
"""
ftp_user = host.user('ftp')
assert ftp_user.exists
assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
| Add nologin in expected user shell test | Add nologin in expected user shell test
| Python | mit | infOpen/ansible-role-vsftpd |
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if packages installed
"""
assert host.package(name).is_installed
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
else:
assert service.is_running
def test_process(host):
"""
Test process state
"""
assert len(host.process.filter(comm='vsftpd')) == 1
def test_socket(host):
"""
Test ports
"""
assert host.socket('tcp://127.0.0.1:21').is_listening
def test_user(host):
"""
Test ftp user exists
"""
ftp_user = host.user('ftp')
assert ftp_user.exists
- assert ftp_user.shell == '/bin/false'
+ assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
| Add nologin in expected user shell test | ## Code Before:
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if packages installed
"""
assert host.package(name).is_installed
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
else:
assert service.is_running
def test_process(host):
"""
Test process state
"""
assert len(host.process.filter(comm='vsftpd')) == 1
def test_socket(host):
"""
Test ports
"""
assert host.socket('tcp://127.0.0.1:21').is_listening
def test_user(host):
"""
Test ftp user exists
"""
ftp_user = host.user('ftp')
assert ftp_user.exists
assert ftp_user.shell == '/bin/false'
## Instruction:
Add nologin in expected user shell test
## Code After:
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if packages installed
"""
assert host.package(name).is_installed
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
else:
assert service.is_running
def test_process(host):
"""
Test process state
"""
assert len(host.process.filter(comm='vsftpd')) == 1
def test_socket(host):
"""
Test ports
"""
assert host.socket('tcp://127.0.0.1:21').is_listening
def test_user(host):
"""
Test ftp user exists
"""
ftp_user = host.user('ftp')
assert ftp_user.exists
assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
|
b4c9b76d132668695b77d37d7db3071e629fcba7 | makerscience_admin/models.py | makerscience_admin/models.py | from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
| from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
def clear_makerscience(sender, instance, **kwargs):
if sender == MakerSciencePost:
ObjectProfileLink.objects.filter(content_type__model='post',
object_id=instance.parent.id).delete()
instance.parent.delete()
post_delete.connect(clear_makerscience, sender=MakerSciencePost)
| Allow to clear useless instances | Allow to clear useless instances
| Python | agpl-3.0 | atiberghien/makerscience-server,atiberghien/makerscience-server | from django.db import models
+ from django.db.models.signals import post_delete
+
from solo.models import SingletonModel
+
+ from accounts.models import ObjectProfileLink
+
+ from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
+
+ def clear_makerscience(sender, instance, **kwargs):
+ if sender == MakerSciencePost:
+ ObjectProfileLink.objects.filter(content_type__model='post',
+ object_id=instance.parent.id).delete()
+ instance.parent.delete()
+
+ post_delete.connect(clear_makerscience, sender=MakerSciencePost)
+ | Allow to clear useless instances | ## Code Before:
from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
## Instruction:
Allow to clear useless instances
## Code After:
from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField(null=True, blank=True)
about_cgu = models.TextField(null=True, blank=True)
class PageViews(models.Model):
client = models.CharField(max_length=255)
resource_uri = models.CharField(max_length=255)
def clear_makerscience(sender, instance, **kwargs):
if sender == MakerSciencePost:
ObjectProfileLink.objects.filter(content_type__model='post',
object_id=instance.parent.id).delete()
instance.parent.delete()
post_delete.connect(clear_makerscience, sender=MakerSciencePost)
|
c713273fe145418113d750579f8b135dc513c3b8 | config.py | config.py | import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| Delete default case for SQLALCHEMY_DATABASE_URI | Delete default case for SQLALCHEMY_DATABASE_URI
if user doesn't set it, he coud have some problems with SQLite
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | import os
- if os.environ.get('DATABASE_URL') is None:
- SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
- else:
- SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
+ SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
-
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| Delete default case for SQLALCHEMY_DATABASE_URI | ## Code Before:
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
## Instruction:
Delete default case for SQLALCHEMY_DATABASE_URI
## Code After:
import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
|
c61d5e84863dd67b5b76ec8031e624642f4c957c | main.py | main.py | from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
from .ide.utility import *
| from .ide.auto_complete import *
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
| Fix issue with wrong import | Fix issue with wrong import
| Python | mit | b123400/purescript-ide-sublime | + from .ide.auto_complete import *
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
- from .ide.utility import *
| Fix issue with wrong import | ## Code Before:
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
from .ide.utility import *
## Instruction:
Fix issue with wrong import
## Code After:
from .ide.auto_complete import *
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
|
4e75e742475236cf7358b4481a29a54eb607dd4d | spacy/tests/regression/test_issue850.py | spacy/tests/regression/test_issue850.py | '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
@pytest.mark.xfail
def test_issue850():
matcher = Matcher(Vocab())
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank'])
match = matcher(doc)
assert len(match) == 1
start, end, label, ent_id = match
assert start == 0
assert end == 4
| '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
def test_basic_case():
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', LOWER: 'and'},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
@pytest.mark.xfail
def test_issue850():
'''The problem here is that the variable-length pattern matches the
succeeding token. We then don't handle the ambiguity correctly.'''
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
| Update regression test for variable-length pattern problem in the matcher. | Update regression test for variable-length pattern problem in the matcher.
| Python | mit | aikramer2/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,recognai/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy | '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
+ from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
+ def test_basic_case():
+ matcher = Matcher(Vocab(
+ lex_attr_getters={LOWER: lambda string: string.lower()}))
+ IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
+ matcher.add_pattern(
+ "FarAway",
+ [
+ {LOWER: "bob"},
+ {'OP': '*', LOWER: 'and'},
+ {LOWER: 'frank'}
+ ])
+ doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
+ match = matcher(doc)
+ assert len(match) == 1
+ ent_id, label, start, end = match[0]
+ assert start == 0
+ assert end == 4
+
@pytest.mark.xfail
def test_issue850():
+ '''The problem here is that the variable-length pattern matches the
+ succeeding token. We then don't handle the ambiguity correctly.'''
- matcher = Matcher(Vocab())
+ matcher = Matcher(Vocab(
+ lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
- doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank'])
+ doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
- start, end, label, ent_id = match
+ ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
| Update regression test for variable-length pattern problem in the matcher. | ## Code Before:
'''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
@pytest.mark.xfail
def test_issue850():
matcher = Matcher(Vocab())
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank'])
match = matcher(doc)
assert len(match) == 1
start, end, label, ent_id = match
assert start == 0
assert end == 4
## Instruction:
Update regression test for variable-length pattern problem in the matcher.
## Code After:
'''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
def test_basic_case():
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', LOWER: 'and'},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
@pytest.mark.xfail
def test_issue850():
'''The problem here is that the variable-length pattern matches the
succeeding token. We then don't handle the ambiguity correctly.'''
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
|
fa8783f3307582dafcf636f5c94a7e4cff05724b | bin/tree_print_fasta_names.py | bin/tree_print_fasta_names.py |
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
|
import os
import shutil
import datetime
import sys
from ete3 import Tree
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
| Fix error in loading trees | Fix error in loading trees
Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda | Python | mit | karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle |
import os
import shutil
import datetime
import sys
- import argparse
from ete3 import Tree
-
- import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
- self.tree=read_newick(tree_newick_fn,format=format)
+ self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
| Fix error in loading trees | ## Code Before:
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
## Instruction:
Fix error in loading trees
## Code After:
import os
import shutil
import datetime
import sys
from ete3 import Tree
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
|
a20c6d072d70c535ed1f116fc04016c834ea9c14 | doc/en/_getdoctarget.py | doc/en/_getdoctarget.py |
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line:
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(get_version_string().split(".")[:2])
if __name__ == "__main__":
print (get_minor_version_string())
|
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line and not line.strip().startswith('#'):
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(get_version_string().split(".")[:2])
if __name__ == "__main__":
print (get_minor_version_string())
| Fix getdoctarget to ignore comment lines | Fix getdoctarget to ignore comment lines
| Python | mit | etataurov/pytest,gabrielcnr/pytest,mbirtwell/pytest,vodik/pytest,The-Compiler/pytest,omarkohl/pytest,Bjwebb/pytest,davidszotten/pytest,gabrielcnr/pytest,mdboom/pytest,ionelmc/pytest,malinoff/pytest,hpk42/pytest,tareqalayan/pytest,userzimmermann/pytest,rouge8/pytest,tgoodlet/pytest,abusalimov/pytest,bukzor/pytest,icemac/pytest,pfctdayelise/pytest,JonathonSonesen/pytest,ionelmc/pytest,alfredodeza/pytest,chiller/pytest,skylarjhdownes/pytest,RonnyPfannschmidt/pytest,Haibo-Wang-ORG/pytest,lukas-bednar/pytest,mhils/pytest,mhils/pytest,chiller/pytest,oleg-alexandrov/pytest,oleg-alexandrov/pytest,MengJueM/pytest,chillbear/pytest,rmfitzpatrick/pytest,tomviner/pytest,Bachmann1234/pytest,pytest-dev/pytest,doordash/pytest,eli-b/pytest,codewarrior0/pytest,flub/pytest,bukzor/pytest,ropez/pytest,Haibo-Wang-ORG/pytest,abusalimov/pytest,mdboom/pytest,MengJueM/pytest,icemac/pytest,The-Compiler/pytest,vmalloc/dessert,codewarrior0/pytest,jb098/pytest,chillbear/pytest,jb098/pytest,omarkohl/pytest,doordash/pytest,mbirtwell/pytest,nicoddemus/pytest,tomviner/pytest,nicoddemus/pytest,ropez/pytest,jaraco/pytest,rouge8/pytest,markshao/pytest,txomon/pytest,lukas-bednar/pytest,Bachmann1234/pytest,userzimmermann/pytest,MichaelAquilina/pytest,vodik/pytest,hpk42/pytest,ddboline/pytest,hackebrot/pytest,JonathonSonesen/pytest,Akasurde/pytest,Bjwebb/pytest |
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
- if "version" in line:
+ if "version" in line and not line.strip().startswith('#'):
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(get_version_string().split(".")[:2])
if __name__ == "__main__":
print (get_minor_version_string())
| Fix getdoctarget to ignore comment lines | ## Code Before:
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line:
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(get_version_string().split(".")[:2])
if __name__ == "__main__":
print (get_minor_version_string())
## Instruction:
Fix getdoctarget to ignore comment lines
## Code After:
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line and not line.strip().startswith('#'):
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(get_version_string().split(".")[:2])
if __name__ == "__main__":
print (get_minor_version_string())
|
efd6fad89131c4d3070c68013ace77f11647bd68 | opal/core/search/__init__.py | opal/core/search/__init__.py | from opal.core.search import urls
from opal.core import plugins
from opal.core import celery # NOQA
class SearchPlugin(plugins.OpalPlugin):
"""
The plugin entrypoint for OPAL's core search functionality
"""
urls = urls.urlpatterns
javascripts = {
'opal.services': [
'js/search/services/filter.js',
'js/search/services/filters_loader.js',
'js/search/services/filter_resource.js',
"js/search/services/paginator.js",
],
'opal.controllers': [
'js/search/controllers/search.js',
'js/search/controllers/extract.js',
"js/search/controllers/save_filter.js",
]
}
plugins.register(SearchPlugin)
| from opal.core import celery # NOQA
from opal.core.search import plugin
| Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor | Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | + from opal.core import celery # NOQA
- from opal.core.search import urls
+ from opal.core.search import plugin
- from opal.core import plugins
-
- from opal.core import celery # NOQA
-
-
- class SearchPlugin(plugins.OpalPlugin):
- """
- The plugin entrypoint for OPAL's core search functionality
- """
- urls = urls.urlpatterns
- javascripts = {
- 'opal.services': [
- 'js/search/services/filter.js',
- 'js/search/services/filters_loader.js',
- 'js/search/services/filter_resource.js',
- "js/search/services/paginator.js",
- ],
- 'opal.controllers': [
- 'js/search/controllers/search.js',
- 'js/search/controllers/extract.js',
- "js/search/controllers/save_filter.js",
- ]
- }
-
- plugins.register(SearchPlugin)
- | Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor | ## Code Before:
from opal.core.search import urls
from opal.core import plugins
from opal.core import celery # NOQA
class SearchPlugin(plugins.OpalPlugin):
"""
The plugin entrypoint for OPAL's core search functionality
"""
urls = urls.urlpatterns
javascripts = {
'opal.services': [
'js/search/services/filter.js',
'js/search/services/filters_loader.js',
'js/search/services/filter_resource.js',
"js/search/services/paginator.js",
],
'opal.controllers': [
'js/search/controllers/search.js',
'js/search/controllers/extract.js',
"js/search/controllers/save_filter.js",
]
}
plugins.register(SearchPlugin)
## Instruction:
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
## Code After:
from opal.core import celery # NOQA
from opal.core.search import plugin
|
56a8b900570200e63ee460dd7e2962cba2450b16 | preparation/tools/build_assets.py | preparation/tools/build_assets.py | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert all not in args.resources or len(args.resources) == 1
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
| from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert 'all' not in args.resources or len(args.resources) == 1
if 'all' in args.resources:
args.resources = [name.replace('Resource', '') for name in names_registered()]
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
| Fix bug with 'all' argument | Fix bug with 'all' argument
| Python | mit | hatbot-team/hatbot_resources | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
- assert all not in args.resources or len(args.resources) == 1
+ assert 'all' not in args.resources or len(args.resources) == 1
+ if 'all' in args.resources:
+ args.resources = [name.replace('Resource', '') for name in names_registered()]
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
| Fix bug with 'all' argument | ## Code Before:
from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert all not in args.resources or len(args.resources) == 1
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
## Instruction:
Fix bug with 'all' argument
## Code After:
from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert 'all' not in args.resources or len(args.resources) == 1
if 'all' in args.resources:
args.resources = [name.replace('Resource', '') for name in names_registered()]
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
|
6167215e4ed49e8a4300f327d5b4ed4540d1a420 | numba/tests/npyufunc/test_parallel_env_variable.py | numba/tests/npyufunc/test_parallel_env_variable.py | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
try:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
| from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default. Should not fail even if
# threads are launched because the value is the same.
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
| Fix the parallel env variable test to reset the env correctly | Fix the parallel env variable test to reset the env correctly
| Python | bsd-2-clause | seibert/numba,seibert/numba,stonebig/numba,cpcloud/numba,sklam/numba,gmarkall/numba,stuartarchibald/numba,numba/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,sklam/numba,sklam/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,numba/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,gmarkall/numba,numba/numba,seibert/numba,IntelLabs/numba,gmarkall/numba,numba/numba,numba/numba,sklam/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,stonebig/numba,IntelLabs/numba,seibert/numba,cpcloud/numba | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
- try:
- self.assertEqual(threads, str(get_thread_count()))
+ self.assertEqual(threads, str(get_thread_count()))
- self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
+ self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
- finally:
+ finally:
- # reset the env variable/set to default
+ # reset the env variable/set to default. Should not fail even if
+ # threads are launched because the value is the same.
- env[key] = current
+ env[key] = current
- config.reload_config()
+ config.reload_config()
if __name__ == '__main__':
unittest.main()
| Fix the parallel env variable test to reset the env correctly | ## Code Before:
from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
try:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
## Instruction:
Fix the parallel env variable test to reset the env correctly
## Code After:
from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
try:
config.reload_config()
except RuntimeError as e:
# This test should fail if threads have already been launched
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
else:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default. Should not fail even if
# threads are launched because the value is the same.
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
|
504205d02ef2f5b66da225390fdb34b8b736ce57 | ideascube/migrations/0009_add_a_system_user.py | ideascube/migrations/0009_add_a_system_user.py | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import migrations
def add_user(*args):
User = get_user_model()
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
| from __future__ import unicode_literals
from django.db import migrations
def add_user(apps, *args):
User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
| Load user from migration registry when creating system user | Load user from migration registry when creating system user
Always load models from the registry in migration files.
I hate the idea of touching a migration already released, but
this one prevents us from adding new properties to User.
If we load the User directly (not from registry) when creating
the user model, we'll try to create a user with column that does
not exist at the time of this migration.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from __future__ import unicode_literals
- from django.contrib.auth import get_user_model
from django.db import migrations
- def add_user(*args):
+ def add_user(apps, *args):
- User = get_user_model()
+ User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
| Load user from migration registry when creating system user | ## Code Before:
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import migrations
def add_user(*args):
User = get_user_model()
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
## Instruction:
Load user from migration registry when creating system user
## Code After:
from __future__ import unicode_literals
from django.db import migrations
def add_user(apps, *args):
User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
|
d8d2e4b763fbd7cedc42046f6f45395bf15caa79 | samples/plugins/scenario/scenario_plugin.py | samples/plugins/scenario/scenario_plugin.py |
from rally.task.scenarios import base
class ScenarioPlugin(base.Scenario):
"""Sample plugin which lists flavors."""
@base.atomic_action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@base.atomic_action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@base.scenario()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
|
from rally.plugins.openstack import scenario
from rally.task import atomic
class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
@atomic.action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@atomic.action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@scenario.configure()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
| Fix the scenario plugin sample | Fix the scenario plugin sample
We forgot to fix scenario plugin sample when we were doing
rally.task.scenario refactoring
Change-Id: Iadbb960cf168bd3b9cd6c1881a5f7a8dffd7036f
| Python | apache-2.0 | group-policy/rally,eayunstack/rally,openstack/rally,amit0701/rally,paboldin/rally,eonpatapon/rally,cernops/rally,afaheem88/rally,yeming233/rally,vganapath/rally,gluke77/rally,aforalee/RRally,yeming233/rally,openstack/rally,gluke77/rally,gluke77/rally,eayunstack/rally,openstack/rally,aforalee/RRally,cernops/rally,group-policy/rally,openstack/rally,vganapath/rally,amit0701/rally,vganapath/rally,redhat-openstack/rally,eonpatapon/rally,amit0701/rally,gluke77/rally,paboldin/rally,redhat-openstack/rally,paboldin/rally,group-policy/rally,afaheem88/rally,eayunstack/rally,aplanas/rally,vganapath/rally,aplanas/rally |
- from rally.task.scenarios import base
+ from rally.plugins.openstack import scenario
+ from rally.task import atomic
- class ScenarioPlugin(base.Scenario):
+ class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
- @base.atomic_action_timer("list_flavors")
+ @atomic.action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
- @base.atomic_action_timer("list_flavors_as_admin")
+ @atomic.action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
- @base.scenario()
+ @scenario.configure()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
| Fix the scenario plugin sample | ## Code Before:
from rally.task.scenarios import base
class ScenarioPlugin(base.Scenario):
"""Sample plugin which lists flavors."""
@base.atomic_action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@base.atomic_action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@base.scenario()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
## Instruction:
Fix the scenario plugin sample
## Code After:
from rally.plugins.openstack import scenario
from rally.task import atomic
class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
@atomic.action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients which are
initialized on scenario instance creation.
"""
self.clients("nova").flavors.list()
@atomic.action_timer("list_flavors_as_admin")
def _list_flavors_as_admin(self):
"""The same with admin clients."""
self.admin_clients("nova").flavors.list()
@scenario.configure()
def list_flavors(self):
"""List flavors."""
self._list_flavors()
self._list_flavors_as_admin()
|
68a621005c5a520b7a97c4cad462d43fb7f3aaed | paws/views.py | paws/views.py |
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
request = Request(event, context)
resp = self.prepare(request)
if resp:
return resp
kwargs = event.get('pathParameters') or {}
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
|
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
kwargs = event.get('pathParameters') or {}
self.dispatch(request, **kwargs)
def dispatch(self, request, **kwargs):
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
| Break out dispatch, and drop prepare. Easier testing | Break out dispatch, and drop prepare. Easier testing
| Python | bsd-3-clause | funkybob/paws |
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
- request = Request(event, context)
- resp = self.prepare(request)
- if resp:
- return resp
kwargs = event.get('pathParameters') or {}
+ self.dispatch(request, **kwargs)
+
+ def dispatch(self, request, **kwargs):
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
| Break out dispatch, and drop prepare. Easier testing | ## Code Before:
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
request = Request(event, context)
resp = self.prepare(request)
if resp:
return resp
kwargs = event.get('pathParameters') or {}
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
## Instruction:
Break out dispatch, and drop prepare. Easier testing
## Code After:
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
kwargs = event.get('pathParameters') or {}
self.dispatch(request, **kwargs)
def dispatch(self, request, **kwargs):
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
|
d4d448adff71b609d5efb269d1a9a2ea4aba3590 | radio/templatetags/radio_js_config.py | radio/templatetags/radio_js_config.py | import random
import json
from django import template
from django.conf import settings
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
| import random
import json
from django import template
from django.conf import settings
from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
for opt in SiteOption.objects.filter(javascript_visible=True):
js_json[opt.name] = opt.value_boolean_or_string()
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
| Allow SiteOption to load into the JS | Allow SiteOption to load into the JS
| Python | mit | ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player | import random
import json
from django import template
from django.conf import settings
+
+ from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
+ for opt in SiteOption.objects.filter(javascript_visible=True):
+ js_json[opt.name] = opt.value_boolean_or_string()
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
| Allow SiteOption to load into the JS | ## Code Before:
import random
import json
from django import template
from django.conf import settings
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
## Instruction:
Allow SiteOption to load into the JS
## Code After:
import random
import json
from django import template
from django.conf import settings
from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
for setting in js_settings:
set_val = getattr(settings, setting, '')
js_json[setting] = set_val
for opt in SiteOption.objects.filter(javascript_visible=True):
js_json[opt.name] = opt.value_boolean_or_string()
js_json['user_is_staff'] = user.is_staff
if user.is_authenticated():
js_json['user_is_authenticated'] = True
else:
js_json['user_is_authenticated'] = False
js_json['radio_change_unit'] = user.has_perm('radio.change_unit')
return json.dumps(js_json)
|
0a13a9a8a779102dbcb2beead7d8aa9143f4c79b | tests/pytests/unit/client/ssh/test_shell.py | tests/pytests/unit/client/ssh/test_shell.py | import os
import subprocess
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
@pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh")
@pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True)
class TestSSHShell:
def test_ssh_shell_key_gen(self, keys):
"""
Test ssh key_gen
"""
shell.gen_key(keys["priv_key"])
for fp in keys.keys():
assert os.path.exists(keys[fp])
# verify there is not a passphrase set on key
ret = subprocess.check_output(
["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30,
)
assert ret.decode().startswith("ssh-rsa")
| import subprocess
import types
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key)
@pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh")
@pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True)
def test_ssh_shell_key_gen(keys):
"""
Test ssh key_gen
"""
shell.gen_key(str(keys.priv_key))
assert keys.priv_key.exists()
assert keys.pub_key.exists()
# verify there is not a passphrase set on key
ret = subprocess.check_output(
["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30,
)
assert ret.decode().startswith("ssh-rsa")
| Use commit suggestion to use types | Use commit suggestion to use types
Co-authored-by: Pedro Algarvio <[email protected]>
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | - import os
import subprocess
+ import types
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
- yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
+ return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key)
@pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh")
@pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True)
- class TestSSHShell:
- def test_ssh_shell_key_gen(self, keys):
+ def test_ssh_shell_key_gen(keys):
- """
+ """
- Test ssh key_gen
+ Test ssh key_gen
- """
+ """
- shell.gen_key(keys["priv_key"])
+ shell.gen_key(str(keys.priv_key))
- for fp in keys.keys():
- assert os.path.exists(keys[fp])
+ assert keys.priv_key.exists()
+ assert keys.pub_key.exists()
+ # verify there is not a passphrase set on key
+ ret = subprocess.check_output(
+ ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30,
+ )
+ assert ret.decode().startswith("ssh-rsa")
- # verify there is not a passphrase set on key
- ret = subprocess.check_output(
- ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30,
- )
- assert ret.decode().startswith("ssh-rsa")
- | Use commit suggestion to use types | ## Code Before:
import os
import subprocess
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
@pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh")
@pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True)
class TestSSHShell:
def test_ssh_shell_key_gen(self, keys):
"""
Test ssh key_gen
"""
shell.gen_key(keys["priv_key"])
for fp in keys.keys():
assert os.path.exists(keys[fp])
# verify there is not a passphrase set on key
ret = subprocess.check_output(
["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30,
)
assert ret.decode().startswith("ssh-rsa")
## Instruction:
Use commit suggestion to use types
## Code After:
import subprocess
import types
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key)
@pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh")
@pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True)
def test_ssh_shell_key_gen(keys):
"""
Test ssh key_gen
"""
shell.gen_key(str(keys.priv_key))
assert keys.priv_key.exists()
assert keys.pub_key.exists()
# verify there is not a passphrase set on key
ret = subprocess.check_output(
["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30,
)
assert ret.decode().startswith("ssh-rsa")
|
09d780474d00f3a8f4c2295154d74dae2023c1d3 | samples/storage_sample/storage/__init__.py | samples/storage_sample/storage/__init__.py | """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| Drop the CLI from the sample storage client imports. | Drop the CLI from the sample storage client imports.
| Python | apache-2.0 | cherba/apitools,craigcitro/apitools,b-daniels/apitools,betamos/apitools,kevinli7/apitools,houglum/apitools,pcostell/apitools,thobrla/apitools,google/apitools | """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
- from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| Drop the CLI from the sample storage client imports. | ## Code Before:
"""Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
## Instruction:
Drop the CLI from the sample storage client imports.
## Code After:
"""Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
|
08d838e87bd92dacbbbfe31b19c628b9d3b271a8 | src/plone.example/plone/example/todo.py | src/plone.example/plone/example/todo.py | from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
| from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
default=u''
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
default=False
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
| Set default values for fields | Set default values for fields
| Python | bsd-2-clause | plone/plone.server,plone/plone.server | from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
+ default=u''
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
+ default=False
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
| Set default values for fields | ## Code Before:
from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
## Instruction:
Set default values for fields
## Code After:
from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.interface import provider
class ITodo(model.Schema):
title = schema.TextLine(
title=u"Title",
required=False,
description=u"It's a title",
default=u''
)
done = schema.Bool(
title=u"Done",
required=False,
description=u"Has the task been completed?",
default=False
)
class View(Service):
def __init__(self, context, request):
self.context = context
self.request = request
async def __call__(self):
return {
'context': str(self.context),
'portal_type': self.context.portal_type,
}
@provider(IFormFieldProvider)
class IDublinCore(IWriteZopeDublinCore):
""" We basically just want the IFormFieldProvider interface applied
There's probably a zcml way of doing this. """
@adapter(IDexterityContent)
class DublinCore(ZDCAnnotatableAdapter):
pass
|
29a964a64230e26fca550e81a1ecba3dd782dfb1 | python/vtd.py | python/vtd.py | import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
| import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
if 'my_system' not in globals():
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
my_system.Refresh()
| Refresh system instead of clobbering it | Refresh system instead of clobbering it
Otherwise, if we set the Contexts, they'll be gone before we can request the
NextActions!
| Python | apache-2.0 | chiphogg/vim-vtd | import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
+ if 'my_system' not in globals():
- my_system = libvtd.trusted_system.TrustedSystem()
+ my_system = libvtd.trusted_system.TrustedSystem()
- my_system.AddFile(file_name)
+ my_system.AddFile(file_name)
+ my_system.Refresh()
| Refresh system instead of clobbering it | ## Code Before:
import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
## Instruction:
Refresh system instead of clobbering it
## Code After:
import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
if 'my_system' not in globals():
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
my_system.Refresh()
|
b532ffff18e95b6014921d88b6df075e8ac2c4ec | problib/example1/__init__.py | problib/example1/__init__.py | from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers between 0 and 10.
root1 = r.randint(0,10)
root2 = r.randint(0,10)
root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
p = ((x-root1)*(x-root2)).expand(basic=True)
template_variables = {
'p': latex(p),
}
a1 = answer.Answer()
a1.value = cos(x)**2-sin(x)**2
a1.type = 'function'
a1.variables = ['x']
a1.domain = 'R'
a2 = answer.Answer()
a2.value = 'x+1'
a2.type = "function"
a2.variables = ['x','y']
answers = {
'ans1': a1,
'ans2': a2
}
| from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers between 0 and 10.
root1 = r.randint(0,10)
root2 = r.randint(0,10)
root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
p = ((x-root1)*(x-root2)).expand(basic=True)
func = cos(x)**2-sin(x)**2
a1 = answer.Answer(
value=func,
type='function',
vars=['x'])
a2 = answer.Answer(value='x+1',type='function',vars=['x'])
answers = {
'ans1': a1,
'ans2': a2
}
template_variables = {
'p': latex(p),
}
| Update mathdeck problib for new Answer refactoring | Update mathdeck problib for new Answer refactoring
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck | from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers between 0 and 10.
root1 = r.randint(0,10)
root2 = r.randint(0,10)
root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
p = ((x-root1)*(x-root2)).expand(basic=True)
+ func = cos(x)**2-sin(x)**2
- template_variables = {
- 'p': latex(p),
- }
- a1 = answer.Answer()
+ a1 = answer.Answer(
+ value=func,
+ type='function',
+ vars=['x'])
+ a2 = answer.Answer(value='x+1',type='function',vars=['x'])
- a1.value = cos(x)**2-sin(x)**2
- a1.type = 'function'
- a1.variables = ['x']
- a1.domain = 'R'
-
- a2 = answer.Answer()
- a2.value = 'x+1'
- a2.type = "function"
- a2.variables = ['x','y']
answers = {
'ans1': a1,
'ans2': a2
}
+ template_variables = {
+ 'p': latex(p),
+ }
+ | Update mathdeck problib for new Answer refactoring | ## Code Before:
from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers between 0 and 10.
root1 = r.randint(0,10)
root2 = r.randint(0,10)
root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
p = ((x-root1)*(x-root2)).expand(basic=True)
template_variables = {
'p': latex(p),
}
a1 = answer.Answer()
a1.value = cos(x)**2-sin(x)**2
a1.type = 'function'
a1.variables = ['x']
a1.domain = 'R'
a2 = answer.Answer()
a2.value = 'x+1'
a2.type = "function"
a2.variables = ['x','y']
answers = {
'ans1': a1,
'ans2': a2
}
## Instruction:
Update mathdeck problib for new Answer refactoring
## Code After:
from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers between 0 and 10.
root1 = r.randint(0,10)
root2 = r.randint(0,10)
root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
p = ((x-root1)*(x-root2)).expand(basic=True)
func = cos(x)**2-sin(x)**2
a1 = answer.Answer(
value=func,
type='function',
vars=['x'])
a2 = answer.Answer(value='x+1',type='function',vars=['x'])
answers = {
'ans1': a1,
'ans2': a2
}
template_variables = {
'p': latex(p),
}
|
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | migrations: Fix zulipinternal migration corner case.
It's theoretically possible to have configured a Zulip server where
the system bots live in the same realm as normal users (and may have
in fact been the default in early Zulip releases? Unclear.). We
should handle these without the migration intended to clean up naming
for the system bot realm crashing.
Fixes #13660.
| Python | apache-2.0 | brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,zulip/zulip,kou/zulip,showell/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,rht/zulip,hackerkid/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,kou/zulip,synicalsyntax/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,kou/zulip,punchagan/zulip,synicalsyntax/zulip,rht/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
+ return
+ if not Realm.objects.filter(string_id="zulip").exists():
+ # If the user renamed the `zulip` system bot realm (or deleted
+ # it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | ## Code Before:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
## Instruction:
Fix zulipinternal migration corner case.
## Code After:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
|
97e3b202bbe6726a4056facb8b4690b0710029a9 | handroll/tests/test_site.py | handroll/tests/test_site.py |
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, 'template.html'), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_finds_valid_site_root_from_conf(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, Site.CONFIG), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_site_has_absolute_path(self):
original = os.getcwd()
tempdir = tempfile.mkdtemp()
site_path = os.path.join(tempdir, 'site')
os.mkdir(site_path)
os.chdir(tempdir)
site = Site('site')
self.assertEqual(site_path, site.path)
os.chdir(original)
|
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, 'template.html'), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_finds_valid_site_root_from_conf(self):
original = os.getcwd()
valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, Site.CONFIG), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_site_has_absolute_path(self):
original = os.getcwd()
tempdir = os.path.realpath(tempfile.mkdtemp())
site_path = os.path.join(tempdir, 'site')
os.mkdir(site_path)
os.chdir(tempdir)
site = Site('site')
self.assertEqual(site_path, site.path)
os.chdir(original)
| Use a real path when testing sites. | Use a real path when testing sites.
Mac OS X returns link paths when calling `mkdtemp`. Calling realpath
allows the site path comparison to be consistent across platforms.
| Python | bsd-2-clause | handroll/handroll |
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
- valid_site = tempfile.mkdtemp()
+ valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, 'template.html'), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_finds_valid_site_root_from_conf(self):
original = os.getcwd()
- valid_site = tempfile.mkdtemp()
+ valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, Site.CONFIG), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_site_has_absolute_path(self):
original = os.getcwd()
- tempdir = tempfile.mkdtemp()
+ tempdir = os.path.realpath(tempfile.mkdtemp())
site_path = os.path.join(tempdir, 'site')
os.mkdir(site_path)
os.chdir(tempdir)
site = Site('site')
self.assertEqual(site_path, site.path)
os.chdir(original)
| Use a real path when testing sites. | ## Code Before:
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, 'template.html'), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_finds_valid_site_root_from_conf(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, Site.CONFIG), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_site_has_absolute_path(self):
original = os.getcwd()
tempdir = tempfile.mkdtemp()
site_path = os.path.join(tempdir, 'site')
os.mkdir(site_path)
os.chdir(tempdir)
site = Site('site')
self.assertEqual(site_path, site.path)
os.chdir(original)
## Instruction:
Use a real path when testing sites.
## Code After:
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, 'template.html'), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_finds_valid_site_root_from_conf(self):
original = os.getcwd()
valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, Site.CONFIG), 'w').close()
os.chdir(valid_site)
site = Site()
self.assertEqual(valid_site, site.path)
os.chdir(original)
def test_site_has_absolute_path(self):
original = os.getcwd()
tempdir = os.path.realpath(tempfile.mkdtemp())
site_path = os.path.join(tempdir, 'site')
os.mkdir(site_path)
os.chdir(tempdir)
site = Site('site')
self.assertEqual(site_path, site.path)
os.chdir(original)
|
7e44a8bd38105144111624710819a1ee54891222 | campos_checkin/__openerp__.py | campos_checkin/__openerp__.py |
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
'campos_crewnet',
'web_ir_actions_act_window_message',
#'web_tree_dynamic_colored_field',
],
'data': [
'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
'wizards/campos_checkin_wiz.xml',
'security/campos_checkin.xml',
'views/campos_event_participant.xml',
'views/campos_mat_report.xml',
],
'demo': [
],
}
|
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
'campos_crewnet',
'web_ir_actions_act_window_message',
#'web_tree_dynamic_colored_field',
],
'data': [
'wizards/campos_checkin_wiz.xml',
'security/campos_checkin.xml',
'views/campos_event_participant.xml',
'views/campos_mat_report.xml',
'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
],
'demo': [
],
}
| Fix order for menu ref | Fix order for menu ref | Python | agpl-3.0 | sl2017/campos |
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
'campos_crewnet',
'web_ir_actions_act_window_message',
#'web_tree_dynamic_colored_field',
],
'data': [
- 'wizards/campos_checkin_grp_wiz.xml',
- 'views/event_registration.xml',
'wizards/campos_checkin_wiz.xml',
'security/campos_checkin.xml',
'views/campos_event_participant.xml',
'views/campos_mat_report.xml',
+ 'wizards/campos_checkin_grp_wiz.xml',
+ 'views/event_registration.xml',
],
'demo': [
],
}
| Fix order for menu ref | ## Code Before:
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
'campos_crewnet',
'web_ir_actions_act_window_message',
#'web_tree_dynamic_colored_field',
],
'data': [
'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
'wizards/campos_checkin_wiz.xml',
'security/campos_checkin.xml',
'views/campos_event_participant.xml',
'views/campos_mat_report.xml',
],
'demo': [
],
}
## Instruction:
Fix order for menu ref
## Code After:
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
'campos_crewnet',
'web_ir_actions_act_window_message',
#'web_tree_dynamic_colored_field',
],
'data': [
'wizards/campos_checkin_wiz.xml',
'security/campos_checkin.xml',
'views/campos_event_participant.xml',
'views/campos_mat_report.xml',
'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
],
'demo': [
],
}
|
3cd99c23099a625da711e3ac458a46a7b364d83c | hystrix/pool.py | hystrix/pool.py | from __future__ import absolute_import
from concurrent.futures import ThreadPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls.__blacklist__:
return super(PoolMetaclass, cls).__new__(cls, name,
bases, attrs)
pool_key = attrs.get('pool_key') or '{}Pool'.format(name)
new_class = super(PoolMetaclass, cls).__new__(cls, pool_key,
bases, attrs)
setattr(new_class, 'pool_key', pool_key)
if pool_key not in cls.__instances__:
cls.__instances__[pool_key] = new_class
return cls.__instances__[pool_key]
class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)):
pool_key = None
def __init__(self, pool_key=None, max_workers=5):
super(Pool, self).__init__(max_workers)
| from __future__ import absolute_import
from concurrent.futures import ProcessPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls.__blacklist__:
return super(PoolMetaclass, cls).__new__(cls, name,
bases, attrs)
pool_key = attrs.get('pool_key') or '{}Pool'.format(name)
new_class = super(PoolMetaclass, cls).__new__(cls, pool_key,
bases, attrs)
setattr(new_class, 'pool_key', pool_key)
if pool_key not in cls.__instances__:
cls.__instances__[pool_key] = new_class
return cls.__instances__[pool_key]
class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)):
pool_key = None
def __init__(self, pool_key=None, max_workers=5):
super(Pool, self).__init__(max_workers)
| Change Pool to use ProcessPoolExecutor | Change Pool to use ProcessPoolExecutor
| Python | apache-2.0 | wiliamsouza/hystrix-py,wiliamsouza/hystrix-py | from __future__ import absolute_import
- from concurrent.futures import ThreadPoolExecutor
+ from concurrent.futures import ProcessPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls.__blacklist__:
return super(PoolMetaclass, cls).__new__(cls, name,
bases, attrs)
pool_key = attrs.get('pool_key') or '{}Pool'.format(name)
new_class = super(PoolMetaclass, cls).__new__(cls, pool_key,
bases, attrs)
setattr(new_class, 'pool_key', pool_key)
if pool_key not in cls.__instances__:
cls.__instances__[pool_key] = new_class
return cls.__instances__[pool_key]
- class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)):
+ class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)):
pool_key = None
def __init__(self, pool_key=None, max_workers=5):
super(Pool, self).__init__(max_workers)
| Change Pool to use ProcessPoolExecutor | ## Code Before:
from __future__ import absolute_import
from concurrent.futures import ThreadPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls.__blacklist__:
return super(PoolMetaclass, cls).__new__(cls, name,
bases, attrs)
pool_key = attrs.get('pool_key') or '{}Pool'.format(name)
new_class = super(PoolMetaclass, cls).__new__(cls, pool_key,
bases, attrs)
setattr(new_class, 'pool_key', pool_key)
if pool_key not in cls.__instances__:
cls.__instances__[pool_key] = new_class
return cls.__instances__[pool_key]
class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)):
pool_key = None
def __init__(self, pool_key=None, max_workers=5):
super(Pool, self).__init__(max_workers)
## Instruction:
Change Pool to use ProcessPoolExecutor
## Code After:
from __future__ import absolute_import
from concurrent.futures import ProcessPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls.__blacklist__:
return super(PoolMetaclass, cls).__new__(cls, name,
bases, attrs)
pool_key = attrs.get('pool_key') or '{}Pool'.format(name)
new_class = super(PoolMetaclass, cls).__new__(cls, pool_key,
bases, attrs)
setattr(new_class, 'pool_key', pool_key)
if pool_key not in cls.__instances__:
cls.__instances__[pool_key] = new_class
return cls.__instances__[pool_key]
class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)):
pool_key = None
def __init__(self, pool_key=None, max_workers=5):
super(Pool, self).__init__(max_workers)
|
c52edc120f38acb079fa364cdb684fc2052d4727 | corehq/messaging/smsbackends/trumpia/urls.py | corehq/messaging/smsbackends/trumpia/urls.py | from django.conf.urls import url
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
name=TrumpiaIncomingView.urlname),
]
| from django.conf.urls import url
from corehq.apps.hqwebapp.decorators import waf_allow
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()),
name=TrumpiaIncomingView.urlname),
]
| Annotate trumpia url to say it allows XML in the querystring | Annotate trumpia url to say it allows XML in the querystring
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.conf.urls import url
+
+ from corehq.apps.hqwebapp.decorators import waf_allow
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
- url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
+ url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()),
name=TrumpiaIncomingView.urlname),
]
| Annotate trumpia url to say it allows XML in the querystring | ## Code Before:
from django.conf.urls import url
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
name=TrumpiaIncomingView.urlname),
]
## Instruction:
Annotate trumpia url to say it allows XML in the querystring
## Code After:
from django.conf.urls import url
from corehq.apps.hqwebapp.decorators import waf_allow
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()),
name=TrumpiaIncomingView.urlname),
]
|
d159f8201b9d9aeafd24f07a9e39855fc537182d | cocoscore/tools/data_tools.py | cocoscore/tools/data_tools.py | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
| import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the second-to-last column
:param match_distance: if True, the distance between the closest match is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
if match_distance:
column_names.append('distance')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
| Add match_distance flag to load_data_frame() | Add match_distance flag to load_data_frame()
| Python | mit | JungeAlexander/cocoscore | import pandas as pd
- def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
+ def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
- :param class_labels: if True, the class label is assumed to be present as the last column
+ :param class_labels: if True, the class label is assumed to be present as the second-to-last column
+ :param match_distance: if True, the distance between the closest match is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
+ if match_distance:
+ column_names.append('distance')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
| Add match_distance flag to load_data_frame() | ## Code Before:
import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
## Instruction:
Add match_distance flag to load_data_frame()
## Code After:
import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the second-to-last column
:param match_distance: if True, the distance between the closest match is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
if match_distance:
column_names.append('distance')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
|
920e2fbb7e99c17dbe8d5b71e9c9b26a718ca444 | ideascube/search/apps.py | ideascube/search/apps.py | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
if isinstance(sender, SearchConfig):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
Django run (pre|post)_migrate script once per database.
As we have two databases, the create_index is launch twice with different
kwargs['using'] ('default' and 'transient'). We should try to create
the index table only when we are working on the transient database.
Most of the time, this is not important and create a new index table
twice is not important.
However, if we run tests, the database are configured and migrate
one after the other and the 'transient' database may be miss-configured
at a time. By creating the table only at the right time, we ensure that
everything is properly configured.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | ## Code Before:
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
if isinstance(sender, SearchConfig):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
## Instruction:
Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
## Code After:
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
|
360efe51bc45f189c235bed6b2b7bfdd4fd1bfbd | flask-restful/api.py | flask-restful/api.py | from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(self):
args = parser.parse_args()
txt = args['txt']
rp = reach.process_text(txt, offline=False)
st = rp.statements
json_statements = {}
json_statements['statements'] = []
for s in st:
s_json = s.to_json()
json_statements['statements'].append(s_json)
json_statements = json.dumps(json_statements)
return json_statements, 201
api.add_resource(InputText, '/parse')
class InputStmtJSON(Resource):
def post(self):
args = parser.parse_args()
print(args)
json_data = args['json']
json_dict = json.loads(json_data)
st = []
for j in json_dict['statements']:
s = Statement.from_json(j)
print(s)
st.append(s)
return 201
api.add_resource(InputStmtJSON, '/load')
if __name__ == '__main__':
app.run(debug=True)
| import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
| Reimplement using bottle and add 3 endpoints | Reimplement using bottle and add 3 endpoints
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra | - from flask import Flask, request
- from flask_restful import Resource, Api, reqparse
- from indra import reach
+ import json
+ from bottle import route, run, request, post, default_app
+ from indra import trips, reach, bel, biopax
from indra.statements import *
- import json
- app = Flask(__name__)
- api = Api(app)
- parser = reqparse.RequestParser()
- parser.add_argument('txt')
- parser.add_argument('json')
- class InputText(Resource):
- def post(self):
- args = parser.parse_args()
- txt = args['txt']
- rp = reach.process_text(txt, offline=False)
- st = rp.statements
- json_statements = {}
- json_statements['statements'] = []
- for s in st:
- s_json = s.to_json()
- json_statements['statements'].append(s_json)
- json_statements = json.dumps(json_statements)
- return json_statements, 201
+ @route('/trips/process_text', method='POST')
+ def trips_process_text():
+ body = json.load(request.body)
+ text = body.get('text')
+ tp = trips.process_text(text)
+ if tp and tp.statements:
+ stmts = json.dumps([json.loads(st.to_json()) for st
+ in tp.statements])
+ res = {'statements': stmts}
+ return res
+ else:
+ res = {'statements': []}
+ return res
- api.add_resource(InputText, '/parse')
+ @route('/reach/process_text', method='POST')
+ def reach_process_text():
+ body = json.load(request.body)
+ text = body.get('text')
+ rp = reach.process_text(text)
+ if rp and rp.statements:
+ stmts = json.dumps([json.loads(st.to_json()) for st
+ in rp.statements])
+ res = {'statements': stmts}
- class InputStmtJSON(Resource):
- def post(self):
- args = parser.parse_args()
- print(args)
- json_data = args['json']
- json_dict = json.loads(json_data)
- st = []
- for j in json_dict['statements']:
- s = Statement.from_json(j)
- print(s)
- st.append(s)
- return 201
+ return res
+ else:
+ res = {'statements': []}
+ return res
- api.add_resource(InputStmtJSON, '/load')
+
+ @route('/reach/process_pmc', method='POST')
+ def reach_process_pmc():
+ body = json.load(request.body)
+ pmcid = body.get('pmcid')
+ rp = reach.process_pmc(pmcid)
+ if rp and rp.statements:
+ stmts = json.dumps([json.loads(st.to_json()) for st
+ in rp.statements])
+ res = {'statements': stmts}
+ return res
+ else:
+ res = {'statements': []}
+ return res
+
if __name__ == '__main__':
- app.run(debug=True)
+ app = default_app()
+ run(app)
| Reimplement using bottle and add 3 endpoints | ## Code Before:
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(self):
args = parser.parse_args()
txt = args['txt']
rp = reach.process_text(txt, offline=False)
st = rp.statements
json_statements = {}
json_statements['statements'] = []
for s in st:
s_json = s.to_json()
json_statements['statements'].append(s_json)
json_statements = json.dumps(json_statements)
return json_statements, 201
api.add_resource(InputText, '/parse')
class InputStmtJSON(Resource):
def post(self):
args = parser.parse_args()
print(args)
json_data = args['json']
json_dict = json.loads(json_data)
st = []
for j in json_dict['statements']:
s = Statement.from_json(j)
print(s)
st.append(s)
return 201
api.add_resource(InputStmtJSON, '/load')
if __name__ == '__main__':
app.run(debug=True)
## Instruction:
Reimplement using bottle and add 3 endpoints
## Code After:
import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
|
e78910c8b9ecf48f96a693dae3c15afa32a12da1 | casexml/apps/phone/views.py | casexml/apps/phone/views.py | from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
from django.http import HttpResponse
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
| from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
| Revert "moving httpresponse to view" | Revert "moving httpresponse to view"
This reverts commit a6f501bb9de6382e35372996851916adac067fa0.
| Python | bsd-3-clause | SEL-Columbia/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq | + from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
- from django.http import HttpResponse
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
| Revert "moving httpresponse to view" | ## Code Before:
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
from django.http import HttpResponse
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
## Instruction:
Revert "moving httpresponse to view"
## Code After:
from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User.from_django_user(request.user)
restore_id = request.GET.get('since')
return generate_restore_response(user, restore_id)
def xml_for_case(request, case_id, version="1.0"):
"""
Test view to get the xml for a particular case
"""
case = CommCareCase.get(case_id)
return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
const.CASE_ACTION_UPDATE],
version), mimetype="text/xml")
|
63f6e4d50116d5ca2bfc82c1c608e08040055b5e | subdue/core/__init__.py | subdue/core/__init__.py | __all__ = [
'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
| __all__ = [
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
| Remove old exports from subdue.core | Remove old exports from subdue.core
| Python | mit | jdevera/subdue | __all__ = [
- 'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
- 'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
| Remove old exports from subdue.core | ## Code Before:
__all__ = [
'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
## Instruction:
Remove old exports from subdue.core
## Code After:
__all__ = [
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
|
459bf08b9fe4ae5a879a138bd2497abb23bf5910 | modules/expansion/cve.py | modules/expansion/cve.py | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
return vulnerability
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
| import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
if vulnerability.get('summary'):
summary = vulnerability['summary']
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
| Return a text attribute for an hover only module | Return a text attribute for an hover only module
| Python | agpl-3.0 | VirusTotal/misp-modules,MISP/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,Rafiot/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules | import json
import requests
misperrors = {'error': 'Error'}
- mispattributes = {'input': ['vulnerability'], 'output': ['']}
+ mispattributes = {'input': ['vulnerability'], 'output': ['text']}
- moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
+ moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
+ if vulnerability.get('summary'):
+ summary = vulnerability['summary']
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
- return vulnerability
+ r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
+ return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
| Return a text attribute for an hover only module | ## Code Before:
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
return vulnerability
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
## Instruction:
Return a text attribute for an hover only module
## Code After:
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_url = 'https://cve.circl.lu/api/cve/'
def handler(q=False):
if q is False:
return False
print (q)
request = json.loads(q)
if not request.get('vulnerability'):
misperrors['error'] = 'Vulnerability id missing'
return misperrors
r = requests.get(cveapi_url+request.get('vulnerability'))
if r.status_code == 200:
vulnerability = json.loads(r.text)
if vulnerability.get('summary'):
summary = vulnerability['summary']
else:
misperrors['error'] = 'cve.circl.lu API not accessible'
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
03380a1042443465d6f1d74afb5fd120dbc3379b | manage.py | manage.py | from manager import Manager
manager = Manager()
@manager.command
def build(threads=1):
print("Starting a build with %d threads ..." % threads)
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
| from manager import Manager
from multiprocessing import Pool
manager = Manager()
def func(period):
from time import sleep
sleep(period)
@manager.command
def build(threads=1):
pool = Pool(threads)
print("Starting a build with %d threads ..." % threads)
pool.map(func, [1, 1, 1, 1, 1])
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
| Add parallelizing code to build | Add parallelizing code to build
| Python | mit | tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website | from manager import Manager
+ from multiprocessing import Pool
manager = Manager()
+ def func(period):
+ from time import sleep
+ sleep(period)
+
+
@manager.command
def build(threads=1):
+ pool = Pool(threads)
print("Starting a build with %d threads ..." % threads)
+ pool.map(func, [1, 1, 1, 1, 1])
+
@manager.command
def clean():
pass
+
if __name__ == '__main__':
manager.main()
| Add parallelizing code to build | ## Code Before:
from manager import Manager
manager = Manager()
@manager.command
def build(threads=1):
print("Starting a build with %d threads ..." % threads)
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
## Instruction:
Add parallelizing code to build
## Code After:
from manager import Manager
from multiprocessing import Pool
manager = Manager()
def func(period):
from time import sleep
sleep(period)
@manager.command
def build(threads=1):
pool = Pool(threads)
print("Starting a build with %d threads ..." % threads)
pool.map(func, [1, 1, 1, 1, 1])
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
|
a5003b6f45d262923a1c00bd9a9c1addb3854178 | lapostesdk/apis/apibase.py | lapostesdk/apis/apibase.py | import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
'product': self.product,
'version': self.version}
self.headers = {'X-Okapi-Key': api_key}
def get(self, resource, params={}):
response = self._get(resource, params)
if self.entity is None:
return response
module = import_module('lapostesdk.entities')
obj = getattr(module, self.entity)
instance = obj()
instance.hydrate(response)
return instance
def _get(self, resource, params={}):
r = requests.get(self.api_url + resource, params=params, headers=self.headers)
return r.json()
| import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
'product': self.product,
'version': self.version}
self.headers = {'X-Okapi-Key': api_key}
def get(self, resource, params={}):
response = self._get(resource, params)
if self.entity is None:
return response
return self.create_object(response, self.entity)
def _get(self, resource, params={}):
r = requests.get(self.api_url + resource, params=params, headers=self.headers)
return r.json()
def create_object(self, response, entity):
module = import_module('lapostesdk.entities')
obj = getattr(module, self.entity)
instance = obj()
instance.hydrate(response)
return instance
| Move object creation outside of get method | Move object creation outside of get method
| Python | mit | geelweb/laposte-python-sdk | import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
'product': self.product,
'version': self.version}
self.headers = {'X-Okapi-Key': api_key}
def get(self, resource, params={}):
response = self._get(resource, params)
if self.entity is None:
return response
+ return self.create_object(response, self.entity)
+
+ def _get(self, resource, params={}):
+ r = requests.get(self.api_url + resource, params=params, headers=self.headers)
+ return r.json()
+
+ def create_object(self, response, entity):
module = import_module('lapostesdk.entities')
obj = getattr(module, self.entity)
instance = obj()
instance.hydrate(response)
return instance
- def _get(self, resource, params={}):
- r = requests.get(self.api_url + resource, params=params, headers=self.headers)
- return r.json()
| Move object creation outside of get method | ## Code Before:
import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
'product': self.product,
'version': self.version}
self.headers = {'X-Okapi-Key': api_key}
def get(self, resource, params={}):
response = self._get(resource, params)
if self.entity is None:
return response
module = import_module('lapostesdk.entities')
obj = getattr(module, self.entity)
instance = obj()
instance.hydrate(response)
return instance
def _get(self, resource, params={}):
r = requests.get(self.api_url + resource, params=params, headers=self.headers)
return r.json()
## Instruction:
Move object creation outside of get method
## Code After:
import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
'product': self.product,
'version': self.version}
self.headers = {'X-Okapi-Key': api_key}
def get(self, resource, params={}):
response = self._get(resource, params)
if self.entity is None:
return response
return self.create_object(response, self.entity)
def _get(self, resource, params={}):
r = requests.get(self.api_url + resource, params=params, headers=self.headers)
return r.json()
def create_object(self, response, entity):
module = import_module('lapostesdk.entities')
obj = getattr(module, self.entity)
instance = obj()
instance.hydrate(response)
return instance
|
1b385ce127f0a1802b0effa0054b44f58b3317b0 | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py | from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
re_path(
r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| from django.contrib.auth import views
from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
r"account/reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| Fix webapp password reset link | DEVOPS-42: Fix webapp password reset link
| Python | isc | thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template | from django.contrib.auth import views
- from django.urls import path, re_path
+ from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
- re_path(
+ path(
- r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
+ r"account/reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| Fix webapp password reset link | ## Code Before:
from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
re_path(
r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
## Instruction:
Fix webapp password reset link
## Code After:
from django.contrib.auth import views
from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
r"account/reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
|
9b10f600b5611380f72fe2aeacfe2ee6f02e4e3a | kicad_footprint_load.py | kicad_footprint_load.py | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
#Ignore paths with unicode as KiCad can't deal with them in enumerate
list_of_footprints = src_plugin.FootprintEnumerate(libpath, False)
| import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
list_of_footprints = src_plugin.FootprintEnumerate(libpath)
| Switch to old invocation of FootprintEnumerate | Switch to old invocation of FootprintEnumerate
| Python | mit | monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
- #Ignore paths with unicode as KiCad can't deal with them in enumerate
- list_of_footprints = src_plugin.FootprintEnumerate(libpath, False)
+ list_of_footprints = src_plugin.FootprintEnumerate(libpath)
| Switch to old invocation of FootprintEnumerate | ## Code Before:
import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
#Ignore paths with unicode as KiCad can't deal with them in enumerate
list_of_footprints = src_plugin.FootprintEnumerate(libpath, False)
## Instruction:
Switch to old invocation of FootprintEnumerate
## Code After:
import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
list_of_footprints = src_plugin.FootprintEnumerate(libpath)
|
f5fd283497afb5030632108ce692e8acde526188 | datalake_ingester/reporter.py | datalake_ingester/reporter.py | import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
raise InsufficientConfiguration('Please configure a report_key')
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
| import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
return None
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
| Allow the ingester to work without a report key | Allow the ingester to work without a report key
| Python | apache-2.0 | planetlabs/datalake-ingester,planetlabs/atl,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake | import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
- from datalake_common.errors import InsufficientConfiguration
-
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
- raise InsufficientConfiguration('Please configure a report_key')
+ return None
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
| Allow the ingester to work without a report key | ## Code Before:
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
raise InsufficientConfiguration('Please configure a report_key')
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
## Instruction:
Allow the ingester to work without a report key
## Code After:
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@classmethod
def from_config(cls):
report_key = os.environ.get('DATALAKE_REPORT_KEY')
if report_key is None:
return None
return cls(report_key)
@property
def _log_name(self):
return self.report_key.split(':')[-1]
@memoized_property
def _connection(self):
region = os.environ.get('AWS_REGION')
if region:
return boto.sns.connect_to_region(region)
else:
return boto.connect_sns()
def report(self, ingestion_report):
message = json.dumps(ingestion_report)
self.logger.info('REPORTING: %s', message)
self._connection.publish(topic=self.report_key, message=message)
|
f45fc8854647754b24df5f9601920368cd2d3c49 | tests/chainerx_tests/unit_tests/test_cuda.py | tests/chainerx_tests/unit_tests/test_cuda.py | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
| import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
| Add safety checks in test | Add safety checks in test
| Python | mit | wkentaro/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,pfnet/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,wkentaro/chainer | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
+ assert used_bytes > 0
+ assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
| Add safety checks in test | ## Code Before:
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
## Instruction:
Add safety checks in test
## Code After:
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs):
self.acquired_bytes += kwargs['mem_size']
def malloc_preprocess(self, **kwargs):
self.used_bytes += kwargs['mem_size']
@pytest.mark.cuda()
def test_cupy_share_allocator():
with CupyTestMemoryHook() as hook:
cp_allocated = cupy.arange(10)
used_bytes = hook.used_bytes
acquired_bytes = hook.acquired_bytes
assert used_bytes > 0
assert acquired_bytes > 0
# Create a new array after changing the allocator to the memory pool
# of ChainerX and make sure that no additional memory has been
# allocated by CuPy.
_cuda.cupy_share_allocator()
chx_allocated = cupy.arange(10)
cupy.testing.assert_array_equal(cp_allocated, chx_allocated)
assert used_bytes == hook.used_bytes
assert acquired_bytes == hook.acquired_bytes
|
429f38497da0fd520e5bc5bd82e6d4ed5a405521 | real_estate_agency/real_estate_agency/views.py | real_estate_agency/real_estate_agency/views.py | from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requests to DB
feedbacks = Feedback.objects.all()[:4].select_related().prefetch_related('social_media_links')
# Only 2 requests to DB
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True).prefetch_related('type_of_complex')
context = {
'feedbacks': feedbacks,
'form': SearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
| from django.shortcuts import render
from new_buildings.models import ResidentalComplex
from new_buildings.forms import NewBuildingsSearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requests to DB
feedbacks = Feedback.objects.all(
)[:4].select_related().prefetch_related('social_media_links')
# Only 2 requests to DB
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True).prefetch_related('type_of_complex')
context = {
'feedbacks': feedbacks,
'form': NewBuildingsSearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
| Use NewBuildingsSearchForm as main page search form. | Use NewBuildingsSearchForm as main page search form.
intead of non-complete SearchForm.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency | - from django.shortcuts import render, render_to_response
+ from django.shortcuts import render
- from django.template import RequestContext
- from new_buildings.models import Builder, ResidentalComplex, NewApartment
+ from new_buildings.models import ResidentalComplex
- from new_buildings.forms import SearchForm
+ from new_buildings.forms import NewBuildingsSearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requests to DB
+ feedbacks = Feedback.objects.all(
- feedbacks = Feedback.objects.all()[:4].select_related().prefetch_related('social_media_links')
+ )[:4].select_related().prefetch_related('social_media_links')
# Only 2 requests to DB
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True).prefetch_related('type_of_complex')
context = {
'feedbacks': feedbacks,
- 'form': SearchForm,
+ 'form': NewBuildingsSearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
| Use NewBuildingsSearchForm as main page search form. | ## Code Before:
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requests to DB
feedbacks = Feedback.objects.all()[:4].select_related().prefetch_related('social_media_links')
# Only 2 requests to DB
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True).prefetch_related('type_of_complex')
context = {
'feedbacks': feedbacks,
'form': SearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
## Instruction:
Use NewBuildingsSearchForm as main page search form.
## Code After:
from django.shortcuts import render
from new_buildings.models import ResidentalComplex
from new_buildings.forms import NewBuildingsSearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requests to DB
feedbacks = Feedback.objects.all(
)[:4].select_related().prefetch_related('social_media_links')
# Only 2 requests to DB
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True).prefetch_related('type_of_complex')
context = {
'feedbacks': feedbacks,
'form': NewBuildingsSearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
|
fe317230b6d2636b8a736c63be7769dd82663914 | libraries/SwitchManager.py | libraries/SwitchManager.py | class SwitchManager(object):
def extract_all_nodes(self, content):
return [e['node'] for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
| class SwitchManager(object):
def extract_all_nodes(self, content):
"""
Return all nodes.
"""
if isinstance(content,dict) or not content.has_key('nodeProperties'):
return None
else:
return [e.get('node') for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
| Add input check when getting all nodes. | Add input check when getting all nodes.
| Python | epl-1.0 | yeasy/robot_tool | class SwitchManager(object):
def extract_all_nodes(self, content):
+ """
+ Return all nodes.
+ """
+ if isinstance(content,dict) or not content.has_key('nodeProperties'):
+ return None
+ else:
- return [e['node'] for e in content['nodeProperties']]
+ return [e.get('node') for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
| Add input check when getting all nodes. | ## Code Before:
class SwitchManager(object):
def extract_all_nodes(self, content):
return [e['node'] for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
## Instruction:
Add input check when getting all nodes.
## Code After:
class SwitchManager(object):
def extract_all_nodes(self, content):
"""
Return all nodes.
"""
if isinstance(content,dict) or not content.has_key('nodeProperties'):
return None
else:
return [e.get('node') for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
|
99177cdc64bdec740557007800b610bff07ce46a | shivyc.py | shivyc.py |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of the C file to compile. The file name gets saved to the
# file_name attribute of the returned object, but this parameter appears as
# "filename" (no underscore) on the command line.
parser.add_argument("file_name", metavar="filename")
return parser.parse_args()
def compile_code(source: str) -> str:
"""Compile the provided source code into assembly.
source - The C source code to compile.
return - The asm output
"""
return source
def main():
"""Load the input files, and dispatch to the compile function for the main
processing.
"""
arguments = get_arguments()
try:
c_file = open(arguments.file_name)
except IOError:
print("shivyc: error: no such file or directory: '{}'"
.format(arguments.file_name))
else:
compile_code(c_file.read())
c_file.close()
if __name__ == "__main__":
main()
|
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of the C file to compile. The file name gets saved to the
# file_name attribute of the returned object, but this parameter appears as
# "filename" (no underscore) on the command line.
parser.add_argument("file_name", metavar="filename")
return parser.parse_args()
def compile_code(source: str) -> str:
"""Compile the provided source code into assembly.
source - The C source code to compile.
return - The asm output
"""
return source
def main():
"""Load the input files and dispatch to the compile function for the main
processing.
The main function handles interfacing with the user, like reading the
command line arguments, printing errors, and generating output files. The
compilation logic is in the compile_code function to facilitate testing.
"""
arguments = get_arguments()
try:
c_file = open(arguments.file_name)
except IOError:
print("shivyc: error: no such file or directory: '{}'"
.format(arguments.file_name))
else:
compile_code(c_file.read())
c_file.close()
if __name__ == "__main__":
main()
| Improve commenting on main function | Improve commenting on main function
| Python | mit | ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of the C file to compile. The file name gets saved to the
# file_name attribute of the returned object, but this parameter appears as
# "filename" (no underscore) on the command line.
parser.add_argument("file_name", metavar="filename")
return parser.parse_args()
def compile_code(source: str) -> str:
"""Compile the provided source code into assembly.
source - The C source code to compile.
return - The asm output
"""
return source
def main():
- """Load the input files, and dispatch to the compile function for the main
+ """Load the input files and dispatch to the compile function for the main
processing.
+
+ The main function handles interfacing with the user, like reading the
+ command line arguments, printing errors, and generating output files. The
+ compilation logic is in the compile_code function to facilitate testing.
"""
arguments = get_arguments()
try:
c_file = open(arguments.file_name)
except IOError:
print("shivyc: error: no such file or directory: '{}'"
.format(arguments.file_name))
else:
compile_code(c_file.read())
c_file.close()
if __name__ == "__main__":
main()
| Improve commenting on main function | ## Code Before:
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of the C file to compile. The file name gets saved to the
# file_name attribute of the returned object, but this parameter appears as
# "filename" (no underscore) on the command line.
parser.add_argument("file_name", metavar="filename")
return parser.parse_args()
def compile_code(source: str) -> str:
"""Compile the provided source code into assembly.
source - The C source code to compile.
return - The asm output
"""
return source
def main():
"""Load the input files, and dispatch to the compile function for the main
processing.
"""
arguments = get_arguments()
try:
c_file = open(arguments.file_name)
except IOError:
print("shivyc: error: no such file or directory: '{}'"
.format(arguments.file_name))
else:
compile_code(c_file.read())
c_file.close()
if __name__ == "__main__":
main()
## Instruction:
Improve commenting on main function
## Code After:
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of the C file to compile. The file name gets saved to the
# file_name attribute of the returned object, but this parameter appears as
# "filename" (no underscore) on the command line.
parser.add_argument("file_name", metavar="filename")
return parser.parse_args()
def compile_code(source: str) -> str:
"""Compile the provided source code into assembly.
source - The C source code to compile.
return - The asm output
"""
return source
def main():
"""Load the input files and dispatch to the compile function for the main
processing.
The main function handles interfacing with the user, like reading the
command line arguments, printing errors, and generating output files. The
compilation logic is in the compile_code function to facilitate testing.
"""
arguments = get_arguments()
try:
c_file = open(arguments.file_name)
except IOError:
print("shivyc: error: no such file or directory: '{}'"
.format(arguments.file_name))
else:
compile_code(c_file.read())
c_file.close()
if __name__ == "__main__":
main()
|
a34c9628c3f383e7b6f5eb521a9493f2b51d8811 | plata/reporting/views.py | plata/reporting/views.py | from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
output = StringIO.StringIO()
workbook = plata.reporting.product.product_xls()
workbook.save(output)
response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=products.xls'
return response
@staff_member_required
def order_pdf(request, order_id):
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
order.shipping_cost = 8 / Decimal('1.076')
order.shipping_discount = 0
order.recalculate_total(save=False)
pdf, response = pdf_response('order-%09d' % order.id)
plata.reporting.order.order_pdf(pdf, order)
return response
| from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
output = StringIO.StringIO()
workbook = plata.reporting.product.product_xls()
workbook.save(output)
response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=products.xls'
return response
@staff_member_required
def order_pdf(request, order_id):
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('order-%09d' % order.id)
plata.reporting.order.order_pdf(pdf, order)
return response
| Remove hardcoded shipping modification in order PDF view | Remove hardcoded shipping modification in order PDF view
| Python | bsd-3-clause | stefanklug/plata,armicron/plata,armicron/plata,allink/plata,armicron/plata | from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
output = StringIO.StringIO()
workbook = plata.reporting.product.product_xls()
workbook.save(output)
response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=products.xls'
return response
@staff_member_required
def order_pdf(request, order_id):
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
- order.shipping_cost = 8 / Decimal('1.076')
- order.shipping_discount = 0
- order.recalculate_total(save=False)
-
pdf, response = pdf_response('order-%09d' % order.id)
plata.reporting.order.order_pdf(pdf, order)
return response
| Remove hardcoded shipping modification in order PDF view | ## Code Before:
from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
output = StringIO.StringIO()
workbook = plata.reporting.product.product_xls()
workbook.save(output)
response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=products.xls'
return response
@staff_member_required
def order_pdf(request, order_id):
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
order.shipping_cost = 8 / Decimal('1.076')
order.shipping_discount = 0
order.recalculate_total(save=False)
pdf, response = pdf_response('order-%09d' % order.id)
plata.reporting.order.order_pdf(pdf, order)
return response
## Instruction:
Remove hardcoded shipping modification in order PDF view
## Code After:
from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
output = StringIO.StringIO()
workbook = plata.reporting.product.product_xls()
workbook.save(output)
response = HttpResponse(output.getvalue(), mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=products.xls'
return response
@staff_member_required
def order_pdf(request, order_id):
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('order-%09d' % order.id)
plata.reporting.order.order_pdf(pdf, order)
return response
|
7b1a0022b41dbf17de352e4686458e5250b28e49 | quantityfield/widgets.py | quantityfield/widgets.py | import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=None, base_units=None, allowed_types=None):
choices = self.get_choices(allowed_types)
self.base_units = base_units
attrs = attrs or {}
attrs.setdefault('step', 'any')
widgets = (
NumberInput(attrs=attrs),
Select(attrs=attrs, choices=choices)
)
super(QuantityWidget, self).__init__(widgets, attrs)
def decompress(self, value):
non_decimal = re.compile(r'[^\d.]+')
if value:
number_value = non_decimal.sub('', str(value))
return [number_value, self.base_units]
return [None, self.base_units]
| import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=None, base_units=None, allowed_types=None):
choices = self.get_choices(allowed_types)
self.base_units = base_units
attrs = attrs or {}
attrs.setdefault('step', 'any')
widgets = (
NumberInput(attrs=attrs),
Select(attrs=attrs, choices=choices)
)
super(QuantityWidget, self).__init__(widgets, attrs)
def decompress(self, value):
non_decimal = re.compile(r'[^\d.]+')
if value:
number_value = non_decimal.sub('', str(value))
return [number_value, self.base_units]
return [None, self.base_units]
| Fix indentation error from conversion to spaces | Fix indentation error from conversion to spaces
| Python | mit | bharling/django-pint,bharling/django-pint | import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=None, base_units=None, allowed_types=None):
choices = self.get_choices(allowed_types)
self.base_units = base_units
attrs = attrs or {}
attrs.setdefault('step', 'any')
widgets = (
NumberInput(attrs=attrs),
Select(attrs=attrs, choices=choices)
)
super(QuantityWidget, self).__init__(widgets, attrs)
- def decompress(self, value):
+ def decompress(self, value):
- non_decimal = re.compile(r'[^\d.]+')
+ non_decimal = re.compile(r'[^\d.]+')
- if value:
+ if value:
- number_value = non_decimal.sub('', str(value))
+ number_value = non_decimal.sub('', str(value))
- return [number_value, self.base_units]
+ return [number_value, self.base_units]
- return [None, self.base_units]
+ return [None, self.base_units]
| Fix indentation error from conversion to spaces | ## Code Before:
import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=None, base_units=None, allowed_types=None):
choices = self.get_choices(allowed_types)
self.base_units = base_units
attrs = attrs or {}
attrs.setdefault('step', 'any')
widgets = (
NumberInput(attrs=attrs),
Select(attrs=attrs, choices=choices)
)
super(QuantityWidget, self).__init__(widgets, attrs)
def decompress(self, value):
non_decimal = re.compile(r'[^\d.]+')
if value:
number_value = non_decimal.sub('', str(value))
return [number_value, self.base_units]
return [None, self.base_units]
## Instruction:
Fix indentation error from conversion to spaces
## Code After:
import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=None, base_units=None, allowed_types=None):
choices = self.get_choices(allowed_types)
self.base_units = base_units
attrs = attrs or {}
attrs.setdefault('step', 'any')
widgets = (
NumberInput(attrs=attrs),
Select(attrs=attrs, choices=choices)
)
super(QuantityWidget, self).__init__(widgets, attrs)
def decompress(self, value):
non_decimal = re.compile(r'[^\d.]+')
if value:
number_value = non_decimal.sub('', str(value))
return [number_value, self.base_units]
return [None, self.base_units]
|
9ced61716167505875d3938ae01c08b61acc9392 | randterrainpy/terrain.py | randterrainpy/terrain.py | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
| """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
def __add__(self, other):
"""Add two terrains, height by height.
Args:
other (Terrain): Other terrain to add self to. Must have same dimensions as self.
Returns:
Terrain: Terrain of self and other added together.
"""
result = Terrain(self.width, self.length)
for i in range(self.width):
for j in range(self.length):
result[i, j] = self[i, j] + other[i, j]
return result
| Add addition method to Terrain | Add addition method to Terrain
| Python | mit | jackromo/RandTerrainPy | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
+ def __add__(self, other):
+ """Add two terrains, height by height.
+
+ Args:
+ other (Terrain): Other terrain to add self to. Must have same dimensions as self.
+
+ Returns:
+ Terrain: Terrain of self and other added together.
+
+ """
+ result = Terrain(self.width, self.length)
+ for i in range(self.width):
+ for j in range(self.length):
+ result[i, j] = self[i, j] + other[i, j]
+ return result
+ | Add addition method to Terrain | ## Code Before:
"""This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
## Instruction:
Add addition method to Terrain
## Code After:
"""This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map of heights of terrain. Values range from 0 to 1.
"""
def __init__(self, width, length):
"""Initializer for Terrain.
Args:
width (int): Width of terrain.
length (int): Height of terrain.
"""
self.width = width
self.length = length
self.height_map = [[0 for _ in self.width]] * self.length
def __getitem__(self, item):
"""Get an item at x-y coordinates.
Args:
item (tuple): 2-tuple of x and y coordinates.
Returns:
float: Height of terrain at coordinates, between 0 and 1.
"""
return self.height_map[item[1]][item[0]]
def __setitem__(self, key, value):
"""Set the height of an item.
Args:
key (tuple): 2-tuple of x and y coordinates.
value (float): New height of map at x and y coordinates, between 0 and 1.
"""
self.height_map[key[1]][key[0]] = value
def __add__(self, other):
"""Add two terrains, height by height.
Args:
other (Terrain): Other terrain to add self to. Must have same dimensions as self.
Returns:
Terrain: Terrain of self and other added together.
"""
result = Terrain(self.width, self.length)
for i in range(self.width):
for j in range(self.length):
result[i, j] = self[i, j] + other[i, j]
return result
|
2e845dfd2695b1913f4603d88039049fa1eef923 | repositories.py | repositories.py | repositories = [
{
"owner": "talk-to",
"name": "Knock"
}
] | REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] | Use capitalised name for constant | Use capitalised name for constant
| Python | mit | ayushgoel/LongShot | - repositories = [
+ REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] | Use capitalised name for constant | ## Code Before:
repositories = [
{
"owner": "talk-to",
"name": "Knock"
}
]
## Instruction:
Use capitalised name for constant
## Code After:
REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] |
aa7109d038a86f6a19a9fb4af96bd1199cd81330 | functest/opnfv_tests/openstack/snaps/snaps_utils.py | functest/opnfv_tests/openstack/snaps/snaps_utils.py |
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
|
from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the configured external network name or
the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
if (hasattr(CONST, 'EXTERNAL_NETWORK')):
extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK')
for ext_net in ext_nets:
if ext_net.name == extnet_config:
return extnet_config
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
| Support to specify the valid external network name | Support to specify the valid external network name
In some deployments, the retrieved external network by the
def get_external_networks in Snaps checked by "router:external"
is not available. So it is necessary to specify the available
external network as an env by user.
Change-Id: I333e91dd106ed307541a9a197280199fde86bd30
Signed-off-by: Linda Wang <[email protected]>
| Python | apache-2.0 | opnfv/functest,mywulin/functest,opnfv/functest,mywulin/functest | +
+ from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
- Returns the first external network name
+ Returns the configured external network name or
+ the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
+ if (hasattr(CONST, 'EXTERNAL_NETWORK')):
+ extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK')
+ for ext_net in ext_nets:
+ if ext_net.name == extnet_config:
+ return extnet_config
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
| Support to specify the valid external network name | ## Code Before:
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
## Instruction:
Support to specify the valid external network name
## Code After:
from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the configured external network name or
the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
if (hasattr(CONST, 'EXTERNAL_NETWORK')):
extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK')
for ext_net in ext_nets:
if ext_net.name == extnet_config:
return extnet_config
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
|
acd4238dce39464e99964227dca7758cffedca39 | gaphor/UML/classes/tests/test_containmentconnect.py | gaphor/UML/classes/tests/test_containmentconnect.py | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
| """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
def test_containment_package_class(create, diagram):
"""Test containment connecting to a package and a class."""
package = create(ContainmentItem, UML.Package)
line = create(ContainmentItem)
ac = create(ClassItem, UML.Class)
connect(line, line.head, package)
connect(line, line.tail, ac)
assert diagram.connections.get_connection(line.tail).connected is ac
assert len(package.subject.ownedElement) == 1
assert ac.subject in package.subject.ownedElement
| Add test for connecting containment to package and a class | Add test for connecting containment to package and a class [skip ci]
Signed-off-by: Dan Yeaw <[email protected]>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
- from gaphor.UML.classes import PackageItem
+ from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
+
+ def test_containment_package_class(create, diagram):
+ """Test containment connecting to a package and a class."""
+ package = create(ContainmentItem, UML.Package)
+ line = create(ContainmentItem)
+ ac = create(ClassItem, UML.Class)
+
+ connect(line, line.head, package)
+ connect(line, line.tail, ac)
+ assert diagram.connections.get_connection(line.tail).connected is ac
+ assert len(package.subject.ownedElement) == 1
+ assert ac.subject in package.subject.ownedElement
+ | Add test for connecting containment to package and a class | ## Code Before:
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
## Instruction:
Add test for connecting containment to package and a class
## Code After:
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two package items."""
pkg1 = create(PackageItem, UML.Package)
pkg2 = create(PackageItem, UML.Package)
containment = create(ContainmentItem)
glued = allow(containment, containment.head, pkg1)
assert glued
connect(containment, containment.head, pkg1)
glued = allow(containment, containment.tail, pkg2)
assert glued
def test_containment_package_class(create, diagram):
"""Test containment connecting to a package and a class."""
package = create(ContainmentItem, UML.Package)
line = create(ContainmentItem)
ac = create(ClassItem, UML.Class)
connect(line, line.head, package)
connect(line, line.tail, ac)
assert diagram.connections.get_connection(line.tail).connected is ac
assert len(package.subject.ownedElement) == 1
assert ac.subject in package.subject.ownedElement
|
413ba364dc35a7186953d02bb7cc8cf705371873 | contentious/constants.py | contentious/constants.py | from django.conf import settings
SELF_CLOSING_HTML_TAGS = getattr(settings,
'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
| from django.conf import settings
SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta']
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
| Remove SELF_CLOSING_HTML_TAGS as a configurable option | Remove SELF_CLOSING_HTML_TAGS as a configurable option
| Python | bsd-2-clause | potatolondon/contentious,potatolondon/contentious | from django.conf import settings
- SELF_CLOSING_HTML_TAGS = getattr(settings,
- 'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
+ SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta']
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
| Remove SELF_CLOSING_HTML_TAGS as a configurable option | ## Code Before:
from django.conf import settings
SELF_CLOSING_HTML_TAGS = getattr(settings,
'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
## Instruction:
Remove SELF_CLOSING_HTML_TAGS as a configurable option
## Code After:
from django.conf import settings
SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta']
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
|
182cd3b73382bb150111198e5fcbfa43a6bd416f | cbagent/collectors/libstats/typeperfstats.py | cbagent/collectors/libstats/typeperfstats.py | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'"
@parallel_task(server_side=True)
def get_samples(self, process):
samples = {}
if process == "beam.smp":
stdout = self.run(self.typeperf_cmd.format("erl"))
values = stdout.split(',')[1:5]
elif process == "memcached":
stdout = self.run(self.typeperf_cmd.format(process))
values = stdout.split(',')[1:2]
else:
return samples
sum_rss = 0
if stdout:
for v in values:
v = float(v.replace('"', ''))
sum_rss += v
metric, multiplier = self.METRICS[0]
title = "{}_{}".format(process, metric)
samples[title] = float(sum_rss) * multiplier
return samples
| from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'"
@parallel_task(server_side=True)
def get_server_samples(self, process):
samples = {}
if process == "beam.smp":
stdout = self.run(self.typeperf_cmd.format("erl"))
values = stdout.split(',')[1:5]
elif process == "memcached":
stdout = self.run(self.typeperf_cmd.format(process))
values = stdout.split(',')[1:2]
else:
return samples
sum_rss = 0
if stdout:
for v in values:
v = float(v.replace('"', ''))
sum_rss += v
metric, multiplier = self.METRICS[0]
title = "{}_{}".format(process, metric)
samples[title] = float(sum_rss) * multiplier
return samples
def get_client_samples(self, process):
pass
| Add missing methods to TPStats | Add missing methods to TPStats
Change-Id: I332a83f3816ee30597288180ed344da3161861f8
Reviewed-on: http://review.couchbase.org/79675
Tested-by: Build Bot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]>
| Python | apache-2.0 | pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'"
@parallel_task(server_side=True)
- def get_samples(self, process):
+ def get_server_samples(self, process):
samples = {}
if process == "beam.smp":
stdout = self.run(self.typeperf_cmd.format("erl"))
values = stdout.split(',')[1:5]
elif process == "memcached":
stdout = self.run(self.typeperf_cmd.format(process))
values = stdout.split(',')[1:2]
else:
return samples
sum_rss = 0
if stdout:
for v in values:
v = float(v.replace('"', ''))
sum_rss += v
metric, multiplier = self.METRICS[0]
title = "{}_{}".format(process, metric)
samples[title] = float(sum_rss) * multiplier
return samples
+ def get_client_samples(self, process):
+ pass
+ | Add missing methods to TPStats | ## Code Before:
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'"
@parallel_task(server_side=True)
def get_samples(self, process):
samples = {}
if process == "beam.smp":
stdout = self.run(self.typeperf_cmd.format("erl"))
values = stdout.split(',')[1:5]
elif process == "memcached":
stdout = self.run(self.typeperf_cmd.format(process))
values = stdout.split(',')[1:2]
else:
return samples
sum_rss = 0
if stdout:
for v in values:
v = float(v.replace('"', ''))
sum_rss += v
metric, multiplier = self.METRICS[0]
title = "{}_{}".format(process, metric)
samples[title] = float(sum_rss) * multiplier
return samples
## Instruction:
Add missing methods to TPStats
## Code After:
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typeperf \"\\Process(*{}*)\\Working Set\" -sc 1|sed '3q;d'"
@parallel_task(server_side=True)
def get_server_samples(self, process):
samples = {}
if process == "beam.smp":
stdout = self.run(self.typeperf_cmd.format("erl"))
values = stdout.split(',')[1:5]
elif process == "memcached":
stdout = self.run(self.typeperf_cmd.format(process))
values = stdout.split(',')[1:2]
else:
return samples
sum_rss = 0
if stdout:
for v in values:
v = float(v.replace('"', ''))
sum_rss += v
metric, multiplier = self.METRICS[0]
title = "{}_{}".format(process, metric)
samples[title] = float(sum_rss) * multiplier
return samples
def get_client_samples(self, process):
pass
|
c45fc698da9783b561cca69363ec4998622e9ac0 | mint/rest/db/capsulemgr.py | mint/rest/db/capsulemgr.py |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sqlite:///%s/database.sqlite" %
capsuleDataDir)
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
|
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.driver
dbConnectString = self.db.db.db.database
cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
| Use the mint database for capsule data | Use the mint database for capsule data
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
- cfg.configLine("store sqlite:///%s/database.sqlite" %
- capsuleDataDir)
+ dbDriver = self.db.db.driver
+ dbConnectString = self.db.db.db.database
+ cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
| Use the mint database for capsule data | ## Code Before:
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sqlite:///%s/database.sqlite" %
capsuleDataDir)
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
## Instruction:
Use the mint database for capsule data
## Code After:
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.driver
dbConnectString = self.db.db.db.database
cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
|
21059428d95c27cf043ada2e299a4cf3982a4233 | python/printbag.py | python/printbag.py |
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def decode_bag(bag):
topics = ['/scan', '/flagbutton_pressed']
return [message for message in bag.read_messages(topics=topics)]
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} <rosbag> [<outfile>] \n\n'
'Print contents of rosbag file. If <outfile> is provided, \n'
'write contents of rosbag file to <outfile> in the legacy \n'
'lidar binary format.').format(__file__))
sys.exit(1)
outfile = None
filename = sys.argv[1]
if len(sys.argv) == 3:
outfile = sys.argv[2]
with rosbag.Bag(filename) as bag:
print(decode_bag(bag))
sys.exit()
|
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def print_bag(bag):
topics = ['/scan', '/flagbutton_pressed']
for message in bag.read_messages(topics=topics):
print(message)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} <rosbag> [<outfile>] \n\n'
'Print contents of rosbag file. If <outfile> is provided, \n'
'write contents of rosbag file to <outfile> in the legacy \n'
'lidar binary format.').format(__file__))
sys.exit(1)
outfile = None
filename = sys.argv[1]
if len(sys.argv) == 3:
outfile = sys.argv[2]
with rosbag.Bag(filename) as bag:
print_bag(bag)
sys.exit()
| Print out bag contents for lidar and button topics | Print out bag contents for lidar and button topics
| Python | bsd-2-clause | oliverlee/antlia |
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
- def decode_bag(bag):
+ def print_bag(bag):
topics = ['/scan', '/flagbutton_pressed']
- return [message for message in bag.read_messages(topics=topics)]
+ for message in bag.read_messages(topics=topics):
+ print(message)
+
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} <rosbag> [<outfile>] \n\n'
'Print contents of rosbag file. If <outfile> is provided, \n'
'write contents of rosbag file to <outfile> in the legacy \n'
'lidar binary format.').format(__file__))
sys.exit(1)
outfile = None
filename = sys.argv[1]
if len(sys.argv) == 3:
outfile = sys.argv[2]
with rosbag.Bag(filename) as bag:
- print(decode_bag(bag))
+ print_bag(bag)
sys.exit()
| Print out bag contents for lidar and button topics | ## Code Before:
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def decode_bag(bag):
topics = ['/scan', '/flagbutton_pressed']
return [message for message in bag.read_messages(topics=topics)]
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} <rosbag> [<outfile>] \n\n'
'Print contents of rosbag file. If <outfile> is provided, \n'
'write contents of rosbag file to <outfile> in the legacy \n'
'lidar binary format.').format(__file__))
sys.exit(1)
outfile = None
filename = sys.argv[1]
if len(sys.argv) == 3:
outfile = sys.argv[2]
with rosbag.Bag(filename) as bag:
print(decode_bag(bag))
sys.exit()
## Instruction:
Print out bag contents for lidar and button topics
## Code After:
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def print_bag(bag):
topics = ['/scan', '/flagbutton_pressed']
for message in bag.read_messages(topics=topics):
print(message)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} <rosbag> [<outfile>] \n\n'
'Print contents of rosbag file. If <outfile> is provided, \n'
'write contents of rosbag file to <outfile> in the legacy \n'
'lidar binary format.').format(__file__))
sys.exit(1)
outfile = None
filename = sys.argv[1]
if len(sys.argv) == 3:
outfile = sys.argv[2]
with rosbag.Bag(filename) as bag:
print_bag(bag)
sys.exit()
|
78cca16df6a5cdd90ec92e64455215c4b7292fae | report_coverage.py | report_coverage.py | import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
for f in js_files:
source = '\n'.join(open(f['filename']).readlines())
name = os.path.relpath(f['filename'])
coverage = []
for v in f['source'].values():
coverage.append(v['coverage'] if v['coverage'] != '' else None)
js_report.append({
'source': source,
'name': name,
'coverage': coverage}
)
report += js_report
return report
Coveralls.get_coverage = get_coverage_with_js
cli.main(sys.argv[1:])
| import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
for f in js_files:
source = '\n'.join(open(f['filename']).readlines())
name = os.path.relpath(f['filename'])
coverage = []
# Create sorted coverage array from original dict
for k, v in sorted(f['source'].items(), key=lambda x:int(x[0])):
coverage.append(v['coverage'] if v['coverage'] != '' else None)
js_report.append({
'source': source,
'name': name,
'coverage': coverage}
)
report += js_report
return report
Coveralls.get_coverage = get_coverage_with_js
cli.main(sys.argv[1:])
| Sort line coverage info when reporting | Sort line coverage info when reporting
| Python | apache-2.0 | exekias/django-achilles,exekias/django-achilles | import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
for f in js_files:
source = '\n'.join(open(f['filename']).readlines())
name = os.path.relpath(f['filename'])
coverage = []
- for v in f['source'].values():
+
+ # Create sorted coverage array from original dict
+ for k, v in sorted(f['source'].items(), key=lambda x:int(x[0])):
coverage.append(v['coverage'] if v['coverage'] != '' else None)
js_report.append({
'source': source,
'name': name,
'coverage': coverage}
)
report += js_report
return report
Coveralls.get_coverage = get_coverage_with_js
cli.main(sys.argv[1:])
| Sort line coverage info when reporting | ## Code Before:
import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
for f in js_files:
source = '\n'.join(open(f['filename']).readlines())
name = os.path.relpath(f['filename'])
coverage = []
for v in f['source'].values():
coverage.append(v['coverage'] if v['coverage'] != '' else None)
js_report.append({
'source': source,
'name': name,
'coverage': coverage}
)
report += js_report
return report
Coveralls.get_coverage = get_coverage_with_js
cli.main(sys.argv[1:])
## Instruction:
Sort line coverage info when reporting
## Code After:
import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
for f in js_files:
source = '\n'.join(open(f['filename']).readlines())
name = os.path.relpath(f['filename'])
coverage = []
# Create sorted coverage array from original dict
for k, v in sorted(f['source'].items(), key=lambda x:int(x[0])):
coverage.append(v['coverage'] if v['coverage'] != '' else None)
js_report.append({
'source': source,
'name': name,
'coverage': coverage}
)
report += js_report
return report
Coveralls.get_coverage = get_coverage_with_js
cli.main(sys.argv[1:])
|
4ae8302a3d91ca1e9601e0c51cb58a69f1c08cb5 | setup.py | setup.py | """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutils.core.setup(
name='bibpy',
version=get_version(os.path.join('bibpy', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='All',
description=('Bib(la)tex parsing and useful tools'),
license='MIT',
keywords='bibpy, bibtex, biblatex, parser',
url='https://github.com/MisanthropicBit/bibpy',
packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.parsers',
'bibpy.doi'],
long_description=open('README.md').read(),
scripts=['bin/bibgrep', 'bin/bibformat', 'bin/bibstats'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6',
]
)
| """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutils.core.setup(
name='bibpy',
version=get_version(os.path.join('bibpy', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='All',
description=('Bib(la)tex parsing and useful tools'),
license='MIT',
keywords='bibpy, bibtex, biblatex, parser',
url='https://github.com/MisanthropicBit/bibpy',
packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.doi'],
long_description=open('README.md').read(),
scripts=['bin/bibgrep', 'bin/bibformat', 'bin/bibstats'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6',
]
)
| Remove 'bibpy.parsers' from package list | Remove 'bibpy.parsers' from package list
| Python | mit | MisanthropicBit/bibpy,MisanthropicBit/bibpy | """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutils.core.setup(
name='bibpy',
version=get_version(os.path.join('bibpy', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='All',
description=('Bib(la)tex parsing and useful tools'),
license='MIT',
keywords='bibpy, bibtex, biblatex, parser',
url='https://github.com/MisanthropicBit/bibpy',
- packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.parsers',
+ packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.doi'],
- 'bibpy.doi'],
long_description=open('README.md').read(),
scripts=['bin/bibgrep', 'bin/bibformat', 'bin/bibstats'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6',
]
)
| Remove 'bibpy.parsers' from package list | ## Code Before:
"""bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutils.core.setup(
name='bibpy',
version=get_version(os.path.join('bibpy', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='All',
description=('Bib(la)tex parsing and useful tools'),
license='MIT',
keywords='bibpy, bibtex, biblatex, parser',
url='https://github.com/MisanthropicBit/bibpy',
packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.parsers',
'bibpy.doi'],
long_description=open('README.md').read(),
scripts=['bin/bibgrep', 'bin/bibformat', 'bin/bibstats'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6',
]
)
## Instruction:
Remove 'bibpy.parsers' from package list
## Code After:
"""bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutils.core.setup(
name='bibpy',
version=get_version(os.path.join('bibpy', '__init__.py')),
author='Alexander Asp Bock',
author_email='[email protected]',
platforms='All',
description=('Bib(la)tex parsing and useful tools'),
license='MIT',
keywords='bibpy, bibtex, biblatex, parser',
url='https://github.com/MisanthropicBit/bibpy',
packages=['bibpy', 'bibpy.entry', 'bibpy.lexers', 'bibpy.doi'],
long_description=open('README.md').read(),
scripts=['bin/bibgrep', 'bin/bibformat', 'bin/bibstats'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Utilities',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.5'
'Programming Language :: Python :: 3.6',
]
)
|
73f7502f1fda11bc23469c6f3e8f79b0e375c928 | setup.py | setup.py |
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='[email protected]',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
)
|
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='[email protected]',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
data_files=['LICENSE', 'README.rst'],
)
| Add license and readme to the packages | Add license and readme to the packages
| Python | bsd-2-clause | hyunchel/redis-dump-load,p/redis-dump-load,p/redis-dump-load,hyunchel/redis-dump-load |
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='[email protected]',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
+ data_files=['LICENSE', 'README.rst'],
)
| Add license and readme to the packages | ## Code Before:
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='[email protected]',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
)
## Instruction:
Add license and readme to the packages
## Code After:
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='[email protected]',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
data_files=['LICENSE', 'README.rst'],
)
|
c987ed375da13f53928157f14528bed0c148eeac | tasks.py | tasks.py | import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def later(cls, func, *args, after=None, **kwargs):
cls.loop.call_later(after, lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def periodic(cls, func, *args, interval=None, **kwargs):
@asyncio.coroutine
def f():
while True:
yield from asyncio.sleep(interval)
func(*args, **kwargs)
cls.loop.create_task(f())
cls.loop._write_to_self()
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
| import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
asyncio.set_event_loop(cls.loop)
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def later(cls, func, *args, after=None, **kwargs):
cls.loop.call_later(after, lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def periodic(cls, func, *args, interval=None, **kwargs):
@asyncio.coroutine
def f():
while True:
yield from asyncio.sleep(interval)
func(*args, **kwargs)
cls.loop.create_task(f())
cls.loop._write_to_self()
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
| Set implicit loop for Python <3.6 | Set implicit loop for Python <3.6 | Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
+ asyncio.set_event_loop(cls.loop)
+
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def later(cls, func, *args, after=None, **kwargs):
cls.loop.call_later(after, lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def periodic(cls, func, *args, interval=None, **kwargs):
@asyncio.coroutine
def f():
while True:
yield from asyncio.sleep(interval)
func(*args, **kwargs)
cls.loop.create_task(f())
cls.loop._write_to_self()
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
| Set implicit loop for Python <3.6 | ## Code Before:
import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def later(cls, func, *args, after=None, **kwargs):
cls.loop.call_later(after, lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def periodic(cls, func, *args, interval=None, **kwargs):
@asyncio.coroutine
def f():
while True:
yield from asyncio.sleep(interval)
func(*args, **kwargs)
cls.loop.create_task(f())
cls.loop._write_to_self()
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
## Instruction:
Set implicit loop for Python <3.6
## Code After:
import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
asyncio.set_event_loop(cls.loop)
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def later(cls, func, *args, after=None, **kwargs):
cls.loop.call_later(after, lambda: func(*args, **kwargs))
cls.loop._write_to_self()
@classmethod
def periodic(cls, func, *args, interval=None, **kwargs):
@asyncio.coroutine
def f():
while True:
yield from asyncio.sleep(interval)
func(*args, **kwargs)
cls.loop.create_task(f())
cls.loop._write_to_self()
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
|
7dcd2c2aa1e2fd8f17e0b564f9b77375675ccd9a | metakernel/pexpect.py | metakernel/pexpect.py | from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
| from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
| Add handling of which on Windows | Add handling of which on Windows
| Python | bsd-3-clause | Calysto/metakernel | from __future__ import absolute_import
- from pexpect import spawn, which, EOF, TIMEOUT
+ from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
+ import os
+ try:
+ from pexpect import spawn
+ import pty
+ except ImportError:
+ pty = None
+
+
+ def which(filename):
+ '''This takes a given filename; tries to find it in the environment path;
+ then checks if it is executable. This returns the full path to the filename
+ if found and executable. Otherwise this returns None.'''
+
+ # Special case where filename contains an explicit path.
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
+ return filename
+ if 'PATH' not in os.environ or os.environ['PATH'] == '':
+ p = os.defpath
+ else:
+ p = os.environ['PATH']
+ pathlist = p.split(os.pathsep)
+ for path in pathlist:
+ ff = os.path.join(path, filename)
+ if pty:
+ if is_executable_file(ff):
+ return ff
+ else:
+ pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
+ pathext = pathext.split(os.pathsep) + ['']
+ for ext in pathext:
+ if os.access(ff + ext, os.X_OK):
+ return ff + ext
+ return None
+ | Add handling of which on Windows | ## Code Before:
from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
## Instruction:
Add handling of which on Windows
## Code After:
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
|
6defa096b3dae109bf50ab32cdee7062c8b4327b | _python/config/settings/settings_pytest.py | _python/config/settings/settings_pytest.py |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
|
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | Add placeholder CAPAPI key for tests.
| Python | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
+ CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | ## Code Before:
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
## Instruction:
Add placeholder CAPAPI key for tests.
## Code After:
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
|
d413747e996326e62fdf942426f170f66d5acb7c | osf_tests/test_preprint_summary.py | osf_tests/test_preprint_summary.py | import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint_provider():
return PreprintProviderFactory(name='Test 1')
@pytest.fixture()
def preprint(preprint_provider):
return PreprintFactory._build(PreprintService, provider=preprint_provider)
pytestmark = pytest.mark.django_db
class TestPreprintCount:
def test_get_preprint_count(self, preprint_provider, preprint):
requests.post = mock.MagicMock()
resp = requests.Response()
resp._content = '{"hits" : {"total" : 1}}'
requests.post.return_value = resp
field = PreprintService._meta.get_field('date_created')
field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries.
date = datetime.datetime.utcnow() - datetime.timedelta(1)
preprint.date_created = date - datetime.timedelta(0.1)
preprint.save()
field.auto_now_add = True
results = PreprintSummary().get_events(date.date())
assert_equal(len(results), 1)
data = results[0]
assert_equal(data['provider']['name'], 'Test 1')
assert_equal(data['provider']['total'], 1)
| import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint_provider():
return PreprintProviderFactory(name='Test 1')
@pytest.fixture()
def preprint(preprint_provider):
return PreprintFactory._build(PreprintService, provider=preprint_provider)
pytestmark = pytest.mark.django_db
class TestPreprintCount:
def test_get_preprint_count(self, preprint):
requests.post = mock.MagicMock()
resp = requests.Response()
resp._content = '{"hits" : {"total" : 1}}'
requests.post.return_value = resp
field = PreprintService._meta.get_field('date_created')
field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries.
date = datetime.datetime.utcnow() - datetime.timedelta(days=1, hours=1)
preprint.date_created = date - datetime.timedelta(hours=1)
preprint.save()
field.auto_now_add = True
results = PreprintSummary().get_events(date.date())
assert_equal(len(results), 1)
data = results[0]
assert_equal(data['provider']['name'], 'Test 1')
assert_equal(data['provider']['total'], 1)
| Make sure test dates are rounded properly by making they are over a day in the past. | Make sure test dates are rounded properly by making they are over a day in the past.
| Python | apache-2.0 | binoculars/osf.io,TomBaxter/osf.io,sloria/osf.io,adlius/osf.io,Johnetordoff/osf.io,mattclark/osf.io,adlius/osf.io,sloria/osf.io,HalcyonChimera/osf.io,adlius/osf.io,laurenrevere/osf.io,erinspace/osf.io,sloria/osf.io,binoculars/osf.io,mfraezz/osf.io,TomBaxter/osf.io,icereval/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,crcresearch/osf.io,adlius/osf.io,felliott/osf.io,caseyrollins/osf.io,crcresearch/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,chennan47/osf.io,cslzchen/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,erinspace/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,cslzchen/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,felliott/osf.io,felliott/osf.io,laurenrevere/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,pattisdr/osf.io,pattisdr/osf.io,icereval/osf.io,laurenrevere/osf.io,baylee-d/osf.io,chennan47/osf.io,TomBaxter/osf.io,aaxelb/osf.io,binoculars/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,mfraezz/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,erinspace/osf.io,brianjgeiger/osf.io,icereval/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,leb2dg/osf.io,saradbowman/osf.io | import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint_provider():
return PreprintProviderFactory(name='Test 1')
@pytest.fixture()
def preprint(preprint_provider):
return PreprintFactory._build(PreprintService, provider=preprint_provider)
pytestmark = pytest.mark.django_db
class TestPreprintCount:
- def test_get_preprint_count(self, preprint_provider, preprint):
+ def test_get_preprint_count(self, preprint):
requests.post = mock.MagicMock()
resp = requests.Response()
resp._content = '{"hits" : {"total" : 1}}'
requests.post.return_value = resp
field = PreprintService._meta.get_field('date_created')
field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries.
- date = datetime.datetime.utcnow() - datetime.timedelta(1)
+ date = datetime.datetime.utcnow() - datetime.timedelta(days=1, hours=1)
- preprint.date_created = date - datetime.timedelta(0.1)
+ preprint.date_created = date - datetime.timedelta(hours=1)
preprint.save()
field.auto_now_add = True
results = PreprintSummary().get_events(date.date())
assert_equal(len(results), 1)
data = results[0]
assert_equal(data['provider']['name'], 'Test 1')
assert_equal(data['provider']['total'], 1)
| Make sure test dates are rounded properly by making they are over a day in the past. | ## Code Before:
import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint_provider():
return PreprintProviderFactory(name='Test 1')
@pytest.fixture()
def preprint(preprint_provider):
return PreprintFactory._build(PreprintService, provider=preprint_provider)
pytestmark = pytest.mark.django_db
class TestPreprintCount:
def test_get_preprint_count(self, preprint_provider, preprint):
requests.post = mock.MagicMock()
resp = requests.Response()
resp._content = '{"hits" : {"total" : 1}}'
requests.post.return_value = resp
field = PreprintService._meta.get_field('date_created')
field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries.
date = datetime.datetime.utcnow() - datetime.timedelta(1)
preprint.date_created = date - datetime.timedelta(0.1)
preprint.save()
field.auto_now_add = True
results = PreprintSummary().get_events(date.date())
assert_equal(len(results), 1)
data = results[0]
assert_equal(data['provider']['name'], 'Test 1')
assert_equal(data['provider']['total'], 1)
## Instruction:
Make sure test dates are rounded properly by making they are over a day in the past.
## Code After:
import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint_provider():
return PreprintProviderFactory(name='Test 1')
@pytest.fixture()
def preprint(preprint_provider):
return PreprintFactory._build(PreprintService, provider=preprint_provider)
pytestmark = pytest.mark.django_db
class TestPreprintCount:
def test_get_preprint_count(self, preprint):
requests.post = mock.MagicMock()
resp = requests.Response()
resp._content = '{"hits" : {"total" : 1}}'
requests.post.return_value = resp
field = PreprintService._meta.get_field('date_created')
field.auto_now_add = False # We have to fudge the time because Keen doesn't allow same day queries.
date = datetime.datetime.utcnow() - datetime.timedelta(days=1, hours=1)
preprint.date_created = date - datetime.timedelta(hours=1)
preprint.save()
field.auto_now_add = True
results = PreprintSummary().get_events(date.date())
assert_equal(len(results), 1)
data = results[0]
assert_equal(data['provider']['name'], 'Test 1')
assert_equal(data['provider']['total'], 1)
|
7d6ad23cd8435eac9b48a4ea63bb9a2e83239c4a | scent.py | scent.py |
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this variable will be under surveillance for changes.
watch_paths = ['tmuxp/']
@file_validator
def py_files(filename):
return filename.endswith('.py') and not os.path.basename(filename).startswith('.') and filename != ".tmuxp"
@runnable
def execute_nose(*args):
try:
return main()
except SystemExit as x:
if x.message:
print "Found error {0}: {1}".format(x.code, x.message)
return not x.code
else:
return 1
| from __future__ import unicode_literals
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this variable will be under surveillance for changes.
watch_paths = ['tmuxp/']
@file_validator
def py_files(filename):
return filename.endswith('.py') and not os.path.basename(filename).startswith('.') and filename != ".tmuxp"
@runnable
def execute_nose(*args):
try:
return main()
except SystemExit as x:
if x.message:
print("Found error {0}: {1}".format(x.code, x.message))
return not x.code
else:
return 1
| Fix sniffer support for python 3.x | Fix sniffer support for python 3.x
| Python | bsd-3-clause | thomasballinger/tmuxp,thomasballinger/tmuxp,mexicarne/tmuxp,tony/tmuxp,mexicarne/tmuxp | + from __future__ import unicode_literals
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this variable will be under surveillance for changes.
watch_paths = ['tmuxp/']
@file_validator
def py_files(filename):
return filename.endswith('.py') and not os.path.basename(filename).startswith('.') and filename != ".tmuxp"
@runnable
def execute_nose(*args):
try:
return main()
except SystemExit as x:
if x.message:
- print "Found error {0}: {1}".format(x.code, x.message)
+ print("Found error {0}: {1}".format(x.code, x.message))
return not x.code
else:
return 1
- | Fix sniffer support for python 3.x | ## Code Before:
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this variable will be under surveillance for changes.
watch_paths = ['tmuxp/']
@file_validator
def py_files(filename):
return filename.endswith('.py') and not os.path.basename(filename).startswith('.') and filename != ".tmuxp"
@runnable
def execute_nose(*args):
try:
return main()
except SystemExit as x:
if x.message:
print "Found error {0}: {1}".format(x.code, x.message)
return not x.code
else:
return 1
## Instruction:
Fix sniffer support for python 3.x
## Code After:
from __future__ import unicode_literals
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this variable will be under surveillance for changes.
watch_paths = ['tmuxp/']
@file_validator
def py_files(filename):
return filename.endswith('.py') and not os.path.basename(filename).startswith('.') and filename != ".tmuxp"
@runnable
def execute_nose(*args):
try:
return main()
except SystemExit as x:
if x.message:
print("Found error {0}: {1}".format(x.code, x.message))
return not x.code
else:
return 1
|
ec96c3173a770949c13e560b16272bc265a80da4 | setup.py | setup.py |
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
|
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
packages=['mass_api_client', ],
)
| Add mass_api_client as Package; fix typo | Add mass_api_client as Package; fix typo
| Python | mit | mass-project/mass_api_client,mass-project/mass_api_client |
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
- install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
+ install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
+ packages=['mass_api_client', ],
+ )
| Add mass_api_client as Package; fix typo | ## Code Before:
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
## Instruction:
Add mass_api_client as Package; fix typo
## Code After:
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
packages=['mass_api_client', ],
)
|
596613c964311104098e64eeb349216bc7cd0023 | saleor/demo/views.py | saleor/demo/views.py | from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
ctx = {
"query": EXAMPLE_QUERY,
"api_url": request.build_absolute_uri(str(API_PATH)),
}
return render(request, "graphql/playground.html", ctx)
| from django.conf import settings
from django.shortcuts import render
from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
pwa_origin = settings.PWA_ORIGINS[0]
ctx = {
"query": EXAMPLE_QUERY,
"api_url": f"https://{pwa_origin}/graphql/",
}
return render(request, "graphql/playground.html", ctx)
| Fix playground CSP for demo if deployed under proxied domain | Fix playground CSP for demo if deployed under proxied domain
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | from django.conf import settings
from django.shortcuts import render
- from ..graphql.views import API_PATH, GraphQLView
+ from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
+ pwa_origin = settings.PWA_ORIGINS[0]
ctx = {
"query": EXAMPLE_QUERY,
- "api_url": request.build_absolute_uri(str(API_PATH)),
+ "api_url": f"https://{pwa_origin}/graphql/",
}
return render(request, "graphql/playground.html", ctx)
| Fix playground CSP for demo if deployed under proxied domain | ## Code Before:
from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
ctx = {
"query": EXAMPLE_QUERY,
"api_url": request.build_absolute_uri(str(API_PATH)),
}
return render(request, "graphql/playground.html", ctx)
## Instruction:
Fix playground CSP for demo if deployed under proxied domain
## Code After:
from django.conf import settings
from django.shortcuts import render
from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and validation errors highlighted within the text.
#
# Here is an example query to fetch a list of products:
#
{
products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
name
description
}
}
}
}
""" % {
"channel_slug": settings.DEFAULT_CHANNEL_SLUG
}
class DemoGraphQLView(GraphQLView):
def render_playground(self, request):
pwa_origin = settings.PWA_ORIGINS[0]
ctx = {
"query": EXAMPLE_QUERY,
"api_url": f"https://{pwa_origin}/graphql/",
}
return render(request, "graphql/playground.html", ctx)
|
53594f372a45e425076e5dbf36f399503df1972c | salt/output/yaml_out.py | salt/output/yaml_out.py | '''
YAML Outputter
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML
'''
return yaml.dump(data)
| '''
Output data in YAML, this outputter defaults to printing in YAML block mode
for better readability.
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML using the block mode
'''
return yaml.dump(data, default_flow_style=False)
| Change the YAML outputter to use block mode and add some docs | Change the YAML outputter to use block mode and add some docs
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
- YAML Outputter
+ Output data in YAML, this outputter defaults to printing in YAML block mode
+ for better readability.
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
- Print out YAML
+ Print out YAML using the block mode
'''
- return yaml.dump(data)
+ return yaml.dump(data, default_flow_style=False)
| Change the YAML outputter to use block mode and add some docs | ## Code Before:
'''
YAML Outputter
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML
'''
return yaml.dump(data)
## Instruction:
Change the YAML outputter to use block mode and add some docs
## Code After:
'''
Output data in YAML, this outputter defaults to printing in YAML block mode
for better readability.
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML using the block mode
'''
return yaml.dump(data, default_flow_style=False)
|
eb5bcf3130f5fdc0d6be68e7e81555def46a53af | setup.py | setup.py | from distutils.core import setup
setup(
name = 'mstranslator',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = '[email protected]',
url = 'https://github.com/ayushgoel/mstranslator',
download_url = 'https://github.com/peterldowns/mypackage/tarball/0.1',
keywords = ['microsoft', 'translator', 'language'],
requires = ['requests']
)
| from distutils.core import setup
setup(
name = 'mstranslator-2016',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = '[email protected]',
url = 'https://github.com/ayushgoel/mstranslator',
download_url = 'https://github.com/ayushgoel/mstranslator/archive/0.0.1.tar.gz',
keywords = ['microsoft', 'translator', 'language'],
requires = ['requests']
)
| Update nemae and download URL | Update nemae and download URL
| Python | mit | ayushgoel/mstranslator | from distutils.core import setup
setup(
- name = 'mstranslator',
+ name = 'mstranslator-2016',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = '[email protected]',
url = 'https://github.com/ayushgoel/mstranslator',
- download_url = 'https://github.com/peterldowns/mypackage/tarball/0.1',
+ download_url = 'https://github.com/ayushgoel/mstranslator/archive/0.0.1.tar.gz',
keywords = ['microsoft', 'translator', 'language'],
requires = ['requests']
)
| Update nemae and download URL | ## Code Before:
from distutils.core import setup
setup(
name = 'mstranslator',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = '[email protected]',
url = 'https://github.com/ayushgoel/mstranslator',
download_url = 'https://github.com/peterldowns/mypackage/tarball/0.1',
keywords = ['microsoft', 'translator', 'language'],
requires = ['requests']
)
## Instruction:
Update nemae and download URL
## Code After:
from distutils.core import setup
setup(
name = 'mstranslator-2016',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = '[email protected]',
url = 'https://github.com/ayushgoel/mstranslator',
download_url = 'https://github.com/ayushgoel/mstranslator/archive/0.0.1.tar.gz',
keywords = ['microsoft', 'translator', 'language'],
requires = ['requests']
)
|
ccbe4a1c48765fdd9e785392dff949bcc49192a2 | setup.py | setup.py | from distutils.core import setup
setup(
name='Zinc',
version='0.1.7',
author='John Wang',
author_email='[email protected]',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
| from distutils.core import setup
setup(
name='Zinc',
version='0.1.8',
author='John Wang',
author_email='[email protected]',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
| Remove readme from package data. | Remove readme from package data.
| Python | mit | wangjohn/zinc_cli | from distutils.core import setup
setup(
name='Zinc',
- version='0.1.7',
+ version='0.1.8',
author='John Wang',
author_email='[email protected]',
packages=['zinc'],
package_dir={'zinc': ''},
- package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
+ package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
| Remove readme from package data. | ## Code Before:
from distutils.core import setup
setup(
name='Zinc',
version='0.1.7',
author='John Wang',
author_email='[email protected]',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
## Instruction:
Remove readme from package data.
## Code After:
from distutils.core import setup
setup(
name='Zinc',
version='0.1.8',
author='John Wang',
author_email='[email protected]',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
|
7e88739d91cd7db35ffb36804ae59d1878eb2da3 | setup.py | setup.py | import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
| import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
| Use py_modules and not packages | Use py_modules and not packages
| Python | bsd-3-clause | agoragames/py-eventsocket | import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
- packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
+ py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
| Use py_modules and not packages | ## Code Before:
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
## Instruction:
Use py_modules and not packages
## Code After:
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="[email protected]",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
c0b9c9712e464f304bee7c63bfd6b197a1c5fb0f | cmsplugin_bootstrap_carousel/cms_plugins.py | cmsplugin_bootstrap_carousel/cms_plugins.py | import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
| import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
extra = 0
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
| Change extra from 3 to 0. | Change extra from 3 to 0.
| Python | bsd-3-clause | 360youlun/cmsplugin-bootstrap-carousel,360youlun/cmsplugin-bootstrap-carousel | import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
+ extra = 0
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
| Change extra from 3 to 0. | ## Code Before:
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
## Instruction:
Change extra from 3 to 0.
## Code After:
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
extra = 0
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
|
554e79ada3f351ecb6287b08d0f7d1c4e5a5b5f6 | setup.py | setup.py |
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "[email protected]",
maintainer= "IOAM",
maintainer_email= "[email protected]",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
# (until packaging tested)
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
|
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "[email protected]",
maintainer= "IOAM",
maintainer_email= "[email protected]",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
| Update version number to 1.0. | Update version number to 1.0.
| Python | bsd-3-clause | ceball/param,ioam/param |
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
- version='0.05',
+ version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "[email protected]",
maintainer= "IOAM",
maintainer_email= "[email protected]",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
- # (until packaging tested)
- "Development Status :: 4 - Beta",
+ "Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
| Update version number to 1.0. | ## Code Before:
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "[email protected]",
maintainer= "IOAM",
maintainer_email= "[email protected]",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
# (until packaging tested)
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
## Instruction:
Update version number to 1.0.
## Code After:
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "[email protected]",
maintainer= "IOAM",
maintainer_email= "[email protected]",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
|
81b6a138c476084f9ddd6063f31d3efd0ba6e2cf | start.py | start.py | import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argument('-c', '--config',
help='the config file to read from',
type=str, required=True)
cmdArgs = parser.parse_args()
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Set up logging for stdout on the root 'desertbot' logger
# Modules can then just add more handlers to the root logger to capture all logs to files in various ways
rootLogger = logging.getLogger('desertbot')
rootLogger.setLevel(logging.INFO) # TODO change this from config value once it's loaded
logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')
streamHandler = logging.StreamHandler(stream=sys.stdout)
streamHandler.setFormatter(logFormatter)
rootLogger.addHandler(streamHandler)
config = Config(cmdArgs.config)
try:
config.loadConfig()
except ConfigError:
rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
else:
factory = DesertBotFactory(config)
reactor.run()
| import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argument('-c', '--config',
help='the config file to read from',
type=str, required=True)
parser.add_argument('-l', '--loglevel',
help='the logging level (default INFO)',
type=str, default='INFO')
cmdArgs = parser.parse_args()
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Set up logging for stdout on the root 'desertbot' logger
# Modules can then just add more handlers to the root logger to capture all logs to files in various ways
rootLogger = logging.getLogger('desertbot')
numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
if isinstance(numericLevel, int):
rootLogger.setLevel(numericLevel)
else:
raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))
logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')
streamHandler = logging.StreamHandler(stream=sys.stdout)
streamHandler.setFormatter(logFormatter)
rootLogger.addHandler(streamHandler)
config = Config(cmdArgs.config)
try:
config.loadConfig()
except ConfigError:
rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
else:
factory = DesertBotFactory(config)
reactor.run()
| Make the logging level configurable | Make the logging level configurable
| Python | mit | DesertBot/DesertBot | import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argument('-c', '--config',
help='the config file to read from',
type=str, required=True)
+ parser.add_argument('-l', '--loglevel',
+ help='the logging level (default INFO)',
+ type=str, default='INFO')
cmdArgs = parser.parse_args()
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Set up logging for stdout on the root 'desertbot' logger
# Modules can then just add more handlers to the root logger to capture all logs to files in various ways
rootLogger = logging.getLogger('desertbot')
- rootLogger.setLevel(logging.INFO) # TODO change this from config value once it's loaded
+ numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
+ if isinstance(numericLevel, int):
+ rootLogger.setLevel(numericLevel)
+ else:
+ raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))
logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')
streamHandler = logging.StreamHandler(stream=sys.stdout)
streamHandler.setFormatter(logFormatter)
rootLogger.addHandler(streamHandler)
config = Config(cmdArgs.config)
try:
config.loadConfig()
except ConfigError:
rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
else:
factory = DesertBotFactory(config)
reactor.run()
| Make the logging level configurable | ## Code Before:
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argument('-c', '--config',
help='the config file to read from',
type=str, required=True)
cmdArgs = parser.parse_args()
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Set up logging for stdout on the root 'desertbot' logger
# Modules can then just add more handlers to the root logger to capture all logs to files in various ways
rootLogger = logging.getLogger('desertbot')
rootLogger.setLevel(logging.INFO) # TODO change this from config value once it's loaded
logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')
streamHandler = logging.StreamHandler(stream=sys.stdout)
streamHandler.setFormatter(logFormatter)
rootLogger.addHandler(streamHandler)
config = Config(cmdArgs.config)
try:
config.loadConfig()
except ConfigError:
rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
else:
factory = DesertBotFactory(config)
reactor.run()
## Instruction:
Make the logging level configurable
## Code After:
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argument('-c', '--config',
help='the config file to read from',
type=str, required=True)
parser.add_argument('-l', '--loglevel',
help='the logging level (default INFO)',
type=str, default='INFO')
cmdArgs = parser.parse_args()
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Set up logging for stdout on the root 'desertbot' logger
# Modules can then just add more handlers to the root logger to capture all logs to files in various ways
rootLogger = logging.getLogger('desertbot')
numericLevel = getattr(logging, cmdArgs.loglevel.upper(), None)
if isinstance(numericLevel, int):
rootLogger.setLevel(numericLevel)
else:
raise ValueError('Invalid log level {}'.format(cmdArgs.loglevel))
logFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')
streamHandler = logging.StreamHandler(stream=sys.stdout)
streamHandler.setFormatter(logFormatter)
rootLogger.addHandler(streamHandler)
config = Config(cmdArgs.config)
try:
config.loadConfig()
except ConfigError:
rootLogger.exception("Failed to load configuration file {}".format(cmdArgs.config))
else:
factory = DesertBotFactory(config)
reactor.run()
|
f13fc280f25996ec7f4924647fdc879779f51737 | project/tools/normalize.py | project/tools/normalize.py |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
else:
infile = sys.stdin
outfile = sys.stdout
normalize(nbf.read(infile, "ipynb"), sys.stdout) |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
elif len(sys.argv) != 1:
sys.exit("normalize: two arguments or none, please")
else:
infile = sys.stdin
outfile = sys.stdout
try:
normalize(nbf.read(infile, "ipynb"), outfile)
except Exception as e:
sys.exit("Normalization error: '{}'".format(str(e))) | Allow two command arguments for in and out files, or none for standard filter operations | Allow two command arguments for in and out files, or none for standard filter operations
| Python | mit | holdenweb/nbtools,holdenweb/nbtools |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
+ elif len(sys.argv) != 1:
+ sys.exit("normalize: two arguments or none, please")
else:
infile = sys.stdin
outfile = sys.stdout
-
+ try:
- normalize(nbf.read(infile, "ipynb"), sys.stdout)
+ normalize(nbf.read(infile, "ipynb"), outfile)
+ except Exception as e:
+ sys.exit("Normalization error: '{}'".format(str(e))) | Allow two command arguments for in and out files, or none for standard filter operations | ## Code Before:
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
else:
infile = sys.stdin
outfile = sys.stdout
normalize(nbf.read(infile, "ipynb"), sys.stdout)
## Instruction:
Allow two command arguments for in and out files, or none for standard filter operations
## Code After:
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
elif len(sys.argv) != 1:
sys.exit("normalize: two arguments or none, please")
else:
infile = sys.stdin
outfile = sys.stdout
try:
normalize(nbf.read(infile, "ipynb"), outfile)
except Exception as e:
sys.exit("Normalization error: '{}'".format(str(e))) |
7119930b662a20d9e9bbca230f8a6485efcb7c44 | flask_appconfig/middleware.py | flask_appconfig/middleware.py |
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
|
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
# pass through other attributes, like .run() when using werkzeug
def __getattr__(self, key):
return getattr(self.app, key)
| Add __getattr__ passthrough on ReverseProxied. | Add __getattr__ passthrough on ReverseProxied.
| Python | mit | mbr/flask-appconfig |
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
+ # pass through other attributes, like .run() when using werkzeug
+ def __getattr__(self, key):
+ return getattr(self.app, key)
+ | Add __getattr__ passthrough on ReverseProxied. | ## Code Before:
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
## Instruction:
Add __getattr__ passthrough on ReverseProxied.
## Code After:
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_pass http://192.168.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Script-Name /myprefix;
}
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
environ['SCRIPT_NAME'] = script_name
path_info = environ['PATH_INFO']
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):]
scheme = environ.get('HTTP_X_SCHEME', '')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
# pass through other attributes, like .run() when using werkzeug
def __getattr__(self, key):
return getattr(self.app, key)
|
ba32a22cc0cb41c4548c658a7195fab56dab6dbf | atlas/prodtask/tasks.py | atlas/prodtask/tasks.py | from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_ended import check_open_ended
from atlas.prodtask.task_views import sync_old_tasks
import logging
_logger = logging.getLogger('prodtaskwebui')
@app.task
def test_celery():
_logger.info('test celery')
return 2
@app.task(ignore_result=True)
def sync_tasks():
sync_old_tasks(-1)
return None
@app.task(ignore_result=True)
def step_actions():
find_action_to_execute()
return None
@app.task(ignore_result=True)
def data_carousel():
submit_all_tapes_processed()
return None
@app.task(ignore_result=True)
def open_ended():
check_open_ended()
return None
@app.task(ignore_result=True)
def request_hashtags():
hashtag_request_to_tasks()
return None
@app.task(ignore_result=True)
def sync_evgen_jo():
sync_cvmfs_db()
return None
| from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_ended import check_open_ended
from atlas.prodtask.task_views import sync_old_tasks
import logging
_logger = logging.getLogger('prodtaskwebui')
@app.task
def test_celery():
_logger.info('test celery')
return 2
@app.task(ignore_result=True)
def sync_tasks():
sync_old_tasks(-1)
return None
@app.task(ignore_result=True)
def step_actions():
find_action_to_execute()
return None
@app.task(ignore_result=True)
def data_carousel():
submit_all_tapes_processed()
return None
@app.task(ignore_result=True)
def open_ended():
check_open_ended()
return None
@app.task(ignore_result=True)
def request_hashtags():
hashtag_request_to_tasks()
return None
@app.task(ignore_result=True)
def sync_evgen_jo():
sync_cvmfs_db()
return None
@app.task(ignore_result=True)
def remove_done_staging(production_requests):
delete_done_staging_rules(production_requests)
return None | Add remove done staged rules | Add remove done staged rules
| Python | apache-2.0 | PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas | from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
- from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
+ from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_ended import check_open_ended
from atlas.prodtask.task_views import sync_old_tasks
import logging
_logger = logging.getLogger('prodtaskwebui')
@app.task
def test_celery():
_logger.info('test celery')
return 2
@app.task(ignore_result=True)
def sync_tasks():
sync_old_tasks(-1)
return None
@app.task(ignore_result=True)
def step_actions():
find_action_to_execute()
return None
@app.task(ignore_result=True)
def data_carousel():
submit_all_tapes_processed()
return None
@app.task(ignore_result=True)
def open_ended():
check_open_ended()
return None
@app.task(ignore_result=True)
def request_hashtags():
hashtag_request_to_tasks()
return None
@app.task(ignore_result=True)
def sync_evgen_jo():
sync_cvmfs_db()
return None
+ @app.task(ignore_result=True)
+ def remove_done_staging(production_requests):
+ delete_done_staging_rules(production_requests)
+ return None | Add remove done staged rules | ## Code Before:
from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_ended import check_open_ended
from atlas.prodtask.task_views import sync_old_tasks
import logging
_logger = logging.getLogger('prodtaskwebui')
@app.task
def test_celery():
_logger.info('test celery')
return 2
@app.task(ignore_result=True)
def sync_tasks():
sync_old_tasks(-1)
return None
@app.task(ignore_result=True)
def step_actions():
find_action_to_execute()
return None
@app.task(ignore_result=True)
def data_carousel():
submit_all_tapes_processed()
return None
@app.task(ignore_result=True)
def open_ended():
check_open_ended()
return None
@app.task(ignore_result=True)
def request_hashtags():
hashtag_request_to_tasks()
return None
@app.task(ignore_result=True)
def sync_evgen_jo():
sync_cvmfs_db()
return None
## Instruction:
Add remove done staged rules
## Code After:
from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_ended import check_open_ended
from atlas.prodtask.task_views import sync_old_tasks
import logging
_logger = logging.getLogger('prodtaskwebui')
@app.task
def test_celery():
_logger.info('test celery')
return 2
@app.task(ignore_result=True)
def sync_tasks():
sync_old_tasks(-1)
return None
@app.task(ignore_result=True)
def step_actions():
find_action_to_execute()
return None
@app.task(ignore_result=True)
def data_carousel():
submit_all_tapes_processed()
return None
@app.task(ignore_result=True)
def open_ended():
check_open_ended()
return None
@app.task(ignore_result=True)
def request_hashtags():
hashtag_request_to_tasks()
return None
@app.task(ignore_result=True)
def sync_evgen_jo():
sync_cvmfs_db()
return None
@app.task(ignore_result=True)
def remove_done_staging(production_requests):
delete_done_staging_rules(production_requests)
return None |
eede55d9cd39c68ef03091614096e51d7df01336 | test_scraper.py | test_scraper.py | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
for row in extract_listings(test_parse):
print type(row)
assert isinstance(row, bs4.element.Tag)
| from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
test_data = extract_listings(test_parse)
assert isinstance(test_data, list)
for dict_ in test_data:
assert isinstance(dict_, dict) | Modify test_extract_listings() to account for the change in output from extract_listings() | Modify test_extract_listings() to account for the change in output from extract_listings()
| Python | mit | jefrailey/basic-scraper | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
- for row in extract_listings(test_parse):
+ test_data = extract_listings(test_parse)
- print type(row)
- assert isinstance(row, bs4.element.Tag)
-
+ assert isinstance(test_data, list)
+ for dict_ in test_data:
+ assert isinstance(dict_, dict) | Modify test_extract_listings() to account for the change in output from extract_listings() | ## Code Before:
from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
for row in extract_listings(test_parse):
print type(row)
assert isinstance(row, bs4.element.Tag)
## Instruction:
Modify test_extract_listings() to account for the change in output from extract_listings()
## Code After:
from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
test_data = extract_listings(test_parse)
assert isinstance(test_data, list)
for dict_ in test_data:
assert isinstance(dict_, dict) |
b823233978f70d8e34a3653b309ee43b4b1e0c0d | fuel/transformers/defaults.py | fuel/transformers/defaults.py | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = stream.axis_labels
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
| """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = (stream.axis_labels
if stream.axis_labels is not None
else {})
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
| Handle None axis_labels in ToBytes. | Handle None axis_labels in ToBytes.
| Python | mit | udibr/fuel,markusnagel/fuel,vdumoulin/fuel,mila-udem/fuel,dmitriy-serdyuk/fuel,udibr/fuel,markusnagel/fuel,aalmah/fuel,vdumoulin/fuel,aalmah/fuel,capybaralet/fuel,janchorowski/fuel,mila-udem/fuel,dribnet/fuel,capybaralet/fuel,dmitriy-serdyuk/fuel,janchorowski/fuel,dribnet/fuel | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
- axis_labels = stream.axis_labels
+ axis_labels = (stream.axis_labels
+ if stream.axis_labels is not None
+ else {})
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
| Handle None axis_labels in ToBytes. | ## Code Before:
"""Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = stream.axis_labels
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
## Instruction:
Handle None axis_labels in ToBytes.
## Code After:
"""Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = (stream.axis_labels
if stream.axis_labels is not None
else {})
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
|
beeae2daf35da275d5f9e1ad01516c917319bf00 | gapipy/resources/geo/state.py | gapipy/resources/geo/state.py | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| Add Place reference to State model | Add Place reference to State model
| Python | mit | gadventures/gapipy | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
- _resource_fields = [('country', 'Country')]
+ _resource_fields = [
+ ('country', 'Country'),
+ ('place', 'Place'),
+ ]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| Add Place reference to State model | ## Code Before:
from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
## Instruction:
Add Place reference to State model
## Code After:
from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
|
cedac36d38ff0bf70abc1c9193948a288e858a01 | kitsune/lib/pipeline_compilers.py | kitsune/lib/pipeline_compilers.py | import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
command = "%s %s %s > %s" % (
getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
| import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
pipeline_settings = getattr(settings, 'PIPELINE', {})
command = "%s %s %s > %s" % (
pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'),
pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
| Update BrowserifyCompiler for n Pipeline settings. | Update BrowserifyCompiler for n Pipeline settings.
| Python | bsd-3-clause | mythmon/kitsune,MikkCZ/kitsune,brittanystoroz/kitsune,anushbmx/kitsune,MikkCZ/kitsune,anushbmx/kitsune,safwanrahman/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,mozilla/kitsune,safwanrahman/kitsune,mythmon/kitsune,anushbmx/kitsune,mythmon/kitsune,safwanrahman/kitsune,mozilla/kitsune,brittanystoroz/kitsune,mythmon/kitsune,mozilla/kitsune,anushbmx/kitsune,MikkCZ/kitsune,mozilla/kitsune,brittanystoroz/kitsune,safwanrahman/kitsune | import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
+ pipeline_settings = getattr(settings, 'PIPELINE', {})
command = "%s %s %s > %s" % (
- getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
+ pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'),
- getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
+ pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
| Update BrowserifyCompiler for n Pipeline settings. | ## Code Before:
import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
command = "%s %s %s > %s" % (
getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
## Instruction:
Update BrowserifyCompiler for n Pipeline settings.
## Code After:
import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
pipeline_settings = getattr(settings, 'PIPELINE', {})
command = "%s %s %s > %s" % (
pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'),
pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
|
c1f8d5817b8c94b422c0d454dcc0fa3c00e751b6 | activelink/tests/urls.py | activelink/tests/urls.py | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
)
| from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
]
if DJANGO_VERSION < (1, 10):
urlpatterns = patterns('', *urlpatterns)
| Add support for Django 1.11 | Add support for Django 1.11
| Python | unlicense | j4mie/django-activelink | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
+
+ if DJANGO_VERSION >= (1, 10):
+ from django.conf.urls import url
- if DJANGO_VERSION >= (1, 6):
+ elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
- )
+ ]
+ if DJANGO_VERSION < (1, 10):
+ urlpatterns = patterns('', *urlpatterns)
+ | Add support for Django 1.11 | ## Code Before:
from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
)
## Instruction:
Add support for Django 1.11
## Code After:
from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
url(r'^test-url-with-arg/([-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_arg'),
url(r'^test-url-with-kwarg/(?P<arg>[-\w]+)/$', lambda r, arg: HttpResponse('ok'), name='test_with_kwarg'),
]
if DJANGO_VERSION < (1, 10):
urlpatterns = patterns('', *urlpatterns)
|
c2ca03ba94349340447a316ff21bcb26631e308f | lms/djangoapps/discussion/settings/common.py | lms/djangoapps/discussion/settings/common.py | """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
}
| """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
# .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
# .. toggle_implementation: DjangoSetting
# .. toggle_default: False
# .. toggle_description: If True, it adds an option to show/hide the discussions tab.
# .. toggle_use_cases: open_edx
# .. toggle_creation_date: 2015-06-15
# .. toggle_target_removal_date: None
# .. toggle_warnings: None
# .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
}
| Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag | Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
| Python | agpl-3.0 | EDUlib/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,edx/edx-platform,angelapper/edx-platform,edx/edx-platform,angelapper/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform | """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
+ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
+ # .. toggle_implementation: DjangoSetting
+ # .. toggle_default: False
+ # .. toggle_description: If True, it adds an option to show/hide the discussions tab.
+ # .. toggle_use_cases: open_edx
+ # .. toggle_creation_date: 2015-06-15
+ # .. toggle_target_removal_date: None
+ # .. toggle_warnings: None
+ # .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
}
| Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag | ## Code Before:
"""Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
}
## Instruction:
Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
## Code After:
"""Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
# .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
# .. toggle_implementation: DjangoSetting
# .. toggle_default: False
# .. toggle_description: If True, it adds an option to show/hide the discussions tab.
# .. toggle_use_cases: open_edx
# .. toggle_creation_date: 2015-06-15
# .. toggle_target_removal_date: None
# .. toggle_warnings: None
# .. toggle_tickets: https://github.com/edx/edx-platform/pull/8474
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
}
|
90ca340883077f57ba63127db058a8d244ec6f4c | molecule/ui/tests/conftest.py | molecule/ui/tests/conftest.py | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
| import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
| Switch UI tests back to google chrome. | Switch UI tests back to google chrome.
| Python | apache-2.0 | Graylog2/graylog-ansible-role | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
- from webdriver_manager.utils import ChromeType
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
- driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options)
+ driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
| Switch UI tests back to google chrome. | ## Code Before:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
## Instruction:
Switch UI tests back to google chrome.
## Code After:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
|
760506e88d22d86be818017fb6075abe7af2a068 | dactyl.py | dactyl.py | from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
| from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
def url_validator(url):
try:
code = urllib.urlopen(url).getcode()
if code == 200:
return True
except:
return False
def test_url(message, url):
if url_validator(url[1:len(url)-1]):
message.reply('VALID URL')
else:
message.reply('NOT VALID URL')
| Add url_validator function and respond aciton to test url | Add url_validator function and respond aciton to test url
| Python | mit | KrzysztofSendor/dactyl | from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
+
+ def url_validator(url):
+ try:
+ code = urllib.urlopen(url).getcode()
+ if code == 200:
+ return True
+ except:
+ return False
+
+
+ def test_url(message, url):
+ if url_validator(url[1:len(url)-1]):
+ message.reply('VALID URL')
+ else:
+ message.reply('NOT VALID URL')
+ | Add url_validator function and respond aciton to test url | ## Code Before:
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
## Instruction:
Add url_validator function and respond aciton to test url
## Code After:
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
def url_validator(url):
try:
code = urllib.urlopen(url).getcode()
if code == 200:
return True
except:
return False
def test_url(message, url):
if url_validator(url[1:len(url)-1]):
message.reply('VALID URL')
else:
message.reply('NOT VALID URL')
|
1b8efb09ac512622ea3541d950ffc67b0a183178 | survey/signals.py | survey/signals.py | import django.dispatch
survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
| import django.dispatch
# providing_args=["instance", "data"]
survey_completed = django.dispatch.Signal()
| Remove puyrely documental providing-args argument | Remove puyrely documental providing-args argument
See https://docs.djangoproject.com/en/4.0/releases/3.1/#id2
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey | import django.dispatch
- survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
+ # providing_args=["instance", "data"]
+ survey_completed = django.dispatch.Signal()
| Remove puyrely documental providing-args argument | ## Code Before:
import django.dispatch
survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
## Instruction:
Remove puyrely documental providing-args argument
## Code After:
import django.dispatch
# providing_args=["instance", "data"]
survey_completed = django.dispatch.Signal()
|
231657e2bbc81b8299cc91fd24dcd7394f74b4ec | python/dpu_utils/codeutils/identifiersplitting.py | python/dpu_utils/codeutils/identifiersplitting.py | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$])|"
"_")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
| from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$.'\"])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$.'\"])|"
"_|\\s+")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s.lower() for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
| Revert to some of the previous behavior for characters that shouldn't appear in identifiers. | Revert to some of the previous behavior for characters that shouldn't appear in identifiers.
| Python | mit | microsoft/dpu-utils,microsoft/dpu-utils | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
- "(?<=[@$])(?=[a-zA-Z0-9])|"
+ "(?<=[@$.'\"])(?=[a-zA-Z0-9])|"
- "(?<=[a-zA-Z0-9])(?=[@$])|"
+ "(?<=[a-zA-Z0-9])(?=[@$.'\"])|"
- "_")
+ "_|\\s+")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
- identifier_parts = list(s for s in SPLIT_REGEX.split(identifier) if len(s)>0)
+ identifier_parts = list(s.lower() for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
| Revert to some of the previous behavior for characters that shouldn't appear in identifiers. | ## Code Before:
from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$])|"
"_")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
## Instruction:
Revert to some of the previous behavior for characters that shouldn't appear in identifiers.
## Code After:
from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$.'\"])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@$.'\"])|"
"_|\\s+")
if sys.version_info >= (3, 7):
import re
SPLIT_REGEX = re.compile(REGEX_TEXT)
else:
import regex
SPLIT_REGEX = regex.compile("(?V1)"+REGEX_TEXT)
@lru_cache(maxsize=5000)
def split_identifier_into_parts(identifier: str) -> List[str]:
"""
Split a single identifier into parts on snake_case and camelCase
"""
identifier_parts = list(s.lower() for s in SPLIT_REGEX.split(identifier) if len(s)>0)
if len(identifier_parts) == 0:
return [identifier]
return identifier_parts
|
81460f88ee19fb736dfc3453df2905f0ba4b3974 | common/permissions.py | common/permissions.py | from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(token, 'scope'):
assert False, ('TokenHasReadWriteScope requires the'
'`OAuth2Authentication` authentication '
'class to be used.')
if hasattr(obj, 'user'):
print 'token.user', token.user
print 'obj.user', obj.user
return token.user == obj.user
| from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(token, 'scope'):
assert False, ('ObjectHasTokenUser requires the'
'`OAuth2Authentication` authentication '
'class to be used.')
if hasattr(obj, 'user'):
return token.user == obj.user
| Remove debugging code, fix typo | Remove debugging code, fix typo
| Python | mit | PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans | from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(token, 'scope'):
- assert False, ('TokenHasReadWriteScope requires the'
+ assert False, ('ObjectHasTokenUser requires the'
'`OAuth2Authentication` authentication '
'class to be used.')
if hasattr(obj, 'user'):
- print 'token.user', token.user
- print 'obj.user', obj.user
-
return token.user == obj.user
| Remove debugging code, fix typo | ## Code Before:
from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(token, 'scope'):
assert False, ('TokenHasReadWriteScope requires the'
'`OAuth2Authentication` authentication '
'class to be used.')
if hasattr(obj, 'user'):
print 'token.user', token.user
print 'obj.user', obj.user
return token.user == obj.user
## Instruction:
Remove debugging code, fix typo
## Code After:
from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(token, 'scope'):
assert False, ('ObjectHasTokenUser requires the'
'`OAuth2Authentication` authentication '
'class to be used.')
if hasattr(obj, 'user'):
return token.user == obj.user
|
65336509829a42b91b000d2e423ed4581ac61c98 | app/mpv.py | app/mpv.py | import sys
import json
import struct
import subprocess
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
subprocess.call(["mpv", mpv_args])
|
import sys
import json
import struct
import subprocess
import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
args = shlex.split("mpv " + mpv_args)
subprocess.call(args)
sys.exit(0)
| Handle shell args in python scripts | Handle shell args in python scripts
| Python | mit | vayan/external-video,vayan/external-video,vayan/external-video,vayan/external-video | +
import sys
import json
import struct
import subprocess
+ import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
- messageLength = struct.unpack('@I', rawLength)[0]
+ messageLength = struct.unpack('@I', rawLength)[0]
- message = sys.stdin.read(messageLength)
+ message = sys.stdin.read(messageLength)
- return json.loads(message)
+ return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
+ args = shlex.split("mpv " + mpv_args)
- subprocess.call(["mpv", mpv_args])
+ subprocess.call(args)
+ sys.exit(0)
| Handle shell args in python scripts | ## Code Before:
import sys
import json
import struct
import subprocess
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
subprocess.call(["mpv", mpv_args])
## Instruction:
Handle shell args in python scripts
## Code After:
import sys
import json
import struct
import subprocess
import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent)
encodedLength = struct.pack('@I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
sys.stdout.flush()
while True:
mpv_args = getMessage()
if (len(mpv_args) > 1):
args = shlex.split("mpv " + mpv_args)
subprocess.call(args)
sys.exit(0)
|
83d5cc3b4ffb4759e8e073d04299a55802df09a8 | src/ansible/views.py | src/ansible/views.py | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return "200"
| from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return HttpResponse("200")
| Fix return to use HttpResponse | Fix return to use HttpResponse
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
- return "200"
+ return HttpResponse("200")
| Fix return to use HttpResponse | ## Code Before:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return "200"
## Instruction:
Fix return to use HttpResponse
## Code After:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return HttpResponse("200")
|
88e5ecad9966057203a9cbecaeaecdca3e76b6da | tests/fake_filesystem.py | tests/fake_filesystem.py | import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
| import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
def close(self):
"""
Always hold fake files open.
"""
pass
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
| Define noop close() for FakeFile | Define noop close() for FakeFile
| Python | bsd-2-clause | kxxoling/fabric,rodrigc/fabric,qinrong/fabric,elijah513/fabric,bspink/fabric,MjAbuz/fabric,cmattoon/fabric,hrubi/fabric,felix-d/fabric,askulkarni2/fabric,SamuelMarks/fabric,mathiasertl/fabric,tekapo/fabric,StackStorm/fabric,ploxiln/fabric,kmonsoor/fabric,raimon49/fabric,haridsv/fabric,bitprophet/fabric,fernandezcuesta/fabric,itoed/fabric,rane-hs/fabric-py3,sdelements/fabric,likesxuqiang/fabric,bitmonk/fabric,getsentry/fabric,opavader/fabric,jaraco/fabric,xLegoz/fabric,TarasRudnyk/fabric,pgroudas/fabric,akaariai/fabric,rbramwell/fabric,amaniak/fabric,cgvarela/fabric,tolbkni/fabric,pashinin/fabric | import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
+ def close(self):
+ """
+ Always hold fake files open.
+ """
+ pass
+
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
| Define noop close() for FakeFile | ## Code Before:
import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
## Instruction:
Define noop close() for FakeFile
## Code After:
import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
def close(self):
"""
Always hold fake files open.
"""
pass
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
|
f45b3e73b6258c99aed2bff2e7350f1c797ff849 | providers/provider.py | providers/provider.py | import copy
import json
import requests
import html5lib
from application import APPLICATION as APP
# Be compatible with python 2 and 3
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
| import copy
import json
from urllib.parse import urlencode
import html5lib
import requests
from application import APPLICATION as APP
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
| Remove support for Python 2. | Remove support for Python 2.
| Python | mit | EmilStenstrom/nephele | import copy
import json
+ from urllib.parse import urlencode
+
+ import html5lib
import requests
- import html5lib
from application import APPLICATION as APP
- # Be compatible with python 2 and 3
- try:
- from urllib import urlencode
- except ImportError:
- from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
| Remove support for Python 2. | ## Code Before:
import copy
import json
import requests
import html5lib
from application import APPLICATION as APP
# Be compatible with python 2 and 3
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
## Instruction:
Remove support for Python 2.
## Code After:
import copy
import json
from urllib.parse import urlencode
import html5lib
import requests
from application import APPLICATION as APP
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
|
cdd32dd3e346f72f823cc5d3f59c79c027db65c8 | common.py | common.py | """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def open_url(url, task):
"""Retrieve data from the specified url."""
for attempt in range(0, net.retries):
try:
return urllib.request.urlopen(url)
except OSError:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
def urlopen_json(url, task):
"""Retrieve json data from the specified url."""
for attempt in range(0, net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
| """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def open_url(url, task):
"""Retrieve data from the specified url."""
for attempt in range(0, net.retries):
try:
return urllib.request.urlopen(url)
except OSError:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
def urlopen_json(url, task="Unknown task"):
"""Retrieve json data from the specified url."""
for attempt in range(0, net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
| Make task an optional argument. | Make task an optional argument.
| Python | bsd-2-clause | chingc/DJRivals,chingc/DJRivals | """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def open_url(url, task):
"""Retrieve data from the specified url."""
for attempt in range(0, net.retries):
try:
return urllib.request.urlopen(url)
except OSError:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
- def urlopen_json(url, task):
+ def urlopen_json(url, task="Unknown task"):
"""Retrieve json data from the specified url."""
for attempt in range(0, net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
| Make task an optional argument. | ## Code Before:
"""Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def open_url(url, task):
"""Retrieve data from the specified url."""
for attempt in range(0, net.retries):
try:
return urllib.request.urlopen(url)
except OSError:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
def urlopen_json(url, task):
"""Retrieve json data from the specified url."""
for attempt in range(0, net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
## Instruction:
Make task an optional argument.
## Code After:
"""Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def open_url(url, task):
"""Retrieve data from the specified url."""
for attempt in range(0, net.retries):
try:
return urllib.request.urlopen(url)
except OSError:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
def urlopen_json(url, task="Unknown task"):
"""Retrieve json data from the specified url."""
for attempt in range(0, net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
|
150e338b7d2793c434d7e2f21aef061f35634476 | openspending/test/__init__.py | openspending/test/__init__.py |
import os
import sys
from paste.deploy import appconfig
from openspending import mongo
from helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
here_dir = os.getcwd()
config = appconfig('config:test.ini', relative_to=here_dir)
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def teardown(self):
clean_all()
super(DatabaseTestCase, self).teardown() |
import os
import sys
from pylons import config
from openspending import mongo
from .helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def teardown(self):
clean_all()
super(DatabaseTestCase, self).teardown() | Use config given on command line | Use config given on command line
| Python | agpl-3.0 | pudo/spendb,openspending/spendb,openspending/spendb,nathanhilbert/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,johnjohndoe/spendb,USStateDept/FPA_Core,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,openspending/spendb,USStateDept/FPA_Core,spendb/spendb,nathanhilbert/FPA_Core,spendb/spendb,pudo/spendb,spendb/spendb,CivicVision/datahub |
import os
import sys
- from paste.deploy import appconfig
+ from pylons import config
from openspending import mongo
- from helpers import clean_all
+ from .helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
- here_dir = os.getcwd()
- config = appconfig('config:test.ini', relative_to=here_dir)
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def teardown(self):
clean_all()
super(DatabaseTestCase, self).teardown() | Use config given on command line | ## Code Before:
import os
import sys
from paste.deploy import appconfig
from openspending import mongo
from helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
here_dir = os.getcwd()
config = appconfig('config:test.ini', relative_to=here_dir)
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def teardown(self):
clean_all()
super(DatabaseTestCase, self).teardown()
## Instruction:
Use config given on command line
## Code After:
import os
import sys
from pylons import config
from openspending import mongo
from .helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def teardown(self):
clean_all()
super(DatabaseTestCase, self).teardown() |
37a0cb41a88114ab9edb514e29447756b0c3e92a | tests/test_cli.py | tests/test_cli.py |
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result = runner.invoke(main, [version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
|
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
| Use cli_runner fixture in test | Use cli_runner fixture in test
| Python | bsd-3-clause | hackebrot/cibopath |
- from click.testing import CliRunner
import pytest
- from cibopath.cli import main
from cibopath import __version__
-
- runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
- def test_cli_group_version_option(version_cli_flag):
+ def test_cli_group_version_option(cli_runner, version_cli_flag):
- result = runner.invoke(main, [version_cli_flag])
+ result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
| Use cli_runner fixture in test | ## Code Before:
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result = runner.invoke(main, [version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
## Instruction:
Use cli_runner fixture in test
## Code After:
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output == 'cibopath, version {}\n'.format(__version__)
|
f814e945d3e62c87c5f86ef5ac37c5feb733b83d | tests/test_ext.py | tests/test_ext.py | from __future__ import absolute_import, unicode_literals
import unittest
from mopidy import config, ext
class ExtensionTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.ext = ext.Extension()
def test_dist_name_is_none(self):
self.assertIsNone(self.ext.dist_name)
def test_ext_name_is_none(self):
self.assertIsNone(self.ext.ext_name)
def test_version_is_none(self):
self.assertIsNone(self.ext.version)
def test_get_default_config_raises_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.ext.get_default_config()
def test_get_config_schema_returns_extension_schema(self):
schema = self.ext.get_config_schema()
self.assertIsInstance(schema['enabled'], config.Boolean)
def test_validate_environment_does_nothing_by_default(self):
self.assertIsNone(self.ext.validate_environment())
def test_setup_raises_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.ext.setup(None)
| from __future__ import absolute_import, unicode_literals
import pytest
from mopidy import config, ext
@pytest.fixture
def extension():
return ext.Extension()
def test_dist_name_is_none(extension):
assert extension.dist_name is None
def test_ext_name_is_none(extension):
assert extension.ext_name is None
def test_version_is_none(extension):
assert extension.version is None
def test_get_default_config_raises_not_implemented(extension):
with pytest.raises(NotImplementedError):
extension.get_default_config()
def test_get_config_schema_returns_extension_schema(extension):
schema = extension.get_config_schema()
assert isinstance(schema['enabled'], config.Boolean)
def test_validate_environment_does_nothing_by_default(extension):
assert extension.validate_environment() is None
def test_setup_raises_not_implemented(extension):
with pytest.raises(NotImplementedError):
extension.setup(None)
| Convert ext test to pytests | tests: Convert ext test to pytests
| Python | apache-2.0 | mokieyue/mopidy,bencevans/mopidy,ZenithDK/mopidy,jodal/mopidy,quartz55/mopidy,pacificIT/mopidy,pacificIT/mopidy,quartz55/mopidy,ali/mopidy,swak/mopidy,tkem/mopidy,bencevans/mopidy,mopidy/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,hkariti/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,ali/mopidy,bacontext/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,dbrgn/mopidy,mopidy/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,bacontext/mopidy,vrs01/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,vrs01/mopidy,dbrgn/mopidy,jcass77/mopidy,glogiotatidis/mopidy,swak/mopidy,bencevans/mopidy,mokieyue/mopidy,adamcik/mopidy,tkem/mopidy,rawdlite/mopidy,bacontext/mopidy,pacificIT/mopidy,ali/mopidy,jcass77/mopidy,rawdlite/mopidy,mopidy/mopidy,vrs01/mopidy,tkem/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,tkem/mopidy,jodal/mopidy,diandiankan/mopidy,jmarsik/mopidy,quartz55/mopidy,ZenithDK/mopidy,jodal/mopidy,ZenithDK/mopidy,jmarsik/mopidy,swak/mopidy,ZenithDK/mopidy,bacontext/mopidy,kingosticks/mopidy,quartz55/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,hkariti/mopidy,ali/mopidy,hkariti/mopidy,adamcik/mopidy,vrs01/mopidy,rawdlite/mopidy,hkariti/mopidy,rawdlite/mopidy,mokieyue/mopidy,adamcik/mopidy,swak/mopidy,kingosticks/mopidy,bencevans/mopidy,jmarsik/mopidy,jcass77/mopidy | from __future__ import absolute_import, unicode_literals
- import unittest
+ import pytest
from mopidy import config, ext
- class ExtensionTest(unittest.TestCase):
+ @pytest.fixture
+ def extension():
+ return ext.Extension()
- def setUp(self): # noqa: N802
- self.ext = ext.Extension()
- def test_dist_name_is_none(self):
+ def test_dist_name_is_none(extension):
- self.assertIsNone(self.ext.dist_name)
+ assert extension.dist_name is None
- def test_ext_name_is_none(self):
- self.assertIsNone(self.ext.ext_name)
- def test_version_is_none(self):
- self.assertIsNone(self.ext.version)
+ def test_ext_name_is_none(extension):
+ assert extension.ext_name is None
- def test_get_default_config_raises_not_implemented(self):
- with self.assertRaises(NotImplementedError):
- self.ext.get_default_config()
+ def test_version_is_none(extension):
+ assert extension.version is None
- def test_get_config_schema_returns_extension_schema(self):
- schema = self.ext.get_config_schema()
- self.assertIsInstance(schema['enabled'], config.Boolean)
- def test_validate_environment_does_nothing_by_default(self):
- self.assertIsNone(self.ext.validate_environment())
- def test_setup_raises_not_implemented(self):
+ def test_get_default_config_raises_not_implemented(extension):
- with self.assertRaises(NotImplementedError):
+ with pytest.raises(NotImplementedError):
- self.ext.setup(None)
+ extension.get_default_config()
+
+ def test_get_config_schema_returns_extension_schema(extension):
+ schema = extension.get_config_schema()
+ assert isinstance(schema['enabled'], config.Boolean)
+
+
+ def test_validate_environment_does_nothing_by_default(extension):
+ assert extension.validate_environment() is None
+
+
+ def test_setup_raises_not_implemented(extension):
+ with pytest.raises(NotImplementedError):
+ extension.setup(None)
+ | Convert ext test to pytests | ## Code Before:
from __future__ import absolute_import, unicode_literals
import unittest
from mopidy import config, ext
class ExtensionTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.ext = ext.Extension()
def test_dist_name_is_none(self):
self.assertIsNone(self.ext.dist_name)
def test_ext_name_is_none(self):
self.assertIsNone(self.ext.ext_name)
def test_version_is_none(self):
self.assertIsNone(self.ext.version)
def test_get_default_config_raises_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.ext.get_default_config()
def test_get_config_schema_returns_extension_schema(self):
schema = self.ext.get_config_schema()
self.assertIsInstance(schema['enabled'], config.Boolean)
def test_validate_environment_does_nothing_by_default(self):
self.assertIsNone(self.ext.validate_environment())
def test_setup_raises_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.ext.setup(None)
## Instruction:
Convert ext test to pytests
## Code After:
from __future__ import absolute_import, unicode_literals
import pytest
from mopidy import config, ext
@pytest.fixture
def extension():
return ext.Extension()
def test_dist_name_is_none(extension):
assert extension.dist_name is None
def test_ext_name_is_none(extension):
assert extension.ext_name is None
def test_version_is_none(extension):
assert extension.version is None
def test_get_default_config_raises_not_implemented(extension):
with pytest.raises(NotImplementedError):
extension.get_default_config()
def test_get_config_schema_returns_extension_schema(extension):
schema = extension.get_config_schema()
assert isinstance(schema['enabled'], config.Boolean)
def test_validate_environment_does_nothing_by_default(extension):
assert extension.validate_environment() is None
def test_setup_raises_not_implemented(extension):
with pytest.raises(NotImplementedError):
extension.setup(None)
|
27ffcae96c5dce976517035b25a5c72f10e2ec99 | tool_spatialdb.py | tool_spatialdb.py |
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Replace(CCFLAGS=['-g','-O2'])
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
|
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
| Use GLOBAL_TOOLs rather than Export/Import for project wide configuration. | Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
| Python | bsd-3-clause | ncareol/spatialdb,ncareol/spatialdb |
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
- env.Replace(CCFLAGS=['-g','-O2'])
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
| Use GLOBAL_TOOLs rather than Export/Import for project wide configuration. | ## Code Before:
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Replace(CCFLAGS=['-g','-O2'])
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
## Instruction:
Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
## Code After:
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
env.AppendLibrary('geos')
env.AppendLibrary('geos_c')
env.AppendLibrary('proj')
if (platform != 'posix'):
env.AppendLibrary('iconv')
env.Require(tools)
Export('spatialdb')
# build the SpatialDB library
libsources = Split("""
SpatiaLiteDB.cpp
""")
headers = Split("""
SpatiaLiteDB.h
""")
libspatialdb = env.Library('spatialdb', libsources)
env.Default(libspatialdb)
html = env.Apidocs(libsources + headers, DOXYFILE_DICT={'PROJECT_NAME':'SpatialDB', 'PROJECT_NUMBER':'1.0'})
|
da59d7481668a7133eebcd12b4d5ecfb655296a6 | test/test_blob_filter.py | test/test_blob_filter.py | """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, stage_type, path, expected_result', [
((Path("foo"),), 0, Path("foo"), True),
((Path("foo"),), 0, Path("foo/bar"), True),
((Path("foo/bar"),), 0, Path("foo"), False),
((Path("foo"), Path("bar")), 0, Path("foo"), True),
])
# fmt: on
def test_blob_filter(paths: Sequence[PathLike], stage_type: StageType, path: PathLike, expected_result: bool) -> None:
"""Test the blob filter."""
blob_filter = BlobFilter(paths)
binsha = MagicMock(__len__=lambda self: 20)
blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path)
stage_blob: Tuple[StageType, Blob] = (stage_type, blob)
result = blob_filter(stage_blob)
assert result == expected_result
| """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, path, expected_result', [
((Path("foo"),), Path("foo"), True),
((Path("foo"),), Path("foo/bar"), True),
((Path("foo/bar"),), Path("foo"), False),
((Path("foo"), Path("bar")), Path("foo"), True),
])
# fmt: on
def test_blob_filter(paths: Sequence[PathLike], path: PathLike, expected_result: bool) -> None:
"""Test the blob filter."""
blob_filter = BlobFilter(paths)
binsha = MagicMock(__len__=lambda self: 20)
stage_type: StageType = 0
blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path)
stage_blob: Tuple[StageType, Blob] = (stage_type, blob)
result = blob_filter(stage_blob)
assert result == expected_result
| Remove stage type as parameter from blob filter test | Remove stage type as parameter from blob filter test
| Python | bsd-3-clause | gitpython-developers/GitPython,gitpython-developers/gitpython,gitpython-developers/GitPython,gitpython-developers/gitpython | """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
- @pytest.mark.parametrize('paths, stage_type, path, expected_result', [
+ @pytest.mark.parametrize('paths, path, expected_result', [
- ((Path("foo"),), 0, Path("foo"), True),
+ ((Path("foo"),), Path("foo"), True),
- ((Path("foo"),), 0, Path("foo/bar"), True),
+ ((Path("foo"),), Path("foo/bar"), True),
- ((Path("foo/bar"),), 0, Path("foo"), False),
+ ((Path("foo/bar"),), Path("foo"), False),
- ((Path("foo"), Path("bar")), 0, Path("foo"), True),
+ ((Path("foo"), Path("bar")), Path("foo"), True),
])
# fmt: on
- def test_blob_filter(paths: Sequence[PathLike], stage_type: StageType, path: PathLike, expected_result: bool) -> None:
+ def test_blob_filter(paths: Sequence[PathLike], path: PathLike, expected_result: bool) -> None:
"""Test the blob filter."""
blob_filter = BlobFilter(paths)
binsha = MagicMock(__len__=lambda self: 20)
+ stage_type: StageType = 0
blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path)
stage_blob: Tuple[StageType, Blob] = (stage_type, blob)
result = blob_filter(stage_blob)
assert result == expected_result
| Remove stage type as parameter from blob filter test | ## Code Before:
"""Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, stage_type, path, expected_result', [
((Path("foo"),), 0, Path("foo"), True),
((Path("foo"),), 0, Path("foo/bar"), True),
((Path("foo/bar"),), 0, Path("foo"), False),
((Path("foo"), Path("bar")), 0, Path("foo"), True),
])
# fmt: on
def test_blob_filter(paths: Sequence[PathLike], stage_type: StageType, path: PathLike, expected_result: bool) -> None:
"""Test the blob filter."""
blob_filter = BlobFilter(paths)
binsha = MagicMock(__len__=lambda self: 20)
blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path)
stage_blob: Tuple[StageType, Blob] = (stage_type, blob)
result = blob_filter(stage_blob)
assert result == expected_result
## Instruction:
Remove stage type as parameter from blob filter test
## Code After:
"""Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, path, expected_result', [
((Path("foo"),), Path("foo"), True),
((Path("foo"),), Path("foo/bar"), True),
((Path("foo/bar"),), Path("foo"), False),
((Path("foo"), Path("bar")), Path("foo"), True),
])
# fmt: on
def test_blob_filter(paths: Sequence[PathLike], path: PathLike, expected_result: bool) -> None:
"""Test the blob filter."""
blob_filter = BlobFilter(paths)
binsha = MagicMock(__len__=lambda self: 20)
stage_type: StageType = 0
blob: Blob = Blob(repo=MagicMock(), binsha=binsha, path=path)
stage_blob: Tuple[StageType, Blob] = (stage_type, blob)
result = blob_filter(stage_blob)
assert result == expected_result
|
431ca4f2d44656ef9f97be50718712c6f3a0fa9b | qtawesome/tests/test_qtawesome.py | qtawesome/tests/test_qtawesome.py | # Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
prefixes = list(resource.fontname.keys())
assert prefixes
fontnames = set(resource.fontname.values())
assert fontnames
assert len(prefixes) == len(fontnames)
if __name__ == "__main__":
pytest.main()
| # Standard library imports
import subprocess
import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
# Check that the fonts were loaded successfully.
fontnames = resource.fontname.values()
assert fontnames
# Check that qtawesome does not load fonts with duplicate family names.
duplicates = [fontname for fontname, count in
collections.Counter(fontnames).items() if count > 1]
assert not duplicates
if __name__ == "__main__":
pytest.main()
| Make the test more comprehensive. | Make the test more comprehensive.
| Python | mit | spyder-ide/qtawesome | # Standard library imports
import subprocess
+ import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
+ # Check that the fonts were loaded successfully.
- prefixes = list(resource.fontname.keys())
- assert prefixes
-
- fontnames = set(resource.fontname.values())
+ fontnames = resource.fontname.values()
assert fontnames
- assert len(prefixes) == len(fontnames)
+ # Check that qtawesome does not load fonts with duplicate family names.
+ duplicates = [fontname for fontname, count in
+ collections.Counter(fontnames).items() if count > 1]
+ assert not duplicates
if __name__ == "__main__":
pytest.main()
| Make the test more comprehensive. | ## Code Before:
# Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
prefixes = list(resource.fontname.keys())
assert prefixes
fontnames = set(resource.fontname.values())
assert fontnames
assert len(prefixes) == len(fontnames)
if __name__ == "__main__":
pytest.main()
## Instruction:
Make the test more comprehensive.
## Code After:
# Standard library imports
import subprocess
import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon()"', shell=True)
assert output_number == 0
def test_unique_font_family_name(qtbot):
"""
Test that each font used by qtawesome has a unique name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
Regression test for Issue #107
"""
resource = qta._instance()
assert isinstance(resource, IconicFont)
# Check that the fonts were loaded successfully.
fontnames = resource.fontname.values()
assert fontnames
# Check that qtawesome does not load fonts with duplicate family names.
duplicates = [fontname for fontname, count in
collections.Counter(fontnames).items() if count > 1]
assert not duplicates
if __name__ == "__main__":
pytest.main()
|
3d8ec94e61735b84c3b24b44d79fcd57611a93ee | mndeps.py | mndeps.py | from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo,
'torus': TorusTopo }
def build(opts):
return buildTopo(TOPOS, opts)
| from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo
}
def build(opts):
return buildTopo(TOPOS, opts)
| Fix bug after removing torus | Fix bug after removing torus
| Python | apache-2.0 | ravel-net/ravel,ravel-net/ravel | from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
- 'tree': TreeTopo,
+ 'tree': TreeTopo
- 'torus': TorusTopo }
+ }
def build(opts):
return buildTopo(TOPOS, opts)
| Fix bug after removing torus | ## Code Before:
from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo,
'torus': TorusTopo }
def build(opts):
return buildTopo(TOPOS, opts)
## Instruction:
Fix bug after removing torus
## Code After:
from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo
}
def build(opts):
return buildTopo(TOPOS, opts)
|