commit
stringlengths 40
40
| old_file
stringlengths 4
234
| new_file
stringlengths 4
234
| old_contents
stringlengths 10
3.01k
| new_contents
stringlengths 19
3.38k
| subject
stringlengths 16
736
| message
stringlengths 17
2.63k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
82.6k
| config
stringclasses 4
values | content
stringlengths 134
4.41k
| fuzzy_diff
stringlengths 29
3.44k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
c9b97f6d1148378d1ba7189a1838ea03e240de40
|
pycron/__init__.py
|
pycron/__init__.py
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
Add parsing for list of numbers.
|
Add parsing for list of numbers.
|
Python
|
mit
|
kipe/pycron
|
python
|
## Code Before:
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
## Instruction:
Add parsing for list of numbers.
## Code After:
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
...
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
return False
if '/' in value:
value, interval = value.split('/')
...
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
...
|
54d4551ce8efb16d4a8d02e38b9f223f8f1cd816
|
ab_game.py
|
ab_game.py
|
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
if depth > 4:
min_priority = 3
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
|
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
|
Disable min_priority filter for now
|
Disable min_priority filter for now
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
python
|
## Code Before:
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
if depth > 4:
min_priority = 3
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
## Instruction:
Disable min_priority filter for now
## Code After:
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_game = base_game
def to_move(self, state=None):
if state is None:
state = self.current_state
return state.to_move()
def utility(self, state):
return state.utility()
def successors(self, state, depth):
mn = state.get_move_number()
if mn == 1:
# The first black move is always in the centre
brd_size = self.base_game.get_board().get_size()
centre_pos = (brd_size/2, brd_size/2)
p_i = [centre_pos]
else:
min_priority = 0
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
tried_count = 0
for pos in p_i:
# create an AB_State for each possible move from state
succ = state.create_state(pos)
yield pos, succ
tried_count += 1
if depth > 3 and tried_count >= 2:
return
def terminal_test(self, state):
return state.terminal()
|
...
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
...
p_i = [centre_pos]
else:
min_priority = 0
pos_iter = state.get_iter(state.to_move())
p_i = pos_iter.get_iter(state.to_move_colour(), min_priority)
...
|
6ba28684960b14ecb29b26d63ae4a593337e7fa4
|
examples/wordy.py
|
examples/wordy.py
|
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain")
pgm.add_edge("cloudy", "sprinkler")
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
|
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain", label="65\%", xoffset=-.1, label_params={"rotation": 45})
pgm.add_edge("cloudy", "sprinkler", label="35\%", xoffset=.1, label_params={"rotation": -45})
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
|
Add edge label and rotation.
|
Add edge label and rotation.
|
Python
|
mit
|
dfm/daft
|
python
|
## Code Before:
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain")
pgm.add_edge("cloudy", "sprinkler")
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
## Instruction:
Add edge label and rotation.
## Code After:
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain", label="65\%", xoffset=-.1, label_params={"rotation": 45})
pgm.add_edge("cloudy", "sprinkler", label="35\%", xoffset=.1, label_params={"rotation": -45})
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
|
// ... existing code ...
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain", label="65\%", xoffset=-.1, label_params={"rotation": 45})
pgm.add_edge("cloudy", "sprinkler", label="35\%", xoffset=.1, label_params={"rotation": -45})
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
// ... rest of the code ...
|
824ead425a80feeb7dc1fbd6505cf50c6e2ffd90
|
ui_extensions/playground/views.py
|
ui_extensions/playground/views.py
|
from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtensionDelegate):
def should_display(self):
return True
@admin_extension(
title="Playground Admin",
description="Entrypoint for Playground Admin Extension")
def show_admin_extension(request, **kwargs):
return render(request, template_name='playground/templates/admin.html')
# We want this tab to display for all resource handlers, so we set the model
# to the ResourceHandler object. If we wanted to target a specific resource
# handler, we could get more specific, e.g. AWSHandler
@tab_extension(
model=ResourceHandler,
title="Playground",
description="Entrypoint for Playground Resource Handler Tab Extension",
delegate=ResourceHandlerTabDelegate
)
def show_rh_tab_extension(request, model_id, **kwargs):
return render(request, template_name='playground/templates/tab.html')
@dashboard_extension(
title="Playground",
description='Playground widget')
def show_playground_widget(request):
return render(request, template_name='playground/templates/widget.html')
|
from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtensionDelegate):
# We want this tab to display for all resource handlers, so we return
# True regardless of what Resource Handler is being displayed.
# If the goal is to target a specific Resource
# Handler, say AWSHandler, the body of this method would be:
# return if isinstance(self.instance.cast(), AWSHandler) else False
def should_display(self):
return True
@admin_extension(
title="Playground Admin",
description="Entrypoint for Playground Admin Extension")
def show_admin_extension(request, **kwargs):
return render(request, template_name='playground/templates/admin.html')
@tab_extension(
model=ResourceHandler,
title="Playground",
description="Entrypoint for Playground Resource Handler Tab Extension",
delegate=ResourceHandlerTabDelegate
)
def show_rh_tab_extension(request, model_id, **kwargs):
return render(request, template_name='playground/templates/tab.html')
@dashboard_extension(
title="Playground",
description='Playground widget')
def show_playground_widget(request):
return render(request, template_name='playground/templates/widget.html')
|
Add more info to TabDelegate example
|
Add more info to TabDelegate example
Provide details on how to limit a tab delegate to a specific resource handler.
|
Python
|
apache-2.0
|
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
|
python
|
## Code Before:
from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtensionDelegate):
def should_display(self):
return True
@admin_extension(
title="Playground Admin",
description="Entrypoint for Playground Admin Extension")
def show_admin_extension(request, **kwargs):
return render(request, template_name='playground/templates/admin.html')
# We want this tab to display for all resource handlers, so we set the model
# to the ResourceHandler object. If we wanted to target a specific resource
# handler, we could get more specific, e.g. AWSHandler
@tab_extension(
model=ResourceHandler,
title="Playground",
description="Entrypoint for Playground Resource Handler Tab Extension",
delegate=ResourceHandlerTabDelegate
)
def show_rh_tab_extension(request, model_id, **kwargs):
return render(request, template_name='playground/templates/tab.html')
@dashboard_extension(
title="Playground",
description='Playground widget')
def show_playground_widget(request):
return render(request, template_name='playground/templates/widget.html')
## Instruction:
Add more info to TabDelegate example
Provide details on how to limit a tab delegate to a specific resource handler.
## Code After:
from django.shortcuts import render
from extensions.views import admin_extension, tab_extension, \
TabExtensionDelegate, dashboard_extension
from resourcehandlers.models import ResourceHandler
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
class ResourceHandlerTabDelegate(TabExtensionDelegate):
# We want this tab to display for all resource handlers, so we return
# True regardless of what Resource Handler is being displayed.
# If the goal is to target a specific Resource
# Handler, say AWSHandler, the body of this method would be:
# return if isinstance(self.instance.cast(), AWSHandler) else False
def should_display(self):
return True
@admin_extension(
title="Playground Admin",
description="Entrypoint for Playground Admin Extension")
def show_admin_extension(request, **kwargs):
return render(request, template_name='playground/templates/admin.html')
@tab_extension(
model=ResourceHandler,
title="Playground",
description="Entrypoint for Playground Resource Handler Tab Extension",
delegate=ResourceHandlerTabDelegate
)
def show_rh_tab_extension(request, model_id, **kwargs):
return render(request, template_name='playground/templates/tab.html')
@dashboard_extension(
title="Playground",
description='Playground widget')
def show_playground_widget(request):
return render(request, template_name='playground/templates/widget.html')
|
// ... existing code ...
class ResourceHandlerTabDelegate(TabExtensionDelegate):
# We want this tab to display for all resource handlers, so we return
# True regardless of what Resource Handler is being displayed.
# If the goal is to target a specific Resource
# Handler, say AWSHandler, the body of this method would be:
# return if isinstance(self.instance.cast(), AWSHandler) else False
def should_display(self):
return True
// ... modified code ...
return render(request, template_name='playground/templates/admin.html')
@tab_extension(
model=ResourceHandler,
title="Playground",
// ... rest of the code ...
|
eaf74f092e73dcb832d624d9f19e9eaee5fbc244
|
pyfakefs/pytest_plugin.py
|
pyfakefs/pytest_plugin.py
|
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
Add linecache module to skipped modules for pytest plugin
|
Add linecache module to skipped modules for pytest plugin
- see #381
- fixes the problem under Python 3, but not under Python 2
|
Python
|
apache-2.0
|
mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,mrbean-bremen/pyfakefs,jmcgeheeiv/pyfakefs
|
python
|
## Code Before:
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
## Instruction:
Add linecache module to skipped modules for pytest plugin
- see #381
- fixes the problem under Python 3, but not under Python 2
## Code After:
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
// ... existing code ...
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
Patcher.SKIPMODULES.add(linecache) # Seems to be used by pytest internally
@pytest.fixture
// ... rest of the code ...
|
ffddc9d9b570116a0d0acc3c6309794cb68db085
|
src/libbitcoind.h
|
src/libbitcoind.h
|
NAN_METHOD(StartBitcoind);
NAN_METHOD(OnBlocksReady);
NAN_METHOD(OnTipUpdate);
NAN_METHOD(IsStopping);
NAN_METHOD(IsStopped);
NAN_METHOD(StopBitcoind);
NAN_METHOD(GetBlock);
NAN_METHOD(GetTransaction);
NAN_METHOD(GetInfo);
NAN_METHOD(IsSpent);
NAN_METHOD(GetBlockIndex);
NAN_METHOD(GetMempoolOutputs);
NAN_METHOD(AddMempoolUncheckedTransaction);
NAN_METHOD(VerifyScript);
NAN_METHOD(SendTransaction);
NAN_METHOD(EstimateFee);
NAN_METHOD(StartTxMon);
NAN_METHOD(GetProgress);
|
NAN_METHOD(StartBitcoind);
NAN_METHOD(OnBlocksReady);
NAN_METHOD(OnTipUpdate);
NAN_METHOD(IsStopping);
NAN_METHOD(IsStopped);
NAN_METHOD(StopBitcoind);
NAN_METHOD(GetBlock);
NAN_METHOD(GetTransaction);
NAN_METHOD(GetInfo);
NAN_METHOD(IsSpent);
NAN_METHOD(GetBlockIndex);
NAN_METHOD(GetMempoolOutputs);
NAN_METHOD(AddMempoolUncheckedTransaction);
NAN_METHOD(VerifyScript);
NAN_METHOD(SendTransaction);
NAN_METHOD(EstimateFee);
NAN_METHOD(StartTxMon);
NAN_METHOD(SyncPercentage);
NAN_METHOD(IsSynced);
|
Fix declarations for IsSynced and SyncPercentage
|
Fix declarations for IsSynced and SyncPercentage
|
C
|
mit
|
isghe/bitcore-node,braydonf/bitcore-node,CryptArc/bitcore-node,jameswalpole/bitcore-node,wzrdtales/bitcore-node,zcoinrocks/bitcore-node,wzrdtales/bitcore-node,jameswalpole/bitcore-node,snogcel/bitcore-node-dash,phplaboratory/psiacore-node,jameswalpole/bitcore-node,wzrdtales/bitcore-node,wzrdtales/bitcore-node,isghe/bitcore-node,CryptArc/bitcore-node,isghe/bitcore-node,wzrdtales/bitcore-node,snogcel/bitcore-node-dash,zcoinrocks/bitcore-node,isghe/bitcore-node,jameswalpole/bitcore-node,CryptArc/bitcore-node,CryptArc/bitcore-node,fanatid/bitcore-node,kleetus/bitcore-node,kleetus/bitcore-node,fanatid/bitcore-node,fanatid/bitcore-node,jameswalpole/bitcore-node,phplaboratory/psiacore-node,fanatid/bitcore-node,phplaboratory/psiacore-node,CryptArc/bitcore-node,phplaboratory/psiacore-node,fanatid/bitcore-node,phplaboratory/psiacore-node,isghe/bitcore-node,braydonf/bitcore-node
|
c
|
## Code Before:
NAN_METHOD(StartBitcoind);
NAN_METHOD(OnBlocksReady);
NAN_METHOD(OnTipUpdate);
NAN_METHOD(IsStopping);
NAN_METHOD(IsStopped);
NAN_METHOD(StopBitcoind);
NAN_METHOD(GetBlock);
NAN_METHOD(GetTransaction);
NAN_METHOD(GetInfo);
NAN_METHOD(IsSpent);
NAN_METHOD(GetBlockIndex);
NAN_METHOD(GetMempoolOutputs);
NAN_METHOD(AddMempoolUncheckedTransaction);
NAN_METHOD(VerifyScript);
NAN_METHOD(SendTransaction);
NAN_METHOD(EstimateFee);
NAN_METHOD(StartTxMon);
NAN_METHOD(GetProgress);
## Instruction:
Fix declarations for IsSynced and SyncPercentage
## Code After:
NAN_METHOD(StartBitcoind);
NAN_METHOD(OnBlocksReady);
NAN_METHOD(OnTipUpdate);
NAN_METHOD(IsStopping);
NAN_METHOD(IsStopped);
NAN_METHOD(StopBitcoind);
NAN_METHOD(GetBlock);
NAN_METHOD(GetTransaction);
NAN_METHOD(GetInfo);
NAN_METHOD(IsSpent);
NAN_METHOD(GetBlockIndex);
NAN_METHOD(GetMempoolOutputs);
NAN_METHOD(AddMempoolUncheckedTransaction);
NAN_METHOD(VerifyScript);
NAN_METHOD(SendTransaction);
NAN_METHOD(EstimateFee);
NAN_METHOD(StartTxMon);
NAN_METHOD(SyncPercentage);
NAN_METHOD(IsSynced);
|
...
NAN_METHOD(SendTransaction);
NAN_METHOD(EstimateFee);
NAN_METHOD(StartTxMon);
NAN_METHOD(SyncPercentage);
NAN_METHOD(IsSynced);
...
|
34c427200c6ab50fb64fa0d6116366a8fa9186a3
|
netman/core/objects/bond.py
|
netman/core/objects/bond.py
|
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
|
import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
@property
def interface(self):
warnings.warn('Deprecated: Use directly the members of Bond instead.',
category=DeprecationWarning)
return self
|
Support deprecated use of the interface property of Bond.
|
Support deprecated use of the interface property of Bond.
|
Python
|
apache-2.0
|
idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman
|
python
|
## Code Before:
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
## Instruction:
Support deprecated use of the interface property of Bond.
## Code After:
import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
@property
def interface(self):
warnings.warn('Deprecated: Use directly the members of Bond instead.',
category=DeprecationWarning)
return self
|
// ... existing code ...
import warnings
from netman.core.objects.interface import BaseInterface
// ... modified code ...
self.number = number
self.link_speed = link_speed
self.members = members or []
@property
def interface(self):
warnings.warn('Deprecated: Use directly the members of Bond instead.',
category=DeprecationWarning)
return self
// ... rest of the code ...
|
8becd32fc042445d62b885bac12dac326b2dc1fa
|
tests/runtests.py
|
tests/runtests.py
|
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner()
testRunner.run(suite)
|
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(suite)
|
Increase a bit verbosity of tests so people know which test failed
|
Increase a bit verbosity of tests so people know which test failed
|
Python
|
lgpl-2.1
|
nzjrs/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,thiblahute/pygobject,GNOME/pygobject,davidmalcolm/pygobject,GNOME/pygobject,sfeltman/pygobject,MathieuDuponchelle/pygobject,jdahlin/pygobject,Distrotech/pygobject,sfeltman/pygobject,davibe/pygobject,nzjrs/pygobject,nzjrs/pygobject,jdahlin/pygobject,pexip/pygobject,alexef/pygobject,davibe/pygobject,davibe/pygobject,MathieuDuponchelle/pygobject,Distrotech/pygobject,Distrotech/pygobject,choeger/pygobject-cmake,choeger/pygobject-cmake,choeger/pygobject-cmake,pexip/pygobject,sfeltman/pygobject,thiblahute/pygobject,davibe/pygobject,pexip/pygobject,alexef/pygobject,thiblahute/pygobject,GNOME/pygobject,jdahlin/pygobject
|
python
|
## Code Before:
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner()
testRunner.run(suite)
## Instruction:
Increase a bit verbosity of tests so people know which test failed
## Code After:
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(suite)
|
...
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(suite)
...
|
2b372d479f8c022d72954396be9a4a045596f497
|
tests/test52.py
|
tests/test52.py
|
import judicious
judicious.seed("cc722bf6-e319-cf63-a671-cbae64dfdb0f")
# 1 (complete): 3799aa89-ccae-c268-d0e8-cc4e9ddddee4
# 2 (timeout) : 4d30601d-dfe3-ee53-8594-7fc0aa8e68ec
# 3 (complete): fe07a885-53c3-9a22-c93e-91436e5d8f0c
# 1 (complete): 4f4d13ed-7d1c-cbee-638d-6aee5188c929
# 2 (timeout) : 720ebe41-5987-b9f0-b571-fd7fb50f2b05
# 3 (timeout) : 358e7d25-af92-8a18-23ec-49025aecc87b
# 4 (complete) : cab5c911-741c-8721-d851-483669940626
def experiment():
with judicious.Person(lifetime=60) as person:
consent = person.consent()
j1 = person.joke()
j2 = person.joke()
j3 = person.joke()
j4 = person.joke()
person.complete()
return [j1, j2, j3, j4]
results = judicious.map3(experiment, [None for _ in range(100)])
print(results)
|
import judicious
# judicious.register("https://imprudent.herokuapp.com")
# judicious.seed("cc722bf6-e319-cf63-a671-cbae64dfd40f")
def experiment():
with judicious.Person(lifetime=60) as person:
if not person.consent():
return None
j1 = person.joke()
j2 = person.joke()
j3 = person.joke()
j4 = person.joke()
person.complete()
return (j1, j2, j3, j4)
results = judicious.map3(experiment, [None for _ in range(1)])
print(results)
|
Update context manager test script
|
Update context manager test script
|
Python
|
mit
|
suchow/judicious,suchow/judicious,suchow/judicious
|
python
|
## Code Before:
import judicious
judicious.seed("cc722bf6-e319-cf63-a671-cbae64dfdb0f")
# 1 (complete): 3799aa89-ccae-c268-d0e8-cc4e9ddddee4
# 2 (timeout) : 4d30601d-dfe3-ee53-8594-7fc0aa8e68ec
# 3 (complete): fe07a885-53c3-9a22-c93e-91436e5d8f0c
# 1 (complete): 4f4d13ed-7d1c-cbee-638d-6aee5188c929
# 2 (timeout) : 720ebe41-5987-b9f0-b571-fd7fb50f2b05
# 3 (timeout) : 358e7d25-af92-8a18-23ec-49025aecc87b
# 4 (complete) : cab5c911-741c-8721-d851-483669940626
def experiment():
with judicious.Person(lifetime=60) as person:
consent = person.consent()
j1 = person.joke()
j2 = person.joke()
j3 = person.joke()
j4 = person.joke()
person.complete()
return [j1, j2, j3, j4]
results = judicious.map3(experiment, [None for _ in range(100)])
print(results)
## Instruction:
Update context manager test script
## Code After:
import judicious
# judicious.register("https://imprudent.herokuapp.com")
# judicious.seed("cc722bf6-e319-cf63-a671-cbae64dfd40f")
def experiment():
with judicious.Person(lifetime=60) as person:
if not person.consent():
return None
j1 = person.joke()
j2 = person.joke()
j3 = person.joke()
j4 = person.joke()
person.complete()
return (j1, j2, j3, j4)
results = judicious.map3(experiment, [None for _ in range(1)])
print(results)
|
...
import judicious
# judicious.register("https://imprudent.herokuapp.com")
# judicious.seed("cc722bf6-e319-cf63-a671-cbae64dfd40f")
def experiment():
with judicious.Person(lifetime=60) as person:
if not person.consent():
return None
j1 = person.joke()
j2 = person.joke()
j3 = person.joke()
j4 = person.joke()
person.complete()
return (j1, j2, j3, j4)
results = judicious.map3(experiment, [None for _ in range(1)])
print(results)
...
|
c1b8f935801ca8925c0f3b001a2582136cb861ad
|
nani.py
|
nani.py
|
from docopt import docopt
import subprocess
if __name__ == '__main__':
arguments = docopt(__doc__, version='nani 0.2.0')
subprocess.call(['which', arguments['<command>']])
|
from docopt import docopt
import sys
import subprocess
if __name__ == '__main__':
arguments = docopt(__doc__, version='nani 0.3.0')
ret = subprocess.call(['type', arguments['<command>']])
sys.exit(ret)
|
Call type instead of which
|
Call type instead of which
|
Python
|
mit
|
fenhl/nani
|
python
|
## Code Before:
from docopt import docopt
import subprocess
if __name__ == '__main__':
arguments = docopt(__doc__, version='nani 0.2.0')
subprocess.call(['which', arguments['<command>']])
## Instruction:
Call type instead of which
## Code After:
from docopt import docopt
import sys
import subprocess
if __name__ == '__main__':
arguments = docopt(__doc__, version='nani 0.3.0')
ret = subprocess.call(['type', arguments['<command>']])
sys.exit(ret)
|
// ... existing code ...
from docopt import docopt
import sys
import subprocess
if __name__ == '__main__':
arguments = docopt(__doc__, version='nani 0.3.0')
ret = subprocess.call(['type', arguments['<command>']])
sys.exit(ret)
// ... rest of the code ...
|
f4bbcc0498100f2de0f786e6eb7365d342e137c5
|
src/main/java/org/usfirst/frc/team1360/robot/RobotMap.java
|
src/main/java/org/usfirst/frc/team1360/robot/RobotMap.java
|
package org.usfirst.frc.team1360.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap
{
/**
* LeftMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_1 = 0;
/**
* LeftMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_2 = 1;
/**
* RightMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_1 = 2;
/**
* RightMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_2 = 3;
/**
* Driver Controller
*/
public static final int JOYSTICK_DRIVER = 0;
/**
* Operator Controller
*/
public static final int JOYSTICK_OPERATOR = 1;
}
|
package org.usfirst.frc.team1360.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap
{
/**
* LeftMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_1 = 0;
/**
* LeftMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_2 = 1;
/**
* RightMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_1 = 2;
/**
* RightMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_2 = 3;
/**
* Driver Controller
*/
public static final int JOYSTICK_DRIVER = 0;
/**
* Operator Controller
*/
public static final int JOYSTICK_OPERATOR = 1;
/**
* Intake motor
*/
public static final int INTAKE_MOTOR = 5;
}
|
Revert "Revert "Added new port""
|
Revert "Revert "Added new port""
This reverts commit c6b095fabf0ba5228d1549738a0fef806401a1da.
|
Java
|
mit
|
FRC1360/Stronghold2016
|
java
|
## Code Before:
package org.usfirst.frc.team1360.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap
{
/**
* LeftMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_1 = 0;
/**
* LeftMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_2 = 1;
/**
* RightMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_1 = 2;
/**
* RightMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_2 = 3;
/**
* Driver Controller
*/
public static final int JOYSTICK_DRIVER = 0;
/**
* Operator Controller
*/
public static final int JOYSTICK_OPERATOR = 1;
}
## Instruction:
Revert "Revert "Added new port""
This reverts commit c6b095fabf0ba5228d1549738a0fef806401a1da.
## Code After:
package org.usfirst.frc.team1360.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap
{
/**
* LeftMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_1 = 0;
/**
* LeftMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_LEFT_2 = 1;
/**
* RightMotor Front on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_1 = 2;
/**
* RightMotor Back on the Drive Subsystem
* CAN: No
*/
public static final int DRIVESUBSYSTEM_RIGHT_2 = 3;
/**
* Driver Controller
*/
public static final int JOYSTICK_DRIVER = 0;
/**
* Operator Controller
*/
public static final int JOYSTICK_OPERATOR = 1;
/**
* Intake motor
*/
public static final int INTAKE_MOTOR = 5;
}
|
// ... existing code ...
*/
public static final int JOYSTICK_OPERATOR = 1;
/**
* Intake motor
*/
public static final int INTAKE_MOTOR = 5;
}
// ... rest of the code ...
|
266531144042eb9fb8a20ac8d78c027b1037b8f1
|
src/stray/util/render/StencilMaskUtil.java
|
src/stray/util/render/StencilMaskUtil.java
|
package stray.util.render;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
public class StencilMaskUtil {
/**
* call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
*/
public static void prepareMask() {
Gdx.gl20.glDepthFunc(GL20.GL_LESS);
Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glDepthMask(true);
Gdx.gl20.glColorMask(false, false, false, false);
}
/**
* call this AFTER batch.begin() and BEFORE drawing sprites
*/
public static void useMask() {
Gdx.gl20.glDepthMask(false);
Gdx.gl20.glColorMask(true, true, true, true);
Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glDepthFunc(GL20.GL_EQUAL);
}
/**
* call this AFTER batch.flush/end
*/
public static void resetMask(){
Gdx.gl20.glDisable(GL20.GL_DEPTH_TEST);
}
}
|
package stray.util.render;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
public class StencilMaskUtil {
/**
* call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
*/
public static void prepareMask() {
Gdx.gl.glDepthFunc(GL20.GL_LESS);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
Gdx.gl.glColorMask(false, false, false, false);
}
/**
* call this AFTER batch.begin() and BEFORE drawing sprites
*/
public static void useMask() {
Gdx.gl.glDepthMask(false);
Gdx.gl.glColorMask(true, true, true, true);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
}
/**
* call this AFTER batch.flush/end
*/
public static void resetMask(){
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
}
}
|
Refactor to use gdx GL instead of GL20
|
Refactor to use gdx GL instead of GL20
|
Java
|
mit
|
chrislo27/Stray-core
|
java
|
## Code Before:
package stray.util.render;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
public class StencilMaskUtil {
/**
* call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
*/
public static void prepareMask() {
Gdx.gl20.glDepthFunc(GL20.GL_LESS);
Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glDepthMask(true);
Gdx.gl20.glColorMask(false, false, false, false);
}
/**
* call this AFTER batch.begin() and BEFORE drawing sprites
*/
public static void useMask() {
Gdx.gl20.glDepthMask(false);
Gdx.gl20.glColorMask(true, true, true, true);
Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glDepthFunc(GL20.GL_EQUAL);
}
/**
* call this AFTER batch.flush/end
*/
public static void resetMask(){
Gdx.gl20.glDisable(GL20.GL_DEPTH_TEST);
}
}
## Instruction:
Refactor to use gdx GL instead of GL20
## Code After:
package stray.util.render;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
public class StencilMaskUtil {
/**
* call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
*/
public static void prepareMask() {
Gdx.gl.glDepthFunc(GL20.GL_LESS);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
Gdx.gl.glColorMask(false, false, false, false);
}
/**
* call this AFTER batch.begin() and BEFORE drawing sprites
*/
public static void useMask() {
Gdx.gl.glDepthMask(false);
Gdx.gl.glColorMask(true, true, true, true);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
}
/**
* call this AFTER batch.flush/end
*/
public static void resetMask(){
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
}
}
|
// ... existing code ...
* call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
*/
public static void prepareMask() {
Gdx.gl.glDepthFunc(GL20.GL_LESS);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
Gdx.gl.glColorMask(false, false, false, false);
}
/**
// ... modified code ...
* call this AFTER batch.begin() and BEFORE drawing sprites
*/
public static void useMask() {
Gdx.gl.glDepthMask(false);
Gdx.gl.glColorMask(true, true, true, true);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
}
/**
...
* call this AFTER batch.flush/end
*/
public static void resetMask(){
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
}
}
// ... rest of the code ...
|
1f7f058d97c6599401558a280d85affed7fb5394
|
testing/hdiv_proj.py
|
testing/hdiv_proj.py
|
from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
f.project(as_vector([x[1], x[0]]))
r = Function(V)
a = inner(u, v)*dx
L = inner(f, v)*dx
solve(a == L, r)
V_d = FunctionSpace(mesh, BrokenElement(RT))
phi_d = TestFunction(V_d)
r_d = assemble(inner(r, phi_d)*dx)
ref = assemble(inner(f, phi_d)*dx)
print(errornorm(r_d, ref))
|
from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
assemble(42*dot(v, FacetNormal(mesh))*ds, tensor=f)
r = Function(V)
a = inner(u, v)*dx
L = inner(f, v)*dx
solve(a == L, r)
V_d = FunctionSpace(mesh, BrokenElement(RT))
phi_d = TestFunction(V_d)
r_d = assemble(inner(r, phi_d)*dx)
ref = assemble(inner(f, phi_d)*dx)
projection_rd = project(f, V_d)
print(errornorm(r_d, ref))
|
Update projection experiment for HDiv functions
|
Update projection experiment for HDiv functions
|
Python
|
mit
|
thomasgibson/firedrake-hybridization
|
python
|
## Code Before:
from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
f.project(as_vector([x[1], x[0]]))
r = Function(V)
a = inner(u, v)*dx
L = inner(f, v)*dx
solve(a == L, r)
V_d = FunctionSpace(mesh, BrokenElement(RT))
phi_d = TestFunction(V_d)
r_d = assemble(inner(r, phi_d)*dx)
ref = assemble(inner(f, phi_d)*dx)
print(errornorm(r_d, ref))
## Instruction:
Update projection experiment for HDiv functions
## Code After:
from __future__ import absolute_import, print_function, division
from firedrake import *
mesh = UnitSquareMesh(2, 2)
RT = FiniteElement("RT", triangle, 1)
V = FunctionSpace(mesh, RT)
u = TrialFunction(V)
v = TestFunction(V)
f = Function(V)
x = SpatialCoordinate(mesh)
assemble(42*dot(v, FacetNormal(mesh))*ds, tensor=f)
r = Function(V)
a = inner(u, v)*dx
L = inner(f, v)*dx
solve(a == L, r)
V_d = FunctionSpace(mesh, BrokenElement(RT))
phi_d = TestFunction(V_d)
r_d = assemble(inner(r, phi_d)*dx)
ref = assemble(inner(f, phi_d)*dx)
projection_rd = project(f, V_d)
print(errornorm(r_d, ref))
|
// ... existing code ...
f = Function(V)
x = SpatialCoordinate(mesh)
assemble(42*dot(v, FacetNormal(mesh))*ds, tensor=f)
r = Function(V)
a = inner(u, v)*dx
// ... modified code ...
ref = assemble(inner(f, phi_d)*dx)
projection_rd = project(f, V_d)
print(errornorm(r_d, ref))
// ... rest of the code ...
|
c716124b8ede9678ca24eb07f1aa83c1fba9f177
|
doorman/celery_serializer.py
|
doorman/celery_serializer.py
|
from datetime import datetime
from time import mktime
import json
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(obj):
return json.loads(obj, object_hook=djson_decoder)
|
from datetime import datetime
from time import mktime
import json
from doorman.compat import string_types
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(s):
if not isinstance(s, string_types):
s = s.decode('utf-8')
return json.loads(s, object_hook=djson_decoder)
|
Fix custom decoder on Python 3
|
Fix custom decoder on Python 3
|
Python
|
mit
|
mwielgoszewski/doorman,mwielgoszewski/doorman,mwielgoszewski/doorman,mwielgoszewski/doorman
|
python
|
## Code Before:
from datetime import datetime
from time import mktime
import json
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(obj):
return json.loads(obj, object_hook=djson_decoder)
## Instruction:
Fix custom decoder on Python 3
## Code After:
from datetime import datetime
from time import mktime
import json
from doorman.compat import string_types
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(s):
if not isinstance(s, string_types):
s = s.decode('utf-8')
return json.loads(s, object_hook=djson_decoder)
|
...
from datetime import datetime
from time import mktime
import json
from doorman.compat import string_types
class DJSONEncoder(json.JSONEncoder):
...
# Decoder function
def djson_loads(s):
if not isinstance(s, string_types):
s = s.decode('utf-8')
return json.loads(s, object_hook=djson_decoder)
...
|
8f1b473e2dab982e989e9a041aa14e31050d2f4b
|
scripts/promote_orga.py
|
scripts/promote_orga.py
|
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
Use service in script to promote a user to organizer
|
Use service in script to promote a user to organizer
|
Python
|
bsd-3-clause
|
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
|
python
|
## Code Before:
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
## Instruction:
Use service in script to promote a user to organizer
## Code After:
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
...
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
...
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
...
|
bf2dfd5bd2977f5afb22de8dfa61d26b25d09bf6
|
trunk/mobility/src/test/java/es/tid/ps/mobility/jobs/CdrParserTest.java
|
trunk/mobility/src/test/java/es/tid/ps/mobility/jobs/CdrParserTest.java
|
package es.tid.ps.mobility.jobs;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import es.tid.ps.mobility.data.BaseProtocol.Date;
import es.tid.ps.mobility.data.BaseProtocol.Time;
import es.tid.ps.mobility.data.MxCdrUtil;
/**
*
* @author sortega
*/
public class CdrParserTest {
@Test
public void testParse() throws Exception {
CdrParser parser = new CdrParser("33F430521676F4|2221436242|"
+ "33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR");
assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4,
Date.newBuilder()
.setDay(1)
.setMonth(1)
.setYear(10)
.setWeekDay(5)
.build(),
Time.newBuilder()
.setHour(2)
.setMinute(0)
.setSeconds(1)
.build()),
parser.parse());
}
}
|
package es.tid.ps.mobility.jobs;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import es.tid.ps.mobility.data.BaseProtocol.Date;
import es.tid.ps.mobility.data.BaseProtocol.Time;
import es.tid.ps.mobility.data.MxCdrUtil;
import es.tid.ps.mobility.parser.CdrParser;
/**
*
* @author sortega
*/
public class CdrParserTest {
@Test
public void testParse() throws Exception {
CdrParser parser = new CdrParser("33F430521676F4|2221436242|"
+ "33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR");
assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4,
Date.newBuilder()
.setDay(1)
.setMonth(1)
.setYear(10)
.setWeekDay(5)
.build(),
Time.newBuilder()
.setHour(2)
.setMinute(0)
.setSeconds(1)
.build()),
parser.parse());
}
}
|
Add missing import in unit test file.
|
Add missing import in unit test file.
|
Java
|
apache-2.0
|
telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform
|
java
|
## Code Before:
package es.tid.ps.mobility.jobs;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import es.tid.ps.mobility.data.BaseProtocol.Date;
import es.tid.ps.mobility.data.BaseProtocol.Time;
import es.tid.ps.mobility.data.MxCdrUtil;
/**
*
* @author sortega
*/
public class CdrParserTest {
@Test
public void testParse() throws Exception {
CdrParser parser = new CdrParser("33F430521676F4|2221436242|"
+ "33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR");
assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4,
Date.newBuilder()
.setDay(1)
.setMonth(1)
.setYear(10)
.setWeekDay(5)
.build(),
Time.newBuilder()
.setHour(2)
.setMinute(0)
.setSeconds(1)
.build()),
parser.parse());
}
}
## Instruction:
Add missing import in unit test file.
## Code After:
package es.tid.ps.mobility.jobs;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import es.tid.ps.mobility.data.BaseProtocol.Date;
import es.tid.ps.mobility.data.BaseProtocol.Time;
import es.tid.ps.mobility.data.MxCdrUtil;
import es.tid.ps.mobility.parser.CdrParser;
/**
*
* @author sortega
*/
public class CdrParserTest {
@Test
public void testParse() throws Exception {
CdrParser parser = new CdrParser("33F430521676F4|2221436242|"
+ "33F430521676F4|0442224173253|2|01/01/2010|02:00:01|2891|RMITERR");
assertEquals(MxCdrUtil.create(2221436242L, 0x521676f4,
Date.newBuilder()
.setDay(1)
.setMonth(1)
.setYear(10)
.setWeekDay(5)
.build(),
Time.newBuilder()
.setHour(2)
.setMinute(0)
.setSeconds(1)
.build()),
parser.parse());
}
}
|
...
import es.tid.ps.mobility.data.BaseProtocol.Date;
import es.tid.ps.mobility.data.BaseProtocol.Time;
import es.tid.ps.mobility.data.MxCdrUtil;
import es.tid.ps.mobility.parser.CdrParser;
/**
*
...
|
033b17a8be5be32188ca9b5f286fe023fc07d34a
|
frappe/utils/pdf.py
|
frappe/utils/pdf.py
|
from __future__ import unicode_literals
import pdfkit, os, frappe
from frappe.utils import scrub_urls
def get_pdf(html, options=None):
if not options:
options = {}
options.update({
"print-media-type": None,
"background": None,
"images": None,
'margin-top': '15mm',
'margin-right': '15mm',
'margin-bottom': '15mm',
'margin-left': '15mm',
'encoding': "UTF-8",
'no-outline': None
})
if not options.get("page-size"):
options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"
html = scrub_urls(html)
fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
pdfkit.from_string(html, fname, options=options or {})
with open(fname, "rb") as fileobj:
filedata = fileobj.read()
os.remove(fname)
return filedata
|
from __future__ import unicode_literals
import pdfkit, os, frappe
from frappe.utils import scrub_urls
def get_pdf(html, options=None):
if not options:
options = {}
options.update({
"print-media-type": None,
"background": None,
"images": None,
# 'margin-top': '10mm',
# 'margin-right': '1mm',
# 'margin-bottom': '10mm',
# 'margin-left': '1mm',
'encoding': "UTF-8",
'no-outline': None
})
if not options.get("page-size"):
options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"
html = scrub_urls(html)
fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
pdfkit.from_string(html, fname, options=options or {})
with open(fname, "rb") as fileobj:
filedata = fileobj.read()
os.remove(fname)
return filedata
|
Remove margin constrains from PDF printing
|
Remove margin constrains from PDF printing
|
Python
|
mit
|
BhupeshGupta/frappe,BhupeshGupta/frappe,BhupeshGupta/frappe,BhupeshGupta/frappe
|
python
|
## Code Before:
from __future__ import unicode_literals
import pdfkit, os, frappe
from frappe.utils import scrub_urls
def get_pdf(html, options=None):
if not options:
options = {}
options.update({
"print-media-type": None,
"background": None,
"images": None,
'margin-top': '15mm',
'margin-right': '15mm',
'margin-bottom': '15mm',
'margin-left': '15mm',
'encoding': "UTF-8",
'no-outline': None
})
if not options.get("page-size"):
options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"
html = scrub_urls(html)
fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
pdfkit.from_string(html, fname, options=options or {})
with open(fname, "rb") as fileobj:
filedata = fileobj.read()
os.remove(fname)
return filedata
## Instruction:
Remove margin constrains from PDF printing
## Code After:
from __future__ import unicode_literals
import pdfkit, os, frappe
from frappe.utils import scrub_urls
def get_pdf(html, options=None):
if not options:
options = {}
options.update({
"print-media-type": None,
"background": None,
"images": None,
# 'margin-top': '10mm',
# 'margin-right': '1mm',
# 'margin-bottom': '10mm',
# 'margin-left': '1mm',
'encoding': "UTF-8",
'no-outline': None
})
if not options.get("page-size"):
options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"
html = scrub_urls(html)
fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
pdfkit.from_string(html, fname, options=options or {})
with open(fname, "rb") as fileobj:
filedata = fileobj.read()
os.remove(fname)
return filedata
|
...
"print-media-type": None,
"background": None,
"images": None,
# 'margin-top': '10mm',
# 'margin-right': '1mm',
# 'margin-bottom': '10mm',
# 'margin-left': '1mm',
'encoding': "UTF-8",
'no-outline': None
})
...
|
526b988a3dc06e92509e6c67910dbded36ba5aec
|
src/definitions.h
|
src/definitions.h
|
using uint = unsigned int;
using u8 = uint8_t;
using u16 = uint16_t;
using s8 = int8_t;
const int GAMEBOY_WIDTH = 160;
const int GAMEBOY_HEIGHT = 144;
const int CLOCK_RATE = 4194304;
template <typename... T> void unused(T&&...) {}
#define fatal_error() log_error("Fatal error: %s:%d", __FILE__, __LINE__); exit(1);
enum class GBColor {
Color0, /* White */
Color1, /* Light gray */
Color2, /* Dark gray */
Color3, /* Black */
};
enum class Color {
White,
LightGray,
DarkGray,
Black,
};
struct BGPalette {
Color color0 = Color::White;
Color color1 = Color::LightGray;
Color color2 = Color::DarkGray;
Color color3 = Color::Black;
};
struct Noncopyable {
Noncopyable& operator=(const Noncopyable&) = delete;
Noncopyable(const Noncopyable&) = delete;
Noncopyable() = default;
};
|
using uint = unsigned int;
using u8 = uint8_t;
using u16 = uint16_t;
using s8 = int8_t;
using s16 = uint16_t;
const int GAMEBOY_WIDTH = 160;
const int GAMEBOY_HEIGHT = 144;
const int CLOCK_RATE = 4194304;
template <typename... T> void unused(T&&...) {}
#define fatal_error() log_error("Fatal error: %s:%d", __FILE__, __LINE__); exit(1);
enum class GBColor {
Color0, /* White */
Color1, /* Light gray */
Color2, /* Dark gray */
Color3, /* Black */
};
enum class Color {
White,
LightGray,
DarkGray,
Black,
};
struct BGPalette {
Color color0 = Color::White;
Color color1 = Color::LightGray;
Color color2 = Color::DarkGray;
Color color3 = Color::Black;
};
struct Noncopyable {
Noncopyable& operator=(const Noncopyable&) = delete;
Noncopyable(const Noncopyable&) = delete;
Noncopyable() = default;
};
|
Add a s16 (signed 16-bit int) for symmetry with u8/u16
|
Add a s16 (signed 16-bit int) for symmetry with u8/u16
|
C
|
bsd-3-clause
|
jgilchrist/emulator,jgilchrist/emulator,jgilchrist/emulator
|
c
|
## Code Before:
using uint = unsigned int;
using u8 = uint8_t;
using u16 = uint16_t;
using s8 = int8_t;
const int GAMEBOY_WIDTH = 160;
const int GAMEBOY_HEIGHT = 144;
const int CLOCK_RATE = 4194304;
template <typename... T> void unused(T&&...) {}
#define fatal_error() log_error("Fatal error: %s:%d", __FILE__, __LINE__); exit(1);
enum class GBColor {
Color0, /* White */
Color1, /* Light gray */
Color2, /* Dark gray */
Color3, /* Black */
};
enum class Color {
White,
LightGray,
DarkGray,
Black,
};
struct BGPalette {
Color color0 = Color::White;
Color color1 = Color::LightGray;
Color color2 = Color::DarkGray;
Color color3 = Color::Black;
};
struct Noncopyable {
Noncopyable& operator=(const Noncopyable&) = delete;
Noncopyable(const Noncopyable&) = delete;
Noncopyable() = default;
};
## Instruction:
Add a s16 (signed 16-bit int) for symmetry with u8/u16
## Code After:
using uint = unsigned int;
using u8 = uint8_t;
using u16 = uint16_t;
using s8 = int8_t;
using s16 = uint16_t;
const int GAMEBOY_WIDTH = 160;
const int GAMEBOY_HEIGHT = 144;
const int CLOCK_RATE = 4194304;
template <typename... T> void unused(T&&...) {}
#define fatal_error() log_error("Fatal error: %s:%d", __FILE__, __LINE__); exit(1);
enum class GBColor {
Color0, /* White */
Color1, /* Light gray */
Color2, /* Dark gray */
Color3, /* Black */
};
enum class Color {
White,
LightGray,
DarkGray,
Black,
};
struct BGPalette {
Color color0 = Color::White;
Color color1 = Color::LightGray;
Color color2 = Color::DarkGray;
Color color3 = Color::Black;
};
struct Noncopyable {
Noncopyable& operator=(const Noncopyable&) = delete;
Noncopyable(const Noncopyable&) = delete;
Noncopyable() = default;
};
|
# ... existing code ...
using u8 = uint8_t;
using u16 = uint16_t;
using s8 = int8_t;
using s16 = uint16_t;
const int GAMEBOY_WIDTH = 160;
const int GAMEBOY_HEIGHT = 144;
# ... rest of the code ...
|
07ba597a106e60a77ec28debd093079daa55df8f
|
node.py
|
node.py
|
class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
|
class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
# A calculated value
self.value = None
|
Add value property to class Node
|
Add value property to class Node
value is the calculated output of a Node.
|
Python
|
mit
|
YabinHu/miniflow
|
python
|
## Code Before:
class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
## Instruction:
Add value property to class Node
value is the calculated output of a Node.
## Code After:
class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
# A calculated value
self.value = None
|
# ... existing code ...
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
n.outbound_nodes.append(self)
# A calculated value
self.value = None
# ... rest of the code ...
|
91f5db6ddf6e26cec27917109689c200498dc85f
|
statsmodels/formula/try_formula.py
|
statsmodels/formula/try_formula.py
|
import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP",
"PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK",
"PERSPENK", "PTRATIO", "PCTAF"]]
endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW"))
del dta["NABOVE"]
dta["SUCCESS"] = endog
endog = dta.pop("SUCCESS")
exog = dta
mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
|
import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP",
"PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK",
"PERSPENK", "PTRATIO", "PCTAF"]]
endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW"))
del dta["NABOVE"]
dta["SUCCESS"] = endog
endog = dta.pop("SUCCESS")
exog = dta
mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
# try passing a formula object, using user-injected code
def double_it(x):
return 2*x
# What is the correct entry point for this? Should users be able to inject
# code into default_env or similar? I don't see a way to do this yet using
# the approach I have been using, it should be an argument to Desc
from charlton.builtins import builtins
builtins['double_it'] = double_it
formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + '
formula += 'PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
|
Add example for injecting user transform
|
ENH: Add example for injecting user transform
|
Python
|
bsd-3-clause
|
bert9bert/statsmodels,YihaoLu/statsmodels,cbmoore/statsmodels,hlin117/statsmodels,bavardage/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,statsmodels/statsmodels,astocko/statsmodels,DonBeo/statsmodels,bzero/statsmodels,Averroes/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,josef-pkt/statsmodels,kiyoto/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,bavardage/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,wdurhamh/statsmodels,phobson/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,jstoxrocky/statsmodels,bert9bert/statsmodels,gef756/statsmodels,astocko/statsmodels,wdurhamh/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,ChadFulton/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,rgommers/statsmodels,yl565/statsmodels,nvoron23/statsmodels,edhuckle/statsmodels,nguyentu1602/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,waynenilsen/statsmodels,wwf5067/statsmodels,wwf5067/statsmodels,edhuckle/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,gef756/statsmodels,phobson/statsmodels,wwf5067/statsmodels,huongttlan/statsmodels,waynenilsen/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,gef756/statsmodels,bashtage/statsmodels,musically-ut/statsmodels,bavardage/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bzero/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,YihaoLu/statsmodels,josef-pkt/statsmodels,saketkc/statsmodels,jseabold/statsmodels,josef-pkt/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,musically-ut/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,statsmodels/statsmodels,bsipocz/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,adammenges/statsmodels,alekz112/statsmodels,detrout/debian-statsmodels,YihaoLu/statsmodels,musically-ut/statsmodels,bert9bert/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,bavardage/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,wwf5067/statsmodels,hainm/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,hlin117/statsmodels,Averroes/statsmodels,phobson/statsmodels,bzero/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,edhuckle/statsmodels,hainm/statsmodels,astocko/statsmodels,jseabold/statsmodels,bashtage/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,astocko/statsmodels,rgommers/statsmodels,hainm/statsmodels,kiyoto/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,jstoxrocky/statsmodels,huongttlan/statsmodels,yarikoptic/pystatsmodels,bashtage/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels,adammenges/statsmodels,rgommers/statsmodels,bavardage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,bzero/statsmodels,yarikoptic/pystatsmodels,YihaoLu/statsmodels,bzero/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels
|
python
|
## Code Before:
import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP",
"PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK",
"PERSPENK", "PTRATIO", "PCTAF"]]
endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW"))
del dta["NABOVE"]
dta["SUCCESS"] = endog
endog = dta.pop("SUCCESS")
exog = dta
mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
## Instruction:
ENH: Add example for injecting user transform
## Code After:
import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP",
"PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK",
"PERSPENK", "PTRATIO", "PCTAF"]]
endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW"))
del dta["NABOVE"]
dta["SUCCESS"] = endog
endog = dta.pop("SUCCESS")
exog = dta
mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
# try passing a formula object, using user-injected code
def double_it(x):
return 2*x
# What is the correct entry point for this? Should users be able to inject
# code into default_env or similar? I don't see a way to do this yet using
# the approach I have been using, it should be an argument to Desc
from charlton.builtins import builtins
builtins['double_it'] = double_it
formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + '
formula += 'PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
|
...
endog = dta.pop("SUCCESS")
exog = dta
mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
# try passing a formula object, using user-injected code
def double_it(x):
return 2*x
# What is the correct entry point for this? Should users be able to inject
# code into default_env or similar? I don't see a way to do this yet using
# the approach I have been using, it should be an argument to Desc
from charlton.builtins import builtins
builtins['double_it'] = double_it
formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + '
formula += 'PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
...
|
6c7fac2eafb062911f952249455ec43975741f1c
|
runtime/src/main/kotlin/kotlin/native/concurrent/Annotations.kt
|
runtime/src/main/kotlin/kotlin/native/concurrent/Annotations.kt
|
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
/**
* Marks a top level variable with a backing field or an object as thread local.
* The object remains mutable and it is possible to change its state,
* but every thread will have a distinct copy of this object,
* so changes in one thread are not reflected in another.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public actual annotation class ThreadLocal
/**
* Marks a top level variable with a backing field or an object as immutable.
* It is possible to share such object between multiple threads, but it becomes deeply frozen,
* so no changes can be made to its state or the state of objects it refers to.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.BINARY)
public actual annotation class SharedImmutable
|
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
/**
* Marks a top level property with a backing field or an object as thread local.
* The object remains mutable and it is possible to change its state,
* but every thread will have a distinct copy of this object,
* so changes in one thread are not reflected in another.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public actual annotation class ThreadLocal
/**
* Marks a top level property with a backing field as immutable.
* It is possible to share the value of such property between multiple threads, but it becomes deeply frozen,
* so no changes can be made to its state or the state of objects it refers to.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.BINARY)
public actual annotation class SharedImmutable
|
Correct docs of ThreadLocal and SharedImmutable annotations
|
Correct docs of ThreadLocal and SharedImmutable annotations
- clarify that they have effect only in K/N
- correct possible application targets of SharedImmutable
KT-36245
|
Kotlin
|
apache-2.0
|
JetBrains/kotlin-native,JetBrains/kotlin-native,JetBrains/kotlin-native,JetBrains/kotlin-native,wiltonlazary/kotlin-native,wiltonlazary/kotlin-native,JetBrains/kotlin-native,JetBrains/kotlin-native,JetBrains/kotlin-native,JetBrains/kotlin-native,wiltonlazary/kotlin-native,JetBrains/kotlin-native,wiltonlazary/kotlin-native,wiltonlazary/kotlin-native
|
kotlin
|
## Code Before:
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
/**
* Marks a top level variable with a backing field or an object as thread local.
* The object remains mutable and it is possible to change its state,
* but every thread will have a distinct copy of this object,
* so changes in one thread are not reflected in another.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public actual annotation class ThreadLocal
/**
* Marks a top level variable with a backing field or an object as immutable.
* It is possible to share such object between multiple threads, but it becomes deeply frozen,
* so no changes can be made to its state or the state of objects it refers to.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.BINARY)
public actual annotation class SharedImmutable
## Instruction:
Correct docs of ThreadLocal and SharedImmutable annotations
- clarify that they have effect only in K/N
- correct possible application targets of SharedImmutable
KT-36245
## Code After:
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
/**
* Marks a top level property with a backing field or an object as thread local.
* The object remains mutable and it is possible to change its state,
* but every thread will have a distinct copy of this object,
* so changes in one thread are not reflected in another.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public actual annotation class ThreadLocal
/**
* Marks a top level property with a backing field as immutable.
* It is possible to share the value of such property between multiple threads, but it becomes deeply frozen,
* so no changes can be made to its state or the state of objects it refers to.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.BINARY)
public actual annotation class SharedImmutable
|
// ... existing code ...
package kotlin.native.concurrent
/**
* Marks a top level property with a backing field or an object as thread local.
* The object remains mutable and it is possible to change its state,
* but every thread will have a distinct copy of this object,
* so changes in one thread are not reflected in another.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
// ... modified code ...
public actual annotation class ThreadLocal
/**
* Marks a top level property with a backing field as immutable.
* It is possible to share the value of such property between multiple threads, but it becomes deeply frozen,
* so no changes can be made to its state or the state of objects it refers to.
*
* The annotation has effect only in Kotlin/Native platform.
*
* PLEASE NOTE THAT THIS ANNOTATION MAY GO AWAY IN UPCOMING RELEASES.
*/
// ... rest of the code ...
|
091f9daf8758e56c82dbe7a88a50489ab279f793
|
adhocracy/lib/helpers/site_helper.py
|
adhocracy/lib/helpers/site_helper.py
|
from pylons import config, g
from pylons.i18n import _
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
Add h.site.domain() to return the domian without the port
|
Add h.site.domain() to return the domian without the port
|
Python
|
agpl-3.0
|
DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,SysTheron/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,SysTheron/adhocracy,phihag/adhocracy,phihag/adhocracy,phihag/adhocracy
|
python
|
## Code Before:
from pylons import config, g
from pylons.i18n import _
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
## Instruction:
Add h.site.domain() to return the domian without the port
## Code After:
from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
// ... existing code ...
from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
// ... rest of the code ...
|
28803e4669f4c7b2b84e53e39e3a0a99ff57572d
|
skyfield/__main__.py
|
skyfield/__main__.py
|
import pkg_resources
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
tt, delta_t = arrays['delta_t_recent']
start = ts.tt_jd(tt[0])
end = ts.tt_jd(tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
def version_of(distribution):
try:
d = pkg_resources.get_distribution(distribution)
except pkg_resources.DistributionNotFound:
return 'Unknown'
else:
return d.version
main()
|
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
daily_tt = arrays['tt_jd_minus_arange']
daily_tt += np.arange(len(daily_tt))
start = ts.tt_jd(daily_tt[0])
end = ts.tt_jd(daily_tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
def version_of(distribution):
try:
d = pkg_resources.get_distribution(distribution)
except pkg_resources.DistributionNotFound:
return 'Unknown'
else:
return d.version
main()
|
Fix “python -m skyfield” following ∆T array rename
|
Fix “python -m skyfield” following ∆T array rename
|
Python
|
mit
|
skyfielders/python-skyfield,skyfielders/python-skyfield
|
python
|
## Code Before:
import pkg_resources
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
tt, delta_t = arrays['delta_t_recent']
start = ts.tt_jd(tt[0])
end = ts.tt_jd(tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
def version_of(distribution):
try:
d = pkg_resources.get_distribution(distribution)
except pkg_resources.DistributionNotFound:
return 'Unknown'
else:
return d.version
main()
## Instruction:
Fix “python -m skyfield” following ∆T array rename
## Code After:
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
daily_tt = arrays['tt_jd_minus_arange']
daily_tt += np.arange(len(daily_tt))
start = ts.tt_jd(daily_tt[0])
end = ts.tt_jd(daily_tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
def version_of(distribution):
try:
d = pkg_resources.get_distribution(distribution)
except pkg_resources.DistributionNotFound:
return 'Unknown'
else:
return d.version
main()
|
# ... existing code ...
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
# ... modified code ...
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
daily_tt = arrays['tt_jd_minus_arange']
daily_tt += np.arange(len(daily_tt))
start = ts.tt_jd(daily_tt[0])
end = ts.tt_jd(daily_tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
# ... rest of the code ...
|
73d4079795c7cdabf6ff0581459979e0faab3cb2
|
giane-jetty/src/main/java/com/github/kaitoy/sneo/giane/jetty/GianeStarter.java
|
giane-jetty/src/main/java/com/github/kaitoy/sneo/giane/jetty/GianeStarter.java
|
/*_##########################################################################
_##
_## Copyright (C) 2012 Kaito Yamada
_##
_##########################################################################
*/
package com.github.kaitoy.sneo.giane.jetty;
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class GianeStarter {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/giane");
//context.setWelcomeFiles(new String[] {"index.action"});
ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
server.start();
server.join();
}
}
|
/*_##########################################################################
_##
_## Copyright (C) 2012 Kaito Yamada
_##
_##########################################################################
*/
package com.github.kaitoy.sneo.giane.jetty;
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class GianeStarter {
public static void main(String[] args) throws Exception {
int httpPort = 8080;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
try {
if ("--httpPort".equals(arg)) {
httpPort = Integer.parseInt(args[++i]);
} else {
System.err.println("Invalid option: " + arg);
System.exit(1);
}
} catch (Exception e) {
System.err.println("An error occurred in processing an option: " + arg);
System.exit(1);
}
}
Server server = new Server(httpPort);
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/giane");
ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
server.start();
server.join();
}
}
|
Add an option to specify HTTP port.
|
Add an option to specify HTTP port.
|
Java
|
mit
|
kaitoy/sneo,kaitoy/sneo
|
java
|
## Code Before:
/*_##########################################################################
_##
_## Copyright (C) 2012 Kaito Yamada
_##
_##########################################################################
*/
package com.github.kaitoy.sneo.giane.jetty;
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class GianeStarter {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/giane");
//context.setWelcomeFiles(new String[] {"index.action"});
ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
server.start();
server.join();
}
}
## Instruction:
Add an option to specify HTTP port.
## Code After:
/*_##########################################################################
_##
_## Copyright (C) 2012 Kaito Yamada
_##
_##########################################################################
*/
package com.github.kaitoy.sneo.giane.jetty;
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class GianeStarter {
public static void main(String[] args) throws Exception {
int httpPort = 8080;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
try {
if ("--httpPort".equals(arg)) {
httpPort = Integer.parseInt(args[++i]);
} else {
System.err.println("Invalid option: " + arg);
System.exit(1);
}
} catch (Exception e) {
System.err.println("An error occurred in processing an option: " + arg);
System.exit(1);
}
}
Server server = new Server(httpPort);
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/giane");
ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
server.start();
server.join();
}
}
|
// ... existing code ...
public class GianeStarter {
public static void main(String[] args) throws Exception {
int httpPort = 8080;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
try {
if ("--httpPort".equals(arg)) {
httpPort = Integer.parseInt(args[++i]);
} else {
System.err.println("Invalid option: " + arg);
System.exit(1);
}
} catch (Exception e) {
System.err.println("An error occurred in processing an option: " + arg);
System.exit(1);
}
}
Server server = new Server(httpPort);
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/giane");
ProtectionDomain protectionDomain = GianeStarter.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
// ... rest of the code ...
|
f1c270f2145cf1f48a0207696cb4f6e9592af357
|
NTHU_Course/settings/testing_sqlite.py
|
NTHU_Course/settings/testing_sqlite.py
|
'''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': 'test_sqlite'
}
}
|
'''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': ':memory:'
}
}
|
Correct db `NAME`, use in-memory database for testing
|
Correct db `NAME`, use in-memory database for testing
|
Python
|
mit
|
henryyang42/NTHU_Course,henryyang42/NTHU_Course,henryyang42/NTHU_Course,henryyang42/NTHU_Course
|
python
|
## Code Before:
'''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': 'test_sqlite'
}
}
## Instruction:
Correct db `NAME`, use in-memory database for testing
## Code After:
'''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': ':memory:'
}
}
|
# ... existing code ...
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': ':memory:'
}
}
# ... rest of the code ...
|
b134ede57ed2f7cd5eac1d5e274ee512d4c27623
|
library/src/main/java/com/jakewharton/notificationcompat2/NotificationCompatICS.java
|
library/src/main/java/com/jakewharton/notificationcompat2/NotificationCompatICS.java
|
package com.jakewharton.notificationcompat2;
import android.app.Notification;
class NotificationCompatICS implements NotificationCompat2.NotificationCompatImpl {
static Notification.Builder createBuilder(NotificationCompat2.Builder b) {
Notification.Builder builder = NotificationCompatHC.createBuilder(b);
if (b.mProgressSet) {
builder.setProgress(b.mProgress, b.mProgressMax, b.mProgressIndeterminate);
}
return builder;
}
@Override
public Notification build(NotificationCompat2.Builder builder) {
return createBuilder(builder).build();
}
}
|
package com.jakewharton.notificationcompat2;
import android.app.Notification;
class NotificationCompatICS implements NotificationCompat2.NotificationCompatImpl {
static Notification.Builder createBuilder(NotificationCompat2.Builder b) {
Notification.Builder builder = NotificationCompatHC.createBuilder(b);
if (b.mProgressSet) {
builder.setProgress(b.mProgress, b.mProgressMax, b.mProgressIndeterminate);
}
return builder;
}
@Override
public Notification build(NotificationCompat2.Builder builder) {
return createBuilder(builder).getNotification();
}
}
|
Use `getNotification` rather than `build` for ICS.
|
Use `getNotification` rather than `build` for ICS.
|
Java
|
apache-2.0
|
Udinic/NotificationCompat2,Udinic/NotificationCompat2
|
java
|
## Code Before:
package com.jakewharton.notificationcompat2;
import android.app.Notification;
class NotificationCompatICS implements NotificationCompat2.NotificationCompatImpl {
static Notification.Builder createBuilder(NotificationCompat2.Builder b) {
Notification.Builder builder = NotificationCompatHC.createBuilder(b);
if (b.mProgressSet) {
builder.setProgress(b.mProgress, b.mProgressMax, b.mProgressIndeterminate);
}
return builder;
}
@Override
public Notification build(NotificationCompat2.Builder builder) {
return createBuilder(builder).build();
}
}
## Instruction:
Use `getNotification` rather than `build` for ICS.
## Code After:
package com.jakewharton.notificationcompat2;
import android.app.Notification;
class NotificationCompatICS implements NotificationCompat2.NotificationCompatImpl {
static Notification.Builder createBuilder(NotificationCompat2.Builder b) {
Notification.Builder builder = NotificationCompatHC.createBuilder(b);
if (b.mProgressSet) {
builder.setProgress(b.mProgress, b.mProgressMax, b.mProgressIndeterminate);
}
return builder;
}
@Override
public Notification build(NotificationCompat2.Builder builder) {
return createBuilder(builder).getNotification();
}
}
|
// ... existing code ...
@Override
public Notification build(NotificationCompat2.Builder builder) {
return createBuilder(builder).getNotification();
}
}
// ... rest of the code ...
|
74d0e710711f1b499ab32784b751adc55e8b7f00
|
python/bonetrousle.py
|
python/bonetrousle.py
|
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
def minimumValue(k, b):
return 0
# The maximum number of sticks that may be purchased
def maximumValue(k, b):
return 100
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
Implement minimum and maximum values
|
Implement minimum and maximum values
|
Python
|
mit
|
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
|
python
|
## Code Before:
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
def minimumValue(k, b):
return 0
# The maximum number of sticks that may be purchased
def maximumValue(k, b):
return 100
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
## Instruction:
Implement minimum and maximum values
## Code After:
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
...
return -1
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
...
|
214d5f7e09e9b5e854e7471c6dc337456f428647
|
quickavro/_compat.py
|
quickavro/_compat.py
|
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metaclass('temporary_class', None, {})
if PY3:
basestring = (str, bytes)
def ensure_bytes(s):
if type(s) == str:
return bytes(s, default_encoding)
else:
return bytes(s)
def ensure_str(s):
if type(s) == bytes:
return s.decode(default_encoding)
else:
return s
else:
range = xrange
ensure_bytes = lambda s: s
|
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metaclass('temporary_class', None, {})
if PY3:
basestring = (str, bytes)
def ensure_bytes(s):
if type(s) == str:
return bytes(s, default_encoding)
else:
return bytes(s)
def ensure_str(s):
if type(s) == bytes:
return s.decode(default_encoding)
else:
return s
else:
range = xrange
ensure_bytes = lambda s: s
ensure_str = lambda s: s
|
Add missing ensure_str for PY2
|
Add missing ensure_str for PY2
|
Python
|
apache-2.0
|
ChrisRx/quickavro,ChrisRx/quickavro
|
python
|
## Code Before:
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metaclass('temporary_class', None, {})
if PY3:
basestring = (str, bytes)
def ensure_bytes(s):
if type(s) == str:
return bytes(s, default_encoding)
else:
return bytes(s)
def ensure_str(s):
if type(s) == bytes:
return s.decode(default_encoding)
else:
return s
else:
range = xrange
ensure_bytes = lambda s: s
## Instruction:
Add missing ensure_str for PY2
## Code After:
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
default_encoding = "UTF-8"
def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metaclass('temporary_class', None, {})
if PY3:
basestring = (str, bytes)
def ensure_bytes(s):
if type(s) == str:
return bytes(s, default_encoding)
else:
return bytes(s)
def ensure_str(s):
if type(s) == bytes:
return s.decode(default_encoding)
else:
return s
else:
range = xrange
ensure_bytes = lambda s: s
ensure_str = lambda s: s
|
...
range = xrange
ensure_bytes = lambda s: s
ensure_str = lambda s: s
...
|
658e0a3dbd260f2d27756ed5605794b2320ba728
|
backend/src/pox/ext/gini/samples/packet_loss.py
|
backend/src/pox/ext/gini/samples/packet_loss.py
|
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):.
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
conn.send(event.connection)
def launch():
core.openflow.addListenerByName("PacketIn", packet_in)
|
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
event.connection.send(msg)
def launch():
core.openflow.addListenerByName("PacketIn", packet_in)
|
Fix bug in packet loss
|
Fix bug in packet loss
|
Python
|
mit
|
anrl/gini3,michaelkourlas/gini,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,anrl/gini3,michaelkourlas/gini
|
python
|
## Code Before:
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):.
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
conn.send(event.connection)
def launch():
core.openflow.addListenerByName("PacketIn", packet_in)
## Instruction:
Fix bug in packet loss
## Code After:
import random
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
event.connection.send(msg)
def launch():
core.openflow.addListenerByName("PacketIn", packet_in)
|
...
from pox.core import core
import pox.openflow.libopenflow_01 as of
def packet_in(event):
if random.random() >= 0.25:
msg = of.ofp_packet_out(data = event.ofp)
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
event.connection.send(msg)
def launch():
core.openflow.addListenerByName("PacketIn", packet_in)
...
|
d7ea84800b89255137300b8e8d83b4b6abfc30b2
|
src/oscar/apps/voucher/receivers.py
|
src/oscar/apps/voucher/receivers.py
|
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.save()
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.save()
signals.voucher_addition.connect(track_voucher_addition)
signals.voucher_removal.connect(track_voucher_removal)
|
from django.db.models import F
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') + 1,
)
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') - 1,
)
signals.voucher_addition.connect(track_voucher_addition)
signals.voucher_removal.connect(track_voucher_removal)
|
Fix race condition when tracking num_basket_additions on a voucher
|
Fix race condition when tracking num_basket_additions on a voucher
|
Python
|
bsd-3-clause
|
jmt4/django-oscar,mexeniz/django-oscar,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,saadatqadri/django-oscar,jmt4/django-oscar,michaelkuty/django-oscar,nickpack/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,sasha0/django-oscar,okfish/django-oscar,sasha0/django-oscar,bnprk/django-oscar,anentropic/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,solarissmoke/django-oscar,dongguangming/django-oscar,amirrpp/django-oscar,django-oscar/django-oscar,anentropic/django-oscar,saadatqadri/django-oscar,lijoantony/django-oscar,pasqualguerrero/django-oscar,sasha0/django-oscar,jmt4/django-oscar,anentropic/django-oscar,jlmadurga/django-oscar,lijoantony/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,vovanbo/django-oscar,spartonia/django-oscar,eddiep1101/django-oscar,monikasulik/django-oscar,taedori81/django-oscar,amirrpp/django-oscar,sasha0/django-oscar,faratro/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,vovanbo/django-oscar,michaelkuty/django-oscar,sonofatailor/django-oscar,MatthewWilkes/django-oscar,taedori81/django-oscar,lijoantony/django-oscar,pdonadeo/django-oscar,pdonadeo/django-oscar,binarydud/django-oscar,spartonia/django-oscar,michaelkuty/django-oscar,bnprk/django-oscar,binarydud/django-oscar,MatthewWilkes/django-oscar,WillisXChen/django-oscar,MatthewWilkes/django-oscar,monikasulik/django-oscar,WadeYuChen/django-oscar,WadeYuChen/django-oscar,thechampanurag/django-oscar,WadeYuChen/django-oscar,itbabu/django-oscar,QLGu/django-oscar,sonofatailor/django-oscar,anentropic/django-oscar,thechampanurag/django-oscar,QLGu/django-oscar,nfletton/django-oscar,jmt4/django-oscar,jlmadurga/django-oscar,MatthewWilkes/django-oscar,john-parton/django-oscar,john-parton/django-oscar,kapari/django-oscar,kapari/django-oscar,itbabu/django-oscar,Jannes123/django-oscar,okfish/django-oscar,ka7eh/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,Jannes123/django-oscar,saadatqadri/django-oscar,bnprk/django-oscar,faratro/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,mexeniz/django-oscar,Bogh/django-oscar,binarydud/django-oscar,itbabu/django-oscar,taedori81/django-oscar,nfletton/django-oscar,bschuon/django-oscar,pdonadeo/django-oscar,Jannes123/django-oscar,dongguangming/django-oscar,jlmadurga/django-oscar,itbabu/django-oscar,pasqualguerrero/django-oscar,Jannes123/django-oscar,Bogh/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,spartonia/django-oscar,faratro/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,dongguangming/django-oscar,monikasulik/django-oscar,nickpack/django-oscar,nickpack/django-oscar,bschuon/django-oscar,bnprk/django-oscar,saadatqadri/django-oscar,nfletton/django-oscar,nickpack/django-oscar,nfletton/django-oscar,QLGu/django-oscar,eddiep1101/django-oscar,WillisXChen/django-oscar,faratro/django-oscar,thechampanurag/django-oscar,dongguangming/django-oscar,Bogh/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,ka7eh/django-oscar,john-parton/django-oscar,WadeYuChen/django-oscar,ka7eh/django-oscar,taedori81/django-oscar,eddiep1101/django-oscar,WillisXChen/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,pdonadeo/django-oscar,john-parton/django-oscar,kapari/django-oscar,solarissmoke/django-oscar,kapari/django-oscar,rocopartners/django-oscar,amirrpp/django-oscar,mexeniz/django-oscar,vovanbo/django-oscar,vovanbo/django-oscar,WillisXChen/django-oscar,ka7eh/django-oscar,solarissmoke/django-oscar,WillisXChen/django-oscar,spartonia/django-oscar,okfish/django-oscar
|
python
|
## Code Before:
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.save()
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.save()
signals.voucher_addition.connect(track_voucher_addition)
signals.voucher_removal.connect(track_voucher_removal)
## Instruction:
Fix race condition when tracking num_basket_additions on a voucher
## Code After:
from django.db.models import F
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') + 1,
)
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') - 1,
)
signals.voucher_addition.connect(track_voucher_addition)
signals.voucher_removal.connect(track_voucher_removal)
|
// ... existing code ...
from django.db.models import F
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') + 1,
)
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') - 1,
)
signals.voucher_addition.connect(track_voucher_addition)
// ... rest of the code ...
|
f364b55a643c2768f80cb559eb0ec1988aa884c8
|
tests/htmlgeneration_test.py
|
tests/htmlgeneration_test.py
|
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
assert_equal(expected_html, generator.for_document(document))
|
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
|
Add test just for paragraph HTML generation
|
Add test just for paragraph HTML generation
|
Python
|
bsd-2-clause
|
mwilliamson/wordbridge
|
python
|
## Code Before:
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
assert_equal(expected_html, generator.for_document(document))
## Instruction:
Add test just for paragraph HTML generation
## Code After:
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
|
# ... existing code ...
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
# ... modified code ...
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
# ... rest of the code ...
|
431d3e960962543fd162770475a488bd9e21217e
|
setup.py
|
setup.py
|
from distutils.core import setup
version=__import__('sendfile').__version__
setup(
name='django-sendfile',
version=version,
description='Abstraction to offload file uploads to web-server (e.g. Apache with mod_xsendfile) once Django has checked permissions etc.',
long_description=open('README.rst').read(),
author='John Montgomery',
author_email='[email protected]',
url='https://github.com/johnsensible/django-sendfile',
download_url='https://github.com/johnsensible/django-sendfile/archive/v%s.zip#egg=django-sendfile-%s' % (version, version),
license='BSD',
requires=['Django (>=1.4.2)', 'Unidecode'],
packages=['sendfile', 'sendfile.backends'],
package_dir={
'sendfile': 'sendfile',
'sendfile.backends': 'sendfile/backends',
},
package_data = {
'sendfile': ['testfile.txt'],
},
zip_safe=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from distutils.core import setup
version=__import__('sendfile').__version__
setup(
name='django-sendfile',
version=version,
description='Abstraction to offload file uploads to web-server (e.g. Apache with mod_xsendfile) once Django has checked permissions etc.',
long_description=open('README.rst').read(),
author='John Montgomery',
author_email='[email protected]',
url='https://github.com/johnsensible/django-sendfile',
download_url='https://github.com/johnsensible/django-sendfile/archive/v%s.zip#egg=django-sendfile-%s' % (version, version),
license='BSD',
requires=['Django (>=1.4.2)', 'Unidecode'],
install_requires=['Django>=1.4.2', 'Unidecode'],
packages=['sendfile', 'sendfile.backends'],
package_dir={
'sendfile': 'sendfile',
'sendfile.backends': 'sendfile/backends',
},
package_data = {
'sendfile': ['testfile.txt'],
},
zip_safe=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix requirements so pip correctly installs Django and Unidecode.
|
Fix requirements so pip correctly installs Django and Unidecode.
|
Python
|
bsd-3-clause
|
karyon/django-sendfile,nathanielvarona/django-sendfile,joshcartme/django-sendfile,NotSqrt/django-sendfile,johnsensible/django-sendfile,joshcartme/django-sendfile
|
python
|
## Code Before:
from distutils.core import setup
version=__import__('sendfile').__version__
setup(
name='django-sendfile',
version=version,
description='Abstraction to offload file uploads to web-server (e.g. Apache with mod_xsendfile) once Django has checked permissions etc.',
long_description=open('README.rst').read(),
author='John Montgomery',
author_email='[email protected]',
url='https://github.com/johnsensible/django-sendfile',
download_url='https://github.com/johnsensible/django-sendfile/archive/v%s.zip#egg=django-sendfile-%s' % (version, version),
license='BSD',
requires=['Django (>=1.4.2)', 'Unidecode'],
packages=['sendfile', 'sendfile.backends'],
package_dir={
'sendfile': 'sendfile',
'sendfile.backends': 'sendfile/backends',
},
package_data = {
'sendfile': ['testfile.txt'],
},
zip_safe=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
## Instruction:
Fix requirements so pip correctly installs Django and Unidecode.
## Code After:
from distutils.core import setup
version=__import__('sendfile').__version__
setup(
name='django-sendfile',
version=version,
description='Abstraction to offload file uploads to web-server (e.g. Apache with mod_xsendfile) once Django has checked permissions etc.',
long_description=open('README.rst').read(),
author='John Montgomery',
author_email='[email protected]',
url='https://github.com/johnsensible/django-sendfile',
download_url='https://github.com/johnsensible/django-sendfile/archive/v%s.zip#egg=django-sendfile-%s' % (version, version),
license='BSD',
requires=['Django (>=1.4.2)', 'Unidecode'],
install_requires=['Django>=1.4.2', 'Unidecode'],
packages=['sendfile', 'sendfile.backends'],
package_dir={
'sendfile': 'sendfile',
'sendfile.backends': 'sendfile/backends',
},
package_data = {
'sendfile': ['testfile.txt'],
},
zip_safe=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
# ... existing code ...
license='BSD',
requires=['Django (>=1.4.2)', 'Unidecode'],
install_requires=['Django>=1.4.2', 'Unidecode'],
packages=['sendfile', 'sendfile.backends'],
package_dir={
# ... rest of the code ...
|
8817481f758eeb0610b8c77fb9dd15dbdc37579b
|
setup.py
|
setup.py
|
from setuptools import setup
exec (open('plotly/version.py').read())
def readme():
with open('README.rst') as f:
return f.read()
setup(name='plotly',
version=__version__,
use_2to3=False,
author='Chris P',
author_email='[email protected]',
maintainer='Chris P',
maintainer_email='[email protected]',
url='https://plot.ly/api/python',
description="Python plotting library for collaborative, "
"interactive, publication-quality graphs.",
long_description=readme(),
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Visualization',
],
license='MIT',
packages=['plotly',
'plotly/plotly',
'plotly/plotly/chunked_requests',
'plotly/graph_objs',
'plotly/grid_objs',
'plotly/widgets',
'plotly/matplotlylib',
'plotly/matplotlylib/mplexporter',
'plotly/matplotlylib/mplexporter/renderers'],
package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']},
install_requires=['requests', 'six', 'pytz'],
extras_require={"PY2.6": ['simplejson', 'ordereddict',
'requests[security]']},
zip_safe=False)
|
from setuptools import setup
from setuptools import setup, find_packages
exec (open('plotly/version.py').read())
def readme():
with open('README.rst') as f:
return f.read()
setup(name='plotly',
version=__version__,
use_2to3=False,
author='Chris P',
author_email='[email protected]',
maintainer='Chris P',
maintainer_email='[email protected]',
url='https://plot.ly/api/python',
description="Python plotting library for collaborative, "
"interactive, publication-quality graphs.",
long_description=readme(),
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Visualization',
],
license='MIT',
packages=find_packages(),
package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']},
install_requires=['requests', 'six', 'pytz'],
extras_require={"PY2.6": ['simplejson', 'ordereddict',
'requests[security]']},
zip_safe=False)
|
Use `find_packages()` like all the cool kids do.
|
Use `find_packages()` like all the cool kids do.
|
Python
|
mit
|
plotly/python-api,plotly/python-api,plotly/python-api,plotly/plotly.py,ee-in/python-api,ee-in/python-api,ee-in/python-api,plotly/plotly.py,plotly/plotly.py
|
python
|
## Code Before:
from setuptools import setup
exec (open('plotly/version.py').read())
def readme():
with open('README.rst') as f:
return f.read()
setup(name='plotly',
version=__version__,
use_2to3=False,
author='Chris P',
author_email='[email protected]',
maintainer='Chris P',
maintainer_email='[email protected]',
url='https://plot.ly/api/python',
description="Python plotting library for collaborative, "
"interactive, publication-quality graphs.",
long_description=readme(),
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Visualization',
],
license='MIT',
packages=['plotly',
'plotly/plotly',
'plotly/plotly/chunked_requests',
'plotly/graph_objs',
'plotly/grid_objs',
'plotly/widgets',
'plotly/matplotlylib',
'plotly/matplotlylib/mplexporter',
'plotly/matplotlylib/mplexporter/renderers'],
package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']},
install_requires=['requests', 'six', 'pytz'],
extras_require={"PY2.6": ['simplejson', 'ordereddict',
'requests[security]']},
zip_safe=False)
## Instruction:
Use `find_packages()` like all the cool kids do.
## Code After:
from setuptools import setup
from setuptools import setup, find_packages
exec (open('plotly/version.py').read())
def readme():
with open('README.rst') as f:
return f.read()
setup(name='plotly',
version=__version__,
use_2to3=False,
author='Chris P',
author_email='[email protected]',
maintainer='Chris P',
maintainer_email='[email protected]',
url='https://plot.ly/api/python',
description="Python plotting library for collaborative, "
"interactive, publication-quality graphs.",
long_description=readme(),
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Visualization',
],
license='MIT',
packages=find_packages(),
package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']},
install_requires=['requests', 'six', 'pytz'],
extras_require={"PY2.6": ['simplejson', 'ordereddict',
'requests[security]']},
zip_safe=False)
|
...
from setuptools import setup
from setuptools import setup, find_packages
exec (open('plotly/version.py').read())
...
'Topic :: Scientific/Engineering :: Visualization',
],
license='MIT',
packages=find_packages(),
package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']},
install_requires=['requests', 'six', 'pytz'],
extras_require={"PY2.6": ['simplejson', 'ordereddict',
...
|
70f167d3d5a7540fb3521b82ec70bf7c6db09a99
|
tests/test_contrib.py
|
tests/test_contrib.py
|
from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
|
from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus)
|
Add test for recursive agg
|
Add test for recursive agg
|
Python
|
bsd-3-clause
|
mirnylab/cooler
|
python
|
## Code Before:
from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
## Instruction:
Add test for recursive agg
## Code After:
from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus)
|
...
from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
...
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus)
...
|
f5ace7ea8badb2401190e4845fb0216c7a80891e
|
tests/testall.py
|
tests/testall.py
|
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
alltests = unittest.TestSuite()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
alltests.addTest(m.suite)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
|
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
testLoader = unittest.TestLoader()
if len(sys.argv) > 1:
alltests = testLoader.loadTestsFromNames(sys.argv[1:])
else:
alltests = unittest.TestSuite()
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
t = testLoader.loadTestsFromModule(m)
alltests.addTest(t)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
|
Allow specifying which unit-tests to run
|
Allow specifying which unit-tests to run
e.g. 0test ../0release.xml -- testrelease.TestRelease.testBinaryRelease
|
Python
|
lgpl-2.1
|
timbertson/0release,0install/0release,0install/0release,gfxmonk/0release
|
python
|
## Code Before:
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
alltests = unittest.TestSuite()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
alltests.addTest(m.suite)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
## Instruction:
Allow specifying which unit-tests to run
e.g. 0test ../0release.xml -- testrelease.TestRelease.testBinaryRelease
## Code After:
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
testLoader = unittest.TestLoader()
if len(sys.argv) > 1:
alltests = testLoader.loadTestsFromNames(sys.argv[1:])
else:
alltests = unittest.TestSuite()
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
t = testLoader.loadTestsFromModule(m)
alltests.addTest(t)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
|
// ... existing code ...
if not my_dir:
my_dir = os.getcwd()
testLoader = unittest.TestLoader()
if len(sys.argv) > 1:
alltests = testLoader.loadTestsFromNames(sys.argv[1:])
else:
alltests = unittest.TestSuite()
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
t = testLoader.loadTestsFromModule(m)
alltests.addTest(t)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
// ... rest of the code ...
|
2c6a6c03660bf32e114f523c81da1df5c362dbcb
|
sample-app/src/main/java/ca/antonious/sample/models/Sample.java
|
sample-app/src/main/java/ca/antonious/sample/models/Sample.java
|
package ca.antonious.sample.models;
import android.app.Activity;
/**
* Created by George on 2017-01-01.
*/
public class Sample {
private String title;
private Class<? extends Activity> showcaseActivityClass;
public Sample(String title, Class<? extends Activity> showcaseActivityClass) {
this.title = title;
this.showcaseActivityClass = showcaseActivityClass;
}
public String getTitle() {
return title;
}
public Class<? extends Activity> getShowcaseActivityClass() {
return showcaseActivityClass;
}
}
|
package ca.antonious.sample.models;
import android.app.Activity;
/**
* Created by George on 2017-01-01.
*/
public class Sample {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample(String title, String description, Class<? extends Activity> showcaseActivityClass) {
this.title = title;
this.description = description;
this.showcaseActivityClass = showcaseActivityClass;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Class<? extends Activity> getShowcaseActivityClass() {
return showcaseActivityClass;
}
public static class Builder {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample build() {
return new Sample(title, description, showcaseActivityClass);
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Builder setShowcaseActivityClass(Class<? extends Activity> showcaseActivityClass) {
this.showcaseActivityClass = showcaseActivityClass;
return this;
}
}
}
|
Add description and builder to the sample
|
Add description and builder to the sample
|
Java
|
mit
|
gantonious/ViewCellAdapter,gantonious/ViewCellAdapter
|
java
|
## Code Before:
package ca.antonious.sample.models;
import android.app.Activity;
/**
* Created by George on 2017-01-01.
*/
public class Sample {
private String title;
private Class<? extends Activity> showcaseActivityClass;
public Sample(String title, Class<? extends Activity> showcaseActivityClass) {
this.title = title;
this.showcaseActivityClass = showcaseActivityClass;
}
public String getTitle() {
return title;
}
public Class<? extends Activity> getShowcaseActivityClass() {
return showcaseActivityClass;
}
}
## Instruction:
Add description and builder to the sample
## Code After:
package ca.antonious.sample.models;
import android.app.Activity;
/**
* Created by George on 2017-01-01.
*/
public class Sample {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample(String title, String description, Class<? extends Activity> showcaseActivityClass) {
this.title = title;
this.description = description;
this.showcaseActivityClass = showcaseActivityClass;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Class<? extends Activity> getShowcaseActivityClass() {
return showcaseActivityClass;
}
public static class Builder {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample build() {
return new Sample(title, description, showcaseActivityClass);
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Builder setShowcaseActivityClass(Class<? extends Activity> showcaseActivityClass) {
this.showcaseActivityClass = showcaseActivityClass;
return this;
}
}
}
|
...
public class Sample {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample(String title, String description, Class<? extends Activity> showcaseActivityClass) {
this.title = title;
this.description = description;
this.showcaseActivityClass = showcaseActivityClass;
}
...
return title;
}
public String getDescription() {
return description;
}
public Class<? extends Activity> getShowcaseActivityClass() {
return showcaseActivityClass;
}
public static class Builder {
private String title;
private String description;
private Class<? extends Activity> showcaseActivityClass;
public Sample build() {
return new Sample(title, description, showcaseActivityClass);
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Builder setShowcaseActivityClass(Class<? extends Activity> showcaseActivityClass) {
this.showcaseActivityClass = showcaseActivityClass;
return this;
}
}
}
...
|
1ca2092e54d1b1c06daf79eaf76710889a7eda2d
|
RobotC/MotorTest.c
|
RobotC/MotorTest.c
|
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
task main()
{
motor[leftMotor] =100;
motor[rightMotor] = -100;
wait1Msec(1000);
for(int i=0;i<kNumbOfRealMotors;i++) {
motor[i] = 0;
}
}
|
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
//If none of these work, I will be very sad.
#define TOTAL_MOTORS kNumbOfTotalMotors
//#define TOTAL_MOTORS kNumbOfRealMotors
//#define TOTAL_MOTORS kNumbOfVirtualMotors
task main()
{
for(int i=0;i<TOTAL_MOTORS;i++) {
motor[i] = 50;
}
wait1Msec(2000);
motor[Michelangelo_FR] = 0;
motor[Donatello_FL] = 0;
motor[Raphael_BR] = 0;
motor[Leonardo_BL] = 0;
}
|
Add motor loop tester to see once and for all if possible
|
Add motor loop tester to see once and for all if possible
|
C
|
mit
|
RMRobotics/FTC_5421_2014-2015,RMRobotics/FTC_5421_2014-2015
|
c
|
## Code Before:
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
task main()
{
motor[leftMotor] =100;
motor[rightMotor] = -100;
wait1Msec(1000);
for(int i=0;i<kNumbOfRealMotors;i++) {
motor[i] = 0;
}
}
## Instruction:
Add motor loop tester to see once and for all if possible
## Code After:
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
//If none of these work, I will be very sad.
#define TOTAL_MOTORS kNumbOfTotalMotors
//#define TOTAL_MOTORS kNumbOfRealMotors
//#define TOTAL_MOTORS kNumbOfVirtualMotors
task main()
{
for(int i=0;i<TOTAL_MOTORS;i++) {
motor[i] = 50;
}
wait1Msec(2000);
motor[Michelangelo_FR] = 0;
motor[Donatello_FL] = 0;
motor[Raphael_BR] = 0;
motor[Leonardo_BL] = 0;
}
|
...
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
//If none of these work, I will be very sad.
#define TOTAL_MOTORS kNumbOfTotalMotors
//#define TOTAL_MOTORS kNumbOfRealMotors
//#define TOTAL_MOTORS kNumbOfVirtualMotors
task main()
{
for(int i=0;i<TOTAL_MOTORS;i++) {
motor[i] = 50;
}
wait1Msec(2000);
motor[Michelangelo_FR] = 0;
motor[Donatello_FL] = 0;
motor[Raphael_BR] = 0;
motor[Leonardo_BL] = 0;
}
...
|
7e19c3058615f4599ed7339e2bd157b72cd51018
|
test_dimuon.py
|
test_dimuon.py
|
from dimuon import *
from nose.tools import *
from math import pi
class DummyParticle:
def __init__(self, q):
self.q = q
def test_no_particles():
particles = []
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_one_particle():
pos = DummyParticle(+1)
particles = [pos]
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_two_particles_unlike_sign():
pos = DummyParticle(+1)
neg = DummyParticle(-1)
particles = [pos,neg]
pairs = find_pairs(particles)
assert_equal(pairs, [(pos,neg)] )
def test_two_particles_like_sign():
pos1 = DummyParticle(+1)
pos2 = DummyParticle(+1)
particles = [pos1,pos2]
pairs = find_pairs(particles)
assert_equal(len(pairs), 0)
def test_inv_mass_zero_mass_particles():
pos = Particle(1.0, +1.0, 0, pi/2) # massless particle with pt = 1 GeV
neg = Particle(1.0, -1.0, pi, pi/2) # massless, pt = 1 GeV, opposite direction
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
|
from dimuon import *
from nose.tools import *
from math import pi
class DummyParticle:
def __init__(self, q):
self.q = q
def test_no_particles():
particles = []
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_one_particle():
pos = DummyParticle(+1)
particles = [pos]
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_two_particles_unlike_sign():
pos = DummyParticle(+1)
neg = DummyParticle(-1)
particles = [pos,neg]
pairs = find_pairs(particles)
assert_equal(pairs, [(pos,neg)] )
def test_two_particles_like_sign():
pos1 = DummyParticle(+1)
pos2 = DummyParticle(+1)
particles = [pos1,pos2]
pairs = find_pairs(particles)
assert_equal(len(pairs), 0)
def test_inv_mass_zero_mass_particles():
pos = Particle(1.0, +1.0, 0, pi/2) # massless particle with pt = 1 GeV
neg = Particle(1.0, -1.0, pi, pi/2) # massless, pt = 1 GeV, opposite direction
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
def test_inv_mass_nonzero_mass_particles():
# shouldn't actually make any difference if masses are non-zero
pos = Particle(1.0, +0.5, 0, pi/2)
neg = Particle(1.0, -0.5, pi, pi/2)
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
|
Test pair mass for non-zero mass particles
|
Test pair mass for non-zero mass particles
|
Python
|
mit
|
benwaugh/dimuon
|
python
|
## Code Before:
from dimuon import *
from nose.tools import *
from math import pi
class DummyParticle:
def __init__(self, q):
self.q = q
def test_no_particles():
particles = []
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_one_particle():
pos = DummyParticle(+1)
particles = [pos]
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_two_particles_unlike_sign():
pos = DummyParticle(+1)
neg = DummyParticle(-1)
particles = [pos,neg]
pairs = find_pairs(particles)
assert_equal(pairs, [(pos,neg)] )
def test_two_particles_like_sign():
pos1 = DummyParticle(+1)
pos2 = DummyParticle(+1)
particles = [pos1,pos2]
pairs = find_pairs(particles)
assert_equal(len(pairs), 0)
def test_inv_mass_zero_mass_particles():
pos = Particle(1.0, +1.0, 0, pi/2) # massless particle with pt = 1 GeV
neg = Particle(1.0, -1.0, pi, pi/2) # massless, pt = 1 GeV, opposite direction
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
## Instruction:
Test pair mass for non-zero mass particles
## Code After:
from dimuon import *
from nose.tools import *
from math import pi
class DummyParticle:
def __init__(self, q):
self.q = q
def test_no_particles():
particles = []
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_one_particle():
pos = DummyParticle(+1)
particles = [pos]
pairs = find_pairs(particles)
assert len(pairs) == 0
def test_two_particles_unlike_sign():
pos = DummyParticle(+1)
neg = DummyParticle(-1)
particles = [pos,neg]
pairs = find_pairs(particles)
assert_equal(pairs, [(pos,neg)] )
def test_two_particles_like_sign():
pos1 = DummyParticle(+1)
pos2 = DummyParticle(+1)
particles = [pos1,pos2]
pairs = find_pairs(particles)
assert_equal(len(pairs), 0)
def test_inv_mass_zero_mass_particles():
pos = Particle(1.0, +1.0, 0, pi/2) # massless particle with pt = 1 GeV
neg = Particle(1.0, -1.0, pi, pi/2) # massless, pt = 1 GeV, opposite direction
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
def test_inv_mass_nonzero_mass_particles():
# shouldn't actually make any difference if masses are non-zero
pos = Particle(1.0, +0.5, 0, pi/2)
neg = Particle(1.0, -0.5, pi, pi/2)
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
|
// ... existing code ...
pos = Particle(1.0, +1.0, 0, pi/2) # massless particle with pt = 1 GeV
neg = Particle(1.0, -1.0, pi, pi/2) # massless, pt = 1 GeV, opposite direction
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
def test_inv_mass_nonzero_mass_particles():
# shouldn't actually make any difference if masses are non-zero
pos = Particle(1.0, +0.5, 0, pi/2)
neg = Particle(1.0, -0.5, pi, pi/2)
assert_equal(inv_mass_from_pair((pos,neg)), 2.0)
// ... rest of the code ...
|
aed82bc0995cf4175c0ab8c521dfc8e89d776a7e
|
Mac/scripts/zappycfiles.py
|
Mac/scripts/zappycfiles.py
|
import os
import sys
doit = 1
def main():
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
if not sys.argv[1:]:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
|
"""Recursively zap all .pyc files"""
import os
import sys
# set doit true to actually delete files
# set doit false to just print what would be deleted
doit = 1
def main():
if not sys.argv[1:]:
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
|
Patch by Russel Owen: if we have command line arguments zap pyc files in the directories given.
|
Patch by Russel Owen: if we have command line arguments zap pyc files
in the directories given.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
python
|
## Code Before:
import os
import sys
doit = 1
def main():
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
if not sys.argv[1:]:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
## Instruction:
Patch by Russel Owen: if we have command line arguments zap pyc files
in the directories given.
## Code After:
"""Recursively zap all .pyc files"""
import os
import sys
# set doit true to actually delete files
# set doit false to just print what would be deleted
doit = 1
def main():
if not sys.argv[1:]:
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
|
// ... existing code ...
"""Recursively zap all .pyc files"""
import os
import sys
# set doit true to actually delete files
# set doit false to just print what would be deleted
doit = 1
def main():
if not sys.argv[1:]:
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
// ... rest of the code ...
|
0571579b98f516c208e6e84ae77abe25c4f248fc
|
setup.py
|
setup.py
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='[email protected]',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=__doc__,
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_long_description():
with open('README.rst') as f:
return f.read()
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='[email protected]',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=get_long_description(),
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
|
Use README.rst as long_description for package info.
|
Use README.rst as long_description for package info.
|
Python
|
apache-2.0
|
ahawker/scratchdir
|
python
|
## Code Before:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='[email protected]',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=__doc__,
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
## Instruction:
Use README.rst as long_description for package info.
## Code After:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_long_description():
with open('README.rst') as f:
return f.read()
setup(
name='scratchdir',
version='0.0.3',
author='Andrew Hawker',
author_email='[email protected]',
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=get_long_description(),
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules'
)
)
|
// ... existing code ...
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_long_description():
with open('README.rst') as f:
return f.read()
setup(
// ... modified code ...
url='https://github.com/ahawker/scratchdir',
license='Apache 2.0',
description='Context manager used to maintain your temporary directories/files.',
long_description=get_long_description(),
py_modules=['scratchdir'],
classifiers=(
'Development Status :: 5 - Production/Stable',
// ... rest of the code ...
|
6bff4763f486f10e43890191244b33d5b609bfdd
|
flashcards/commands/sets.py
|
flashcards/commands/sets.py
|
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
|
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
"""
Select a studyset.
Focus on a studyset, every new added cards are going to be put directly in
this studyset.
"""
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
|
Add docstring to select command.
|
Add docstring to select command.
|
Python
|
mit
|
zergov/flashcards,zergov/flashcards
|
python
|
## Code Before:
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
## Instruction:
Add docstring to select command.
## Code After:
import os
import click
from flashcards import sets
from flashcards import storage
@click.group('sets')
def sets_group():
"""Command related to the StudySet object """
pass
@click.command('new')
@click.option('--title', prompt='Title of the study set')
@click.option('--desc', prompt='Description for the study set (optional)')
def new(title, desc):
"""
Create a new study set.
User supplies a title and a description.
If this study set does not exist, it is created.
"""
study_set = sets.StudySet(title, desc)
filepath = storage.create_studyset_file(study_set)
# automatically select this studyset
storage.link_selected_studyset(filepath)
click.echo('Study set created !')
@click.command('select')
@click.argument('studyset')
def select(studyset):
"""
Select a studyset.
Focus on a studyset, every new added cards are going to be put directly in
this studyset.
"""
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
click.echo('Selected studyset: %s' % studyset_obj.title)
click.echo('Next created cards will be automatically added '
'to this studyset.')
sets_group.add_command(new)
sets_group.add_command(select)
|
// ... existing code ...
@click.command('select')
@click.argument('studyset')
def select(studyset):
"""
Select a studyset.
Focus on a studyset, every new added cards are going to be put directly in
this studyset.
"""
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
storage.link_selected_studyset(studyset_path)
studyset_obj = storage.load_studyset(studyset_path).load()
// ... rest of the code ...
|
cd5053ac36e13b57e95eeb1241032c97b48a4a85
|
planetstack/openstack_observer/backend.py
|
planetstack/openstack_observer/backend.py
|
import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
try:
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
except:
logger.log_exc("Exception in child thread")
|
import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
|
Drop try/catch that causes uncaught errors in the Observer to be silently ignored
|
Drop try/catch that causes uncaught errors in the Observer to be silently ignored
|
Python
|
apache-2.0
|
wathsalav/xos,wathsalav/xos,wathsalav/xos,wathsalav/xos
|
python
|
## Code Before:
import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
try:
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
except:
logger.log_exc("Exception in child thread")
## Instruction:
Drop try/catch that causes uncaught errors in the Observer to be silently ignored
## Code After:
import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
|
# ... existing code ...
class Backend:
def run(self):
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
# ... modified code ...
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
# ... rest of the code ...
|
0fee9081555e6b8a104aa857a29df14712c5fd43
|
ext/opengl/gl-ext-3dfx.c
|
ext/opengl/gl-ext-3dfx.c
|
/*
* Copyright (C) 2007 Jan Dvorak <[email protected]>
*
* This program is distributed under the terms of the MIT license.
* See the included MIT-LICENSE file for the terms of this license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "common.h"
/* OpenGL 3DFX extensions */
/* #208 - GL_3DFX_tbuffer */
GL_FUNC_LOAD_1(TbufferMask3DFX,GLvoid, GLuint, "GL_3DFX_tbuffer")
void gl_init_functions_ext_3dfx(VALUE module)
{
/* #208 - GL_3DFX_tbuffer */
rb_define_module_function(module, "glTbufferMask3DFX", gl_TbufferMask3DFX, 1);
}
|
/*
* Copyright (C) 2007 Jan Dvorak <[email protected]>
*
* This program is distributed under the terms of the MIT license.
* See the included MIT-LICENSE file for the terms of this license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "common.h"
/* OpenGL 3DFX extensions */
/* #208 - GL_3DFX_tbuffer */
GL_FUNC_LOAD_1(TbufferMask3DFX,GLvoid, GLuint, "GL_3DFX_tbuffer")
void gl_init_functions_ext_3dfx(VALUE klass)
{
/* #208 - GL_3DFX_tbuffer */
rb_define_method(klass, "glTbufferMask3DFX", gl_TbufferMask3DFX, 1);
}
|
Change remaining glTbufferMask3DFX to an instance method.
|
Change remaining glTbufferMask3DFX to an instance method.
|
C
|
mit
|
larskanis/opengl,larskanis/opengl
|
c
|
## Code Before:
/*
* Copyright (C) 2007 Jan Dvorak <[email protected]>
*
* This program is distributed under the terms of the MIT license.
* See the included MIT-LICENSE file for the terms of this license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "common.h"
/* OpenGL 3DFX extensions */
/* #208 - GL_3DFX_tbuffer */
GL_FUNC_LOAD_1(TbufferMask3DFX,GLvoid, GLuint, "GL_3DFX_tbuffer")
void gl_init_functions_ext_3dfx(VALUE module)
{
/* #208 - GL_3DFX_tbuffer */
rb_define_module_function(module, "glTbufferMask3DFX", gl_TbufferMask3DFX, 1);
}
## Instruction:
Change remaining glTbufferMask3DFX to an instance method.
## Code After:
/*
* Copyright (C) 2007 Jan Dvorak <[email protected]>
*
* This program is distributed under the terms of the MIT license.
* See the included MIT-LICENSE file for the terms of this license.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "common.h"
/* OpenGL 3DFX extensions */
/* #208 - GL_3DFX_tbuffer */
GL_FUNC_LOAD_1(TbufferMask3DFX,GLvoid, GLuint, "GL_3DFX_tbuffer")
void gl_init_functions_ext_3dfx(VALUE klass)
{
/* #208 - GL_3DFX_tbuffer */
rb_define_method(klass, "glTbufferMask3DFX", gl_TbufferMask3DFX, 1);
}
|
// ... existing code ...
/* #208 - GL_3DFX_tbuffer */
GL_FUNC_LOAD_1(TbufferMask3DFX,GLvoid, GLuint, "GL_3DFX_tbuffer")
void gl_init_functions_ext_3dfx(VALUE klass)
{
/* #208 - GL_3DFX_tbuffer */
rb_define_method(klass, "glTbufferMask3DFX", gl_TbufferMask3DFX, 1);
}
// ... rest of the code ...
|
2ab77e34c2e175d90c79dde9b708e3c5beff64de
|
include/sys/dirent.h
|
include/sys/dirent.h
|
/*
* Copyright (c) 2007, 2008, 2009, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#ifndef DIRENT_H_
#define DIRENT_H_
#include <sys/cdefs.h>
#define NAME_MAX 512
struct dirent {
// long d_ino;
// off_t d_off;
// unsigned short d_reclen;
char d_name[NAME_MAX + 1];
};
typedef struct {
struct dirent dirent;
void *vh; // really a vfs_handle_t
} DIR;
__BEGIN_DECLS
DIR *opendir(const char *pathname);
struct dirent *readdir(DIR* dir);
int closedir(DIR *dir);
__END_DECLS
#endif
|
/*
* Copyright (c) 2007, 2008, 2009, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#ifndef DIRENT_H_
#define DIRENT_H_
#include <sys/cdefs.h>
// Depending on header include order, this may collide with the definition in
// newlib's <dirent.h> See open issue: https://code.systems.ethz.ch/T58#1169
#ifndef NAME_MAX
#define NAME_MAX 512
#endif
struct dirent {
// long d_ino;
// off_t d_off;
// unsigned short d_reclen;
char d_name[NAME_MAX + 1];
};
typedef struct {
struct dirent dirent;
void *vh; // really a vfs_handle_t
} DIR;
__BEGIN_DECLS
DIR *opendir(const char *pathname);
struct dirent *readdir(DIR* dir);
int closedir(DIR *dir);
__END_DECLS
#endif
|
Duplicate definition of NAME_MAX macro
|
Duplicate definition of NAME_MAX macro
I broke the build in rBFIaee0075101b1; this is just a temporary band-aid and
only masks the more general issue described in T58. If you have an idea for a
better fix, please let me know.
Signed-off-by: Zaheer Chothia <[email protected]>
|
C
|
mit
|
BarrelfishOS/barrelfish,BarrelfishOS/barrelfish,BarrelfishOS/barrelfish,8l/barrelfish,kishoredbn/barrelfish,BarrelfishOS/barrelfish,kishoredbn/barrelfish,kishoredbn/barrelfish,BarrelfishOS/barrelfish,kishoredbn/barrelfish,BarrelfishOS/barrelfish,8l/barrelfish,kishoredbn/barrelfish,8l/barrelfish,kishoredbn/barrelfish,BarrelfishOS/barrelfish,8l/barrelfish,8l/barrelfish,BarrelfishOS/barrelfish,8l/barrelfish,BarrelfishOS/barrelfish
|
c
|
## Code Before:
/*
* Copyright (c) 2007, 2008, 2009, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#ifndef DIRENT_H_
#define DIRENT_H_
#include <sys/cdefs.h>
#define NAME_MAX 512
struct dirent {
// long d_ino;
// off_t d_off;
// unsigned short d_reclen;
char d_name[NAME_MAX + 1];
};
typedef struct {
struct dirent dirent;
void *vh; // really a vfs_handle_t
} DIR;
__BEGIN_DECLS
DIR *opendir(const char *pathname);
struct dirent *readdir(DIR* dir);
int closedir(DIR *dir);
__END_DECLS
#endif
## Instruction:
Duplicate definition of NAME_MAX macro
I broke the build in rBFIaee0075101b1; this is just a temporary band-aid and
only masks the more general issue described in T58. If you have an idea for a
better fix, please let me know.
Signed-off-by: Zaheer Chothia <[email protected]>
## Code After:
/*
* Copyright (c) 2007, 2008, 2009, ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
*/
#ifndef DIRENT_H_
#define DIRENT_H_
#include <sys/cdefs.h>
// Depending on header include order, this may collide with the definition in
// newlib's <dirent.h> See open issue: https://code.systems.ethz.ch/T58#1169
#ifndef NAME_MAX
#define NAME_MAX 512
#endif
struct dirent {
// long d_ino;
// off_t d_off;
// unsigned short d_reclen;
char d_name[NAME_MAX + 1];
};
typedef struct {
struct dirent dirent;
void *vh; // really a vfs_handle_t
} DIR;
__BEGIN_DECLS
DIR *opendir(const char *pathname);
struct dirent *readdir(DIR* dir);
int closedir(DIR *dir);
__END_DECLS
#endif
|
...
#include <sys/cdefs.h>
// Depending on header include order, this may collide with the definition in
// newlib's <dirent.h> See open issue: https://code.systems.ethz.ch/T58#1169
#ifndef NAME_MAX
#define NAME_MAX 512
#endif
struct dirent {
// long d_ino;
...
|
9f49055456049bdff41f61231553d29573fac184
|
test/Analysis/uninit-vals-ps.c
|
test/Analysis/uninit-vals-ps.c
|
// RUN: clang -checker-simple -verify %s
struct FPRec {
void (*my_func)(int * x);
};
int bar(int x);
int f1_a(struct FPRec* foo) {
int x;
(*foo->my_func)(&x);
return bar(x)+1; // no-warning
}
int f1_b() {
int x;
return bar(x)+1; // expected-warning{{Pass-by-value argument in function is undefined.}}
}
int f2() {
int x;
if (x+1) // expected-warning{{Branch}}
return 1;
return 2;
}
int f2_b() {
int x;
return ((x+1)+2+((x))) + 1 ? 1 : 2; // expected-warning{{Branch}}
}
int f3(void) {
int i;
int *p = &i;
if (*p > 0) // expected-warning{{Branch condition evaluates to an uninitialized value}}
return 0;
else
return 1;
}
|
// RUN: clang -checker-simple -verify %s &&
// RUN: clang -checker-simple -analyzer-store-region -verify %s
struct FPRec {
void (*my_func)(int * x);
};
int bar(int x);
int f1_a(struct FPRec* foo) {
int x;
(*foo->my_func)(&x);
return bar(x)+1; // no-warning
}
int f1_b() {
int x;
return bar(x)+1; // expected-warning{{Pass-by-value argument in function is undefined.}}
}
int f2() {
int x;
if (x+1) // expected-warning{{Branch}}
return 1;
return 2;
}
int f2_b() {
int x;
return ((x+1)+2+((x))) + 1 ? 1 : 2; // expected-warning{{Branch}}
}
int f3(void) {
int i;
int *p = &i;
if (*p > 0) // expected-warning{{Branch condition evaluates to an uninitialized value}}
return 0;
else
return 1;
}
|
Enable test file for 'region store' in addition to basic store.
|
Enable test file for 'region store' in addition to basic store.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@59762 91177308-0d34-0410-b5e6-96231b3b80d8
|
C
|
apache-2.0
|
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
|
c
|
## Code Before:
// RUN: clang -checker-simple -verify %s
struct FPRec {
void (*my_func)(int * x);
};
int bar(int x);
int f1_a(struct FPRec* foo) {
int x;
(*foo->my_func)(&x);
return bar(x)+1; // no-warning
}
int f1_b() {
int x;
return bar(x)+1; // expected-warning{{Pass-by-value argument in function is undefined.}}
}
int f2() {
int x;
if (x+1) // expected-warning{{Branch}}
return 1;
return 2;
}
int f2_b() {
int x;
return ((x+1)+2+((x))) + 1 ? 1 : 2; // expected-warning{{Branch}}
}
int f3(void) {
int i;
int *p = &i;
if (*p > 0) // expected-warning{{Branch condition evaluates to an uninitialized value}}
return 0;
else
return 1;
}
## Instruction:
Enable test file for 'region store' in addition to basic store.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@59762 91177308-0d34-0410-b5e6-96231b3b80d8
## Code After:
// RUN: clang -checker-simple -verify %s &&
// RUN: clang -checker-simple -analyzer-store-region -verify %s
struct FPRec {
void (*my_func)(int * x);
};
int bar(int x);
int f1_a(struct FPRec* foo) {
int x;
(*foo->my_func)(&x);
return bar(x)+1; // no-warning
}
int f1_b() {
int x;
return bar(x)+1; // expected-warning{{Pass-by-value argument in function is undefined.}}
}
int f2() {
int x;
if (x+1) // expected-warning{{Branch}}
return 1;
return 2;
}
int f2_b() {
int x;
return ((x+1)+2+((x))) + 1 ? 1 : 2; // expected-warning{{Branch}}
}
int f3(void) {
int i;
int *p = &i;
if (*p > 0) // expected-warning{{Branch condition evaluates to an uninitialized value}}
return 0;
else
return 1;
}
|
...
// RUN: clang -checker-simple -verify %s &&
// RUN: clang -checker-simple -analyzer-store-region -verify %s
struct FPRec {
void (*my_func)(int * x);
...
|
7444dda53e8f3e564cd0cb7d7db5dc9e5bc3f5ae
|
plugins/groovy/src/org/jetbrains/plugins/groovy/util/ClassInstanceCache.java
|
plugins/groovy/src/org/jetbrains/plugins/groovy/util/ClassInstanceCache.java
|
package org.jetbrains.plugins.groovy.util;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
/**
* @author Sergey Evdokimov
*/
public class ClassInstanceCache {
private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();
private ClassInstanceCache() {
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(@NotNull String className) {
Object res = CACHE.get(className);
if (res != null) return (T)res;
try {
Object instance = Class.forName(className).newInstance();
Object oldValue = CACHE.putIfAbsent(className, instance);
if (oldValue != null) {
instance = oldValue;
}
return (T)instance;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package org.jetbrains.plugins.groovy.util;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
/**
* @author Sergey Evdokimov
*/
public class ClassInstanceCache {
private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();
private ClassInstanceCache() {
}
private static Object createInstance(@NotNull String className) {
try {
try {
return Class.forName(className).newInstance();
}
catch (ClassNotFoundException e) {
for (IdeaPluginDescriptor descriptor : PluginManager.getPlugins()) {
try {
return descriptor.getPluginClassLoader().loadClass(className).newInstance();
}
catch (ClassNotFoundException ignored) {
}
}
throw new RuntimeException("Class not found: " + className);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(@NotNull String className) {
Object res = CACHE.get(className);
if (res == null) {
res = createInstance(className);
Object oldValue = CACHE.putIfAbsent(className, res);
if (oldValue != null) {
res = oldValue;
}
}
return (T)res;
}
}
|
Fix EA-30104: ClassNotFound exception: Don't forget that plugins loaded by different class loader.
|
Fix EA-30104: ClassNotFound exception: Don't forget that plugins loaded by different class loader.
|
Java
|
apache-2.0
|
tmpgit/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,izonder/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,supersven/intellij-community,izonder/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,diorcety/intellij-community,izonder/intellij-community,hurricup/intellij-community,FHannes/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,signed/intellij-community,supersven/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,kdwink/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,FHannes/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,allotria/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,adedayo/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,amith01994/intellij-community,consulo/consulo,Distrotech/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,blademainer/intellij-community,fitermay/intellij-community,samthor/intellij-community,izonder/intellij-community,vvv1559/intellij-community,signed/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,fnouama/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,jagguli/intellij-community,xfournet/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,signed/intellij-community,ahb0327/intellij-community,slisson/intellij-community,adedayo/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,kool79/intellij-community,izonder/intellij-community,izonder/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,semonte/intellij-community,slisson/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,consulo/consulo,Distrotech/intellij-community,youdonghai/intellij-community,slisson/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,slisson/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,samthor/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,da1z/intellij-community,hurricup/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,da1z/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,fnouama/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,kdwink/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,fitermay/intellij-community,petteyg/intellij-community,signed/intellij-community,dslomov/intellij-community,consulo/consulo,consulo/consulo,ol-loginov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,supersven/intellij-community,FHannes/intellij-community,jagguli/intellij-community,da1z/intellij-community,hurricup/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,fnouama/intellij-community,caot/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,caot/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,allotria/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,holmes/intellij-community,petteyg/intellij-community,supersven/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,signed/intellij-community,retomerz/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,amith01994/intellij-community,asedunov/intellij-community,semonte/intellij-community,retomerz/intellij-community,jagguli/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,retomerz/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,retomerz/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,signed/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,da1z/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,robovm/robovm-studio,hurricup/intellij-community,jagguli/intellij-community,ryano144/intellij-community,clumsy/intellij-community,vladmm/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,samthor/intellij-community,caot/intellij-community,alphafoobar/intellij-community,consulo/consulo,caot/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,holmes/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,kool79/intellij-community,nicolargo/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,holmes/intellij-community,wreckJ/intellij-community,allotria/intellij-community,semonte/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ernestp/consulo,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,slisson/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,apixandru/intellij-community,samthor/intellij-community,blademainer/intellij-community,retomerz/intellij-community,supersven/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,allotria/intellij-community,holmes/intellij-community,blademainer/intellij-community,jagguli/intellij-community,blademainer/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ernestp/consulo,asedunov/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,blademainer/intellij-community,fitermay/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,FHannes/intellij-community,consulo/consulo,robovm/robovm-studio,ibinti/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,kdwink/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,lucafavatella/intellij-community,signed/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,retomerz/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,fnouama/intellij-community,robovm/robovm-studio,diorcety/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,kool79/intellij-community,vladmm/intellij-community,FHannes/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,caot/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,diorcety/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,signed/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,FHannes/intellij-community,samthor/intellij-community,ernestp/consulo,ol-loginov/intellij-community,diorcety/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,izonder/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,retomerz/intellij-community,caot/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ibinti/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,asedunov/intellij-community,supersven/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,robovm/robovm-studio,fnouama/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ibinti/intellij-community,holmes/intellij-community,blademainer/intellij-community,robovm/robovm-studio,jagguli/intellij-community,xfournet/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ernestp/consulo,slisson/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,kool79/intellij-community,vladmm/intellij-community,allotria/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ernestp/consulo,TangHao1987/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,da1z/intellij-community,petteyg/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ernestp/consulo,TangHao1987/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,signed/intellij-community,adedayo/intellij-community,fnouama/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,signed/intellij-community,vladmm/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,ryano144/intellij-community,blademainer/intellij-community,slisson/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,allotria/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,da1z/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,apixandru/intellij-community,retomerz/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,kool79/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,izonder/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,petteyg/intellij-community,amith01994/intellij-community,caot/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community
|
java
|
## Code Before:
package org.jetbrains.plugins.groovy.util;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
/**
* @author Sergey Evdokimov
*/
public class ClassInstanceCache {
private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();
private ClassInstanceCache() {
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(@NotNull String className) {
Object res = CACHE.get(className);
if (res != null) return (T)res;
try {
Object instance = Class.forName(className).newInstance();
Object oldValue = CACHE.putIfAbsent(className, instance);
if (oldValue != null) {
instance = oldValue;
}
return (T)instance;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
## Instruction:
Fix EA-30104: ClassNotFound exception: Don't forget that plugins loaded by different class loader.
## Code After:
package org.jetbrains.plugins.groovy.util;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
/**
* @author Sergey Evdokimov
*/
public class ClassInstanceCache {
private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();
private ClassInstanceCache() {
}
private static Object createInstance(@NotNull String className) {
try {
try {
return Class.forName(className).newInstance();
}
catch (ClassNotFoundException e) {
for (IdeaPluginDescriptor descriptor : PluginManager.getPlugins()) {
try {
return descriptor.getPluginClassLoader().loadClass(className).newInstance();
}
catch (ClassNotFoundException ignored) {
}
}
throw new RuntimeException("Class not found: " + className);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(@NotNull String className) {
Object res = CACHE.get(className);
if (res == null) {
res = createInstance(className);
Object oldValue = CACHE.putIfAbsent(className, res);
if (oldValue != null) {
res = oldValue;
}
}
return (T)res;
}
}
|
// ... existing code ...
package org.jetbrains.plugins.groovy.util;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
// ... modified code ...
private ClassInstanceCache() {
}
private static Object createInstance(@NotNull String className) {
try {
try {
return Class.forName(className).newInstance();
}
catch (ClassNotFoundException e) {
for (IdeaPluginDescriptor descriptor : PluginManager.getPlugins()) {
try {
return descriptor.getPluginClassLoader().loadClass(className).newInstance();
}
catch (ClassNotFoundException ignored) {
}
}
throw new RuntimeException("Class not found: " + className);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static <T> T getInstance(@NotNull String className) {
Object res = CACHE.get(className);
if (res == null) {
res = createInstance(className);
Object oldValue = CACHE.putIfAbsent(className, res);
if (oldValue != null) {
res = oldValue;
}
}
return (T)res;
}
}
// ... rest of the code ...
|
0c3529bd264d5512e31d828c65676baff6edefa6
|
pinax/waitinglist/templatetags/pinax_waitinglist_tags.py
|
pinax/waitinglist/templatetags/pinax_waitinglist_tags.py
|
from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.assignment_tag
def waitinglist_entry_form():
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
return WaitingListEntryForm()
|
from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.simple_tag(takes_context=True)
def waitinglist_entry_form(context):
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
initial = {}
if "request" in context:
initial.update({
"referrer": context["request"].META.get("HTTP_REFERER", ""),
"campaign": context["request"].GET.get("wlc", "")
})
return WaitingListEntryForm(initial=initial)
|
Update template tag to also take context
|
Update template tag to also take context
|
Python
|
mit
|
pinax/pinax-waitinglist,pinax/pinax-waitinglist
|
python
|
## Code Before:
from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.assignment_tag
def waitinglist_entry_form():
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
return WaitingListEntryForm()
## Instruction:
Update template tag to also take context
## Code After:
from django import template
from ..forms import WaitingListEntryForm
register = template.Library()
@register.simple_tag(takes_context=True)
def waitinglist_entry_form(context):
"""
Get a (new) form object to post a new comment.
Syntax::
{% waitinglist_entry_form as [varname] %}
"""
initial = {}
if "request" in context:
initial.update({
"referrer": context["request"].META.get("HTTP_REFERER", ""),
"campaign": context["request"].GET.get("wlc", "")
})
return WaitingListEntryForm(initial=initial)
|
// ... existing code ...
register = template.Library()
@register.simple_tag(takes_context=True)
def waitinglist_entry_form(context):
"""
Get a (new) form object to post a new comment.
// ... modified code ...
{% waitinglist_entry_form as [varname] %}
"""
initial = {}
if "request" in context:
initial.update({
"referrer": context["request"].META.get("HTTP_REFERER", ""),
"campaign": context["request"].GET.get("wlc", "")
})
return WaitingListEntryForm(initial=initial)
// ... rest of the code ...
|
78bebaa2902636e33409591675b1bede6c359aad
|
telepyth/__init__.py
|
telepyth/__init__.py
|
from telepyth.client import TelePythClient
from telepyth.utils import is_interactive
if is_interactive():
from telepyth.magics import TelePythMagics
|
from telepyth.client import TelePythClient
from telepyth.utils import is_interactive
TelepythClient = TelePythClient # make alias to origin definition
if is_interactive():
from telepyth.magics import TelePythMagics
|
Add alias to TelePythClient which will be deprecated in the future.
|
Add alias to TelePythClient which will be deprecated in the future.
|
Python
|
mit
|
daskol/telepyth,daskol/telepyth
|
python
|
## Code Before:
from telepyth.client import TelePythClient
from telepyth.utils import is_interactive
if is_interactive():
from telepyth.magics import TelePythMagics
## Instruction:
Add alias to TelePythClient which will be deprecated in the future.
## Code After:
from telepyth.client import TelePythClient
from telepyth.utils import is_interactive
TelepythClient = TelePythClient # make alias to origin definition
if is_interactive():
from telepyth.magics import TelePythMagics
|
...
from telepyth.client import TelePythClient
from telepyth.utils import is_interactive
TelepythClient = TelePythClient # make alias to origin definition
if is_interactive():
from telepyth.magics import TelePythMagics
...
|
ccc98ced56ee8dda02332720c7146e1548a3b53c
|
project/project/urls.py
|
project/project/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
url('^accounts/social/', include('allauth.socialaccount.urls')),
url('^accounts/', include('allauth.socialaccount.providers.google.urls')),
url(r'^', include("project.teams.urls")),
url(r'^', include("project.profiles.urls")),
]
|
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/login/$', RedirectView.as_view(url=settings.LOGIN_URL),
name='account_login'),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
url(r'^accounts/social/', include('allauth.socialaccount.urls')),
url(r'^accounts/', include('allauth.socialaccount.providers.google.urls')),
url(r'^', include("project.teams.urls")),
url(r'^', include("project.profiles.urls")),
]
|
Set up redirect to login view
|
Set up redirect to login view
|
Python
|
mit
|
jonsimington/app,compsci-hfh/app,compsci-hfh/app,jonsimington/app
|
python
|
## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
url('^accounts/social/', include('allauth.socialaccount.urls')),
url('^accounts/', include('allauth.socialaccount.providers.google.urls')),
url(r'^', include("project.teams.urls")),
url(r'^', include("project.profiles.urls")),
]
## Instruction:
Set up redirect to login view
## Code After:
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/login/$', RedirectView.as_view(url=settings.LOGIN_URL),
name='account_login'),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
url(r'^accounts/social/', include('allauth.socialaccount.urls')),
url(r'^accounts/', include('allauth.socialaccount.providers.google.urls')),
url(r'^', include("project.teams.urls")),
url(r'^', include("project.profiles.urls")),
]
|
# ... existing code ...
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/login/$', RedirectView.as_view(url=settings.LOGIN_URL),
name='account_login'),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
url(r'^accounts/social/', include('allauth.socialaccount.urls')),
url(r'^accounts/', include('allauth.socialaccount.providers.google.urls')),
url(r'^', include("project.teams.urls")),
url(r'^', include("project.profiles.urls")),
# ... rest of the code ...
|
2179dee14cfbd58ab8d8779561ac3826fe8892dd
|
custom/enikshay/reports/views.py
|
custom/enikshay/reports/views.py
|
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def _locations_query(self, domain, query_text):
if query_text:
return SQLLocation.active_objects.filter_path_by_user_input(
domain=domain, user_input=query_text)
else:
return SQLLocation.active_objects.filter(domain=domain)
def query(self, domain, query_context):
locations = self._locations_query(domain, query_context.query).order_by('name')
return [
{'id': loc.location_id, 'text': loc.display_name}
for loc in locations[query_context.offset:query_context.offset + query_context.limit]
]
def query_count(self, domain, query):
return self._locations_query(domain, query).count()
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
return JsonResponse(
{
'results': self.query(domain, query_context),
'total': self.query_count(domain, query_context)
}
)
|
from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
|
Use LocationChoiceProvider in enikshay location view
|
Use LocationChoiceProvider in enikshay location view
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
|
python
|
## Code Before:
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def _locations_query(self, domain, query_text):
if query_text:
return SQLLocation.active_objects.filter_path_by_user_input(
domain=domain, user_input=query_text)
else:
return SQLLocation.active_objects.filter(domain=domain)
def query(self, domain, query_context):
locations = self._locations_query(domain, query_context.query).order_by('name')
return [
{'id': loc.location_id, 'text': loc.display_name}
for loc in locations[query_context.offset:query_context.offset + query_context.limit]
]
def query_count(self, domain, query):
return self._locations_query(domain, query).count()
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
return JsonResponse(
{
'results': self.query(domain, query_context),
'total': self.query_count(domain, query_context)
}
)
## Instruction:
Use LocationChoiceProvider in enikshay location view
## Code After:
from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
|
# ... existing code ...
from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
# ... modified code ...
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
...
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
# ... rest of the code ...
|
df11143226410708373de21b6645f7ecbc677604
|
Borsch/Borschv002/app/src/main/java/ua/uagames/borsch/v002/MainActivity.java
|
Borsch/Borschv002/app/src/main/java/ua/uagames/borsch/v002/MainActivity.java
|
package ua.uagames.borsch.v002;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
package ua.uagames.borsch.v002;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.firebase.analytics.FirebaseAnalytics;
public class MainActivity extends AppCompatActivity {
private WebView viewer;
private FirebaseAnalytics analytics;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
analytics = FirebaseAnalytics.getInstance(this);
bundle = new Bundle();
viewer = (WebView) findViewById(R.id.viewer);
viewer.getSettings().setJavaScriptEnabled(true);
viewer.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
viewer.loadUrl("https://drive.google.com/file/d/0B3qWNFQol8lILVlzQlJ3V3VHTTg/view?usp=sharing");
bundle.putString("app_name", "Borsch v002.");
bundle.putString("app_event", "Create app and load content.");
analytics.logEvent("app_statistics", bundle);
}
}
|
Change project Borschv002. Add app functional with firebase statistics.
|
Change project Borschv002. Add app functional with firebase statistics.
|
Java
|
mit
|
nevmaks/UAGames
|
java
|
## Code Before:
package ua.uagames.borsch.v002;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
## Instruction:
Change project Borschv002. Add app functional with firebase statistics.
## Code After:
package ua.uagames.borsch.v002;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.firebase.analytics.FirebaseAnalytics;
public class MainActivity extends AppCompatActivity {
private WebView viewer;
private FirebaseAnalytics analytics;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
analytics = FirebaseAnalytics.getInstance(this);
bundle = new Bundle();
viewer = (WebView) findViewById(R.id.viewer);
viewer.getSettings().setJavaScriptEnabled(true);
viewer.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
viewer.loadUrl("https://drive.google.com/file/d/0B3qWNFQol8lILVlzQlJ3V3VHTTg/view?usp=sharing");
bundle.putString("app_name", "Borsch v002.");
bundle.putString("app_event", "Create app and load content.");
analytics.logEvent("app_statistics", bundle);
}
}
|
// ... existing code ...
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.firebase.analytics.FirebaseAnalytics;
public class MainActivity extends AppCompatActivity {
private WebView viewer;
private FirebaseAnalytics analytics;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
analytics = FirebaseAnalytics.getInstance(this);
bundle = new Bundle();
viewer = (WebView) findViewById(R.id.viewer);
viewer.getSettings().setJavaScriptEnabled(true);
viewer.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
viewer.loadUrl("https://drive.google.com/file/d/0B3qWNFQol8lILVlzQlJ3V3VHTTg/view?usp=sharing");
bundle.putString("app_name", "Borsch v002.");
bundle.putString("app_event", "Create app and load content.");
analytics.logEvent("app_statistics", bundle);
}
}
// ... rest of the code ...
|
30dc46288b4f9c0ff2e9a549df583f814effbef7
|
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageInterruptionManager.java
|
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageInterruptionManager.java
|
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;
public class OStorageInterruptionManager {
private int depth = 0;
private boolean interrupted = false;
protected void interrupt(Thread thread) {
synchronized (this) {
if (depth <= 0) {
interrupted = true;
} else if (thread != null) {
thread.interrupt();
}
}
}
protected void enterCriticalPath() {
synchronized (this) {
if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
this.depth++;
}
}
protected void exitCriticalPath() {
synchronized (this) {
this.depth--;
if (interrupted && depth == 0) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
}
}
}
|
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;
public class OStorageInterruptionManager {
private int depth = 0;
private boolean interrupted = false;
protected void interrupt(Thread thread) {
synchronized (this) {
if (depth <= 0) {
interrupted = true;
} else if (thread != null) {
thread.interrupt();
}
}
}
public void enterCriticalPath() {
synchronized (this) {
if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
this.depth++;
}
}
public void exitCriticalPath() {
synchronized (this) {
this.depth--;
if (interrupted && depth == 0) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
}
}
}
|
Change visibility of storage interruption manager
|
Change visibility of storage interruption manager
|
Java
|
apache-2.0
|
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
|
java
|
## Code Before:
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;
public class OStorageInterruptionManager {
private int depth = 0;
private boolean interrupted = false;
protected void interrupt(Thread thread) {
synchronized (this) {
if (depth <= 0) {
interrupted = true;
} else if (thread != null) {
thread.interrupt();
}
}
}
protected void enterCriticalPath() {
synchronized (this) {
if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
this.depth++;
}
}
protected void exitCriticalPath() {
synchronized (this) {
this.depth--;
if (interrupted && depth == 0) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
}
}
}
## Instruction:
Change visibility of storage interruption manager
## Code After:
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;
public class OStorageInterruptionManager {
private int depth = 0;
private boolean interrupted = false;
protected void interrupt(Thread thread) {
synchronized (this) {
if (depth <= 0) {
interrupted = true;
} else if (thread != null) {
thread.interrupt();
}
}
}
public void enterCriticalPath() {
synchronized (this) {
if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
this.depth++;
}
}
public void exitCriticalPath() {
synchronized (this) {
this.depth--;
if (interrupted && depth == 0) {
final Thread thread = Thread.currentThread();
// thread.interrupt();
OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread);
throw new OInterruptedException("Command interrupted");
}
}
}
}
|
// ... existing code ...
}
}
public void enterCriticalPath() {
synchronized (this) {
if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
final Thread thread = Thread.currentThread();
// ... modified code ...
}
}
public void exitCriticalPath() {
synchronized (this) {
this.depth--;
if (interrupted && depth == 0) {
// ... rest of the code ...
|
8b538c452242050e468b71ca937e3d4feb57887b
|
mopidy/backends/stream/__init__.py
|
mopidy/backends/stream/__init__.py
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
__doc__ = """A backend for playing music for streaming music.
This backend will handle streaming of URIs in
:attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are
installed.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Stream+backend
**Dependencies:**
- None
**Settings:**
- :attr:`mopidy.settings.STREAM_PROTOCOLS`
"""
class Extension(ext.Extension):
name = 'Mopidy-Stream'
version = mopidy.__version__
def get_default_config(self):
return '[ext.stream]'
def validate_config(self, config):
pass
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import StreamBackend
return [StreamBackend]
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.stream]
# If the stream extension should be enabled or not
enabled = true
# Whitelist of URI schemas to support streaming from
protocols =
http
https
mms
rtmp
rtmps
rtsp
"""
__doc__ = """A backend for playing music for streaming music.
This backend will handle streaming of URIs in
:attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are
installed.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Stream+backend
**Dependencies:**
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Stream'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['protocols'] = config.List()
return schema
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import StreamBackend
return [StreamBackend]
|
Add default config and config schema
|
stream: Add default config and config schema
|
Python
|
apache-2.0
|
tkem/mopidy,jcass77/mopidy,jmarsik/mopidy,ZenithDK/mopidy,swak/mopidy,vrs01/mopidy,diandiankan/mopidy,quartz55/mopidy,adamcik/mopidy,abarisain/mopidy,liamw9534/mopidy,vrs01/mopidy,tkem/mopidy,dbrgn/mopidy,liamw9534/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,abarisain/mopidy,glogiotatidis/mopidy,hkariti/mopidy,mopidy/mopidy,mokieyue/mopidy,mopidy/mopidy,vrs01/mopidy,ali/mopidy,ZenithDK/mopidy,tkem/mopidy,SuperStarPL/mopidy,hkariti/mopidy,ali/mopidy,glogiotatidis/mopidy,adamcik/mopidy,jmarsik/mopidy,kingosticks/mopidy,ZenithDK/mopidy,kingosticks/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,priestd09/mopidy,rawdlite/mopidy,bacontext/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,hkariti/mopidy,mopidy/mopidy,kingosticks/mopidy,diandiankan/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,priestd09/mopidy,ali/mopidy,bacontext/mopidy,bencevans/mopidy,jodal/mopidy,quartz55/mopidy,mokieyue/mopidy,jodal/mopidy,bencevans/mopidy,quartz55/mopidy,quartz55/mopidy,dbrgn/mopidy,mokieyue/mopidy,jmarsik/mopidy,rawdlite/mopidy,bencevans/mopidy,vrs01/mopidy,ZenithDK/mopidy,tkem/mopidy,dbrgn/mopidy,hkariti/mopidy,rawdlite/mopidy,priestd09/mopidy,woutervanwijk/mopidy,jmarsik/mopidy,SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,jodal/mopidy,swak/mopidy,jcass77/mopidy,pacificIT/mopidy,adamcik/mopidy,bencevans/mopidy,ali/mopidy,bacontext/mopidy,swak/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,pacificIT/mopidy,jcass77/mopidy,woutervanwijk/mopidy
|
python
|
## Code Before:
from __future__ import unicode_literals
import mopidy
from mopidy import ext
__doc__ = """A backend for playing music for streaming music.
This backend will handle streaming of URIs in
:attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are
installed.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Stream+backend
**Dependencies:**
- None
**Settings:**
- :attr:`mopidy.settings.STREAM_PROTOCOLS`
"""
class Extension(ext.Extension):
name = 'Mopidy-Stream'
version = mopidy.__version__
def get_default_config(self):
return '[ext.stream]'
def validate_config(self, config):
pass
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import StreamBackend
return [StreamBackend]
## Instruction:
stream: Add default config and config schema
## Code After:
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.stream]
# If the stream extension should be enabled or not
enabled = true
# Whitelist of URI schemas to support streaming from
protocols =
http
https
mms
rtmp
rtmps
rtsp
"""
__doc__ = """A backend for playing music for streaming music.
This backend will handle streaming of URIs in
:attr:`mopidy.settings.STREAM_PROTOCOLS` assuming the right plugins are
installed.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Stream+backend
**Dependencies:**
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Stream'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['protocols'] = config.List()
return schema
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import StreamBackend
return [StreamBackend]
|
...
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.stream]
# If the stream extension should be enabled or not
enabled = true
# Whitelist of URI schemas to support streaming from
protocols =
http
https
mms
rtmp
rtmps
rtsp
"""
__doc__ = """A backend for playing music for streaming music.
...
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
...
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['protocols'] = config.List()
return schema
def validate_environment(self):
pass
...
|
934cc5692c31111dc787b31cbf369be2017ec1c3
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="[email protected]",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
|
from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="[email protected]",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle',
'responses'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
|
Fix failing build: added getsentry/responses as installation requirement
|
Fix failing build: added getsentry/responses as installation requirement
|
Python
|
apache-2.0
|
cqse/teamscale-client-python
|
python
|
## Code Before:
from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="[email protected]",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
## Instruction:
Fix failing build: added getsentry/responses as installation requirement
## Code After:
from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="[email protected]",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle',
'responses'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
|
// ... existing code ...
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle',
'responses'
],
tests_require=[
// ... rest of the code ...
|
e0607c27cf990f893d837af5717de684bb62aa63
|
plugins/spark/__init__.py
|
plugins/spark/__init__.py
|
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
def pyspark_run_cleanup(event):
if SC_KEY in event.info['kwargs']:
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
|
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
info['cleanup_spark'] = True
def pyspark_run_cleanup(event):
if event.info.get('cleanup_spark'):
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
|
Fix spark mode (faulty shutdown conditional logic)
|
Fix spark mode (faulty shutdown conditional logic)
|
Python
|
apache-2.0
|
Kitware/romanesco,girder/girder_worker,girder/girder_worker,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,Kitware/romanesco
|
python
|
## Code Before:
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
def pyspark_run_cleanup(event):
if SC_KEY in event.info['kwargs']:
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
## Instruction:
Fix spark mode (faulty shutdown conditional logic)
## Code After:
import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.info
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
info['cleanup_spark'] = True
def pyspark_run_cleanup(event):
if event.info.get('cleanup_spark'):
event.info['kwargs'][SC_KEY].stop()
def load(params):
# If we have a spark config section then try to setup spark environment
if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ:
spark.setup_spark_env()
romanesco.register_executor('spark.python', pyspark_executor.run)
romanesco.events.bind('run.before', 'spark', setup_pyspark_task)
romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
|
...
if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']:
spark_conf = info['task'].get('spark_conf', {})
info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf)
info['cleanup_spark'] = True
def pyspark_run_cleanup(event):
if event.info.get('cleanup_spark'):
event.info['kwargs'][SC_KEY].stop()
...
|
8c35b0d9863ac44786b952b69f103cb6163014de
|
src/main/java/fr/insee/pogues/webservice/rest/GenericExceptionMapper.java
|
src/main/java/fr/insee/pogues/webservice/rest/GenericExceptionMapper.java
|
package fr.insee.pogues.webservice.rest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private final Status STATUS = Status.INTERNAL_SERVER_ERROR;
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
package fr.insee.pogues.webservice.rest;
import org.apache.log4j.Logger;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private Status STATUS = Status.INTERNAL_SERVER_ERROR;
private Logger logger = Logger.getLogger(GenericExceptionMapper.class);
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
if(error instanceof NotFoundException) {
STATUS = Status.NOT_FOUND;
message.setMessage("Not Found");
message.setDetails("No JAX-RS resource found for this path");
}
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
Make exception mapper more accurate on jax-rs internal error
|
Make exception mapper more accurate on jax-rs internal error
|
Java
|
mit
|
InseeFr/Pogues-Back-Office,InseeFr/Pogues-Back-Office
|
java
|
## Code Before:
package fr.insee.pogues.webservice.rest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private final Status STATUS = Status.INTERNAL_SERVER_ERROR;
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
## Instruction:
Make exception mapper more accurate on jax-rs internal error
## Code After:
package fr.insee.pogues.webservice.rest;
import org.apache.log4j.Logger;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
/**
* Created by acordier on 04/07/17.
*/
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private Status STATUS = Status.INTERNAL_SERVER_ERROR;
private Logger logger = Logger.getLogger(GenericExceptionMapper.class);
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
if(error instanceof NotFoundException) {
STATUS = Status.NOT_FOUND;
message.setMessage("Not Found");
message.setDetails("No JAX-RS resource found for this path");
}
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
|
# ... existing code ...
package fr.insee.pogues.webservice.rest;
import org.apache.log4j.Logger;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
# ... modified code ...
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
private Status STATUS = Status.INTERNAL_SERVER_ERROR;
private Logger logger = Logger.getLogger(GenericExceptionMapper.class);
public Response toResponse(Throwable error){
RestMessage message = new RestMessage(
STATUS.getStatusCode(),
"An unexpected error occured", error.getMessage());
if(error instanceof NotFoundException) {
STATUS = Status.NOT_FOUND;
message.setMessage("Not Found");
message.setDetails("No JAX-RS resource found for this path");
}
return Response.status(STATUS)
.entity(message)
.type(MediaType.APPLICATION_JSON)
# ... rest of the code ...
|
c6d0cfe468166363450c61e479d6443bd3986d13
|
src/test/resources/CompileTwice.java
|
src/test/resources/CompileTwice.java
|
public class CompileTwice {
public String message() {
return "Hi again!";
}
}
|
import java.util.Collections;
import java.util.List;
public class CompileTwice {
public List<String> message() {
return Collections.singletonList("Hi again!");
}
}
|
Verify imports work when compiling incrementally
|
Verify imports work when compiling incrementally
|
Java
|
mit
|
georgewfraser/vscode-javac,georgewfraser/vscode-javac,georgewfraser/vscode-javac
|
java
|
## Code Before:
public class CompileTwice {
public String message() {
return "Hi again!";
}
}
## Instruction:
Verify imports work when compiling incrementally
## Code After:
import java.util.Collections;
import java.util.List;
public class CompileTwice {
public List<String> message() {
return Collections.singletonList("Hi again!");
}
}
|
...
import java.util.Collections;
import java.util.List;
public class CompileTwice {
public List<String> message() {
return Collections.singletonList("Hi again!");
}
}
...
|
cdfdfd7418f33cc38aa7db3e42e0050d4189ab77
|
webserver/utility/templatetags/active_tags.py
|
webserver/utility/templatetags/active_tags.py
|
import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
|
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
Update active templatetag to accept more complex strings
|
Update active templatetag to accept more complex strings
|
Python
|
bsd-3-clause
|
siggame/webserver,siggame/webserver,siggame/webserver
|
python
|
## Code Before:
import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
## Instruction:
Update active templatetag to accept more complex strings
## Code After:
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
...
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
...
|
fbad1649e9939a3be4194e0d508ff5889f48bb6f
|
unleash/plugins/utils_assign.py
|
unleash/plugins/utils_assign.py
|
import re
# regular expression for finding assignments
_quotes = "['|\"|\"\"\"]"
BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\
_quotes + r')'
def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise ValueError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise ValueError('No version assignment ("{}") found.'.format(varname))
return ASSIGN_RE.search(data).group(2)
def replace_assign(data, varname, new_value):
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
def repl(m):
return m.group(1) + new_value + m.group(3)
return ASSIGN_RE.sub(repl, data)
|
from unleash.exc import PluginError
import re
# regular expression for finding assignments
_quotes = "['|\"|\"\"\"]"
BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\
_quotes + r')'
def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise PluginError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise PluginError('No version assignment ("{}") found.'
.format(varname))
return ASSIGN_RE.search(data).group(2)
def replace_assign(data, varname, new_value):
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
def repl(m):
return m.group(1) + new_value + m.group(3)
return ASSIGN_RE.sub(repl, data)
|
Raise PluginErrors instead of ValueErrors in versions.
|
Raise PluginErrors instead of ValueErrors in versions.
|
Python
|
mit
|
mbr/unleash
|
python
|
## Code Before:
import re
# regular expression for finding assignments
_quotes = "['|\"|\"\"\"]"
BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\
_quotes + r')'
def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise ValueError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise ValueError('No version assignment ("{}") found.'.format(varname))
return ASSIGN_RE.search(data).group(2)
def replace_assign(data, varname, new_value):
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
def repl(m):
return m.group(1) + new_value + m.group(3)
return ASSIGN_RE.sub(repl, data)
## Instruction:
Raise PluginErrors instead of ValueErrors in versions.
## Code After:
from unleash.exc import PluginError
import re
# regular expression for finding assignments
_quotes = "['|\"|\"\"\"]"
BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\
_quotes + r')'
def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise PluginError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise PluginError('No version assignment ("{}") found.'
.format(varname))
return ASSIGN_RE.search(data).group(2)
def replace_assign(data, varname, new_value):
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
def repl(m):
return m.group(1) + new_value + m.group(3)
return ASSIGN_RE.sub(repl, data)
|
...
from unleash.exc import PluginError
import re
...
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_RE.findall(data)) > 1:
raise PluginError('Found multiple {}-strings.'.format(varname))
if len(ASSIGN_RE.findall(data)) < 1:
raise PluginError('No version assignment ("{}") found.'
.format(varname))
return ASSIGN_RE.search(data).group(2)
...
|
08fe9e7beb4285feec9205012a62d464b3489bcf
|
natasha/grammars/person/interpretation.py
|
natasha/grammars/person/interpretation.py
|
from enum import Enum
from collections import Counter
from yargy.interpretation import InterpretationObject
class PersonObject(InterpretationObject):
class Attributes(Enum):
Firstname = 0 # владимир
Middlename = 1 # владимирович
Lastname = 2 # путин
Descriptor = 3 # президент
DescriptorDestination = 4 # российской федерации
@property
def gender(self):
'''
Very simple gender prediction algorithm
'''
counter = Counter()
for field, token in self.__dict__.items():
if not token:
continue
for form in token.forms:
grammemes = set()
if ('Ms-f' in form['grammemes']) or ('Fixd' in form['grammemes']):
continue
elif 'femn' in form['grammemes']:
grammemes |= {'femn'}
elif 'masc' in form['grammemes']:
grammemes |= {'masc'}
counter.update(grammemes)
return counter
|
from __future__ import unicode_literals
from enum import Enum
from collections import Counter
from yargy.interpretation import InterpretationObject
class PersonObject(InterpretationObject):
class Attributes(Enum):
Firstname = 0 # владимир
Middlename = 1 # владимирович
Lastname = 2 # путин
Descriptor = 3 # президент
DescriptorDestination = 4 # российской федерации
@property
def gender(self):
'''
Very simple gender prediction algorithm
'''
counter = Counter()
for field, token in self.__dict__.items():
if not token:
continue
for form in token.forms:
grammemes = set()
if ('Ms-f' in form['grammemes']) or ('Fixd' in form['grammemes']):
continue
elif 'femn' in form['grammemes']:
grammemes |= {'femn'}
elif 'masc' in form['grammemes']:
grammemes |= {'masc'}
counter.update(grammemes)
return counter
|
Fix encoding for python 2.x
|
Fix encoding for python 2.x
|
Python
|
mit
|
natasha/natasha
|
python
|
## Code Before:
from enum import Enum
from collections import Counter
from yargy.interpretation import InterpretationObject
class PersonObject(InterpretationObject):
class Attributes(Enum):
Firstname = 0 # владимир
Middlename = 1 # владимирович
Lastname = 2 # путин
Descriptor = 3 # президент
DescriptorDestination = 4 # российской федерации
@property
def gender(self):
'''
Very simple gender prediction algorithm
'''
counter = Counter()
for field, token in self.__dict__.items():
if not token:
continue
for form in token.forms:
grammemes = set()
if ('Ms-f' in form['grammemes']) or ('Fixd' in form['grammemes']):
continue
elif 'femn' in form['grammemes']:
grammemes |= {'femn'}
elif 'masc' in form['grammemes']:
grammemes |= {'masc'}
counter.update(grammemes)
return counter
## Instruction:
Fix encoding for python 2.x
## Code After:
from __future__ import unicode_literals
from enum import Enum
from collections import Counter
from yargy.interpretation import InterpretationObject
class PersonObject(InterpretationObject):
class Attributes(Enum):
Firstname = 0 # владимир
Middlename = 1 # владимирович
Lastname = 2 # путин
Descriptor = 3 # президент
DescriptorDestination = 4 # российской федерации
@property
def gender(self):
'''
Very simple gender prediction algorithm
'''
counter = Counter()
for field, token in self.__dict__.items():
if not token:
continue
for form in token.forms:
grammemes = set()
if ('Ms-f' in form['grammemes']) or ('Fixd' in form['grammemes']):
continue
elif 'femn' in form['grammemes']:
grammemes |= {'femn'}
elif 'masc' in form['grammemes']:
grammemes |= {'masc'}
counter.update(grammemes)
return counter
|
...
from __future__ import unicode_literals
from enum import Enum
from collections import Counter
from yargy.interpretation import InterpretationObject
...
|
fd697a0a4a4aeb3455ec7b7e8b3ed38ce0eb4502
|
test/sockettest.py
|
test/sockettest.py
|
import kaa
@kaa.coroutine()
def new_client(client):
ip, port = client.address
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = tls.TLSSocket()
#remote = kaa.Socket()
yield remote.connect('www.freevo.org:80')
#yield remote.connect('urandom.ca:443')
#try:
# yield remote.starttls_client()
#except:
# print "TLS ERROR"
# return
remote.write('GET / HTTP/1.0\n\n')
while remote.connected:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
from kaa.net import tls
#server = tls.TLSSocket()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
|
import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = TLSSocket()
yield remote.connect('www.google.com:443')
yield remote.starttls_client()
yield remote.write('GET / HTTP/1.0\n\n')
while remote.readable:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
|
Fix TLS support in socket test
|
Fix TLS support in socket test
|
Python
|
lgpl-2.1
|
freevo/kaa-base,freevo/kaa-base
|
python
|
## Code Before:
import kaa
@kaa.coroutine()
def new_client(client):
ip, port = client.address
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = tls.TLSSocket()
#remote = kaa.Socket()
yield remote.connect('www.freevo.org:80')
#yield remote.connect('urandom.ca:443')
#try:
# yield remote.starttls_client()
#except:
# print "TLS ERROR"
# return
remote.write('GET / HTTP/1.0\n\n')
while remote.connected:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
from kaa.net import tls
#server = tls.TLSSocket()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
## Instruction:
Fix TLS support in socket test
## Code After:
import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = TLSSocket()
yield remote.connect('www.google.com:443')
yield remote.starttls_client()
yield remote.write('GET / HTTP/1.0\n\n')
while remote.readable:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
|
...
import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = TLSSocket()
yield remote.connect('www.google.com:443')
yield remote.starttls_client()
yield remote.write('GET / HTTP/1.0\n\n')
while remote.readable:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
...
|
53d6dd3fb9548b53f4d4fd40c7f3e0be40d8bd19
|
src/net/f4fs/util/RandomDevice.java
|
src/net/f4fs/util/RandomDevice.java
|
package net.f4fs.util;
import java.util.Random;
/**
* RandomDevice for global usage of pseudo-random numbers.
*
* Usage:
*
* RandomDevice.INSTANCE.nextLong
*
* Created by samuel on 31.03.15.
*/
public enum RandomDevice {
// To provide reproducible outcomes.
INSTANCE(new Random(4568321548855l));
private Random rand;
private RandomDevice(Random rand) {
this.rand = rand;
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized int nextInt(int n) {
return rand.nextInt(n);
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized long nextLong(long n) {
return rand.nextLong();
}
public Random getRand() {
return rand;
}
}
|
package net.f4fs.util;
import java.util.Random;
/**
* RandomDevice for global usage of pseudo-random numbers.
*
* Usage:
*
* RandomDevice.INSTANCE.nextLong
*
* Created by samuel on 31.03.15.
*/
public enum RandomDevice {
// To provide reproducible outcomes.
INSTANCE(new Random(System.currentTimeMillis()));
private Random rand;
private RandomDevice(Random rand) {
this.rand = rand;
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized int nextInt(int n) {
return rand.nextInt(n);
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized long nextLong(long n) {
return rand.nextLong();
}
public Random getRand() {
return rand;
}
}
|
Fix random instanciation with milliseconds as seeds
|
Fix random instanciation with milliseconds as seeds
|
Java
|
apache-2.0
|
rmatil/p2pfs,rmatil/p2pfs
|
java
|
## Code Before:
package net.f4fs.util;
import java.util.Random;
/**
* RandomDevice for global usage of pseudo-random numbers.
*
* Usage:
*
* RandomDevice.INSTANCE.nextLong
*
* Created by samuel on 31.03.15.
*/
public enum RandomDevice {
// To provide reproducible outcomes.
INSTANCE(new Random(4568321548855l));
private Random rand;
private RandomDevice(Random rand) {
this.rand = rand;
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized int nextInt(int n) {
return rand.nextInt(n);
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized long nextLong(long n) {
return rand.nextLong();
}
public Random getRand() {
return rand;
}
}
## Instruction:
Fix random instanciation with milliseconds as seeds
## Code After:
package net.f4fs.util;
import java.util.Random;
/**
* RandomDevice for global usage of pseudo-random numbers.
*
* Usage:
*
* RandomDevice.INSTANCE.nextLong
*
* Created by samuel on 31.03.15.
*/
public enum RandomDevice {
// To provide reproducible outcomes.
INSTANCE(new Random(System.currentTimeMillis()));
private Random rand;
private RandomDevice(Random rand) {
this.rand = rand;
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized int nextInt(int n) {
return rand.nextInt(n);
}
/**
* Returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
* and the specified value (exclusive), drawn from this random number generator's sequence.
*
* @param n Bound
* @return 0 <= value < n
*/
public synchronized long nextLong(long n) {
return rand.nextLong();
}
public Random getRand() {
return rand;
}
}
|
# ... existing code ...
*/
public enum RandomDevice {
// To provide reproducible outcomes.
INSTANCE(new Random(System.currentTimeMillis()));
private Random rand;
# ... rest of the code ...
|
bf042cbe47c9fcfc0e608ff726a73d0e562027d0
|
tests/test_with_hypothesis.py
|
tests/test_with_hypothesis.py
|
import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(bytes, bytes)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct, associated_data)
|
import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(
hypothesis.strategies.binary(),
hypothesis.strategies.binary()
)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct, associated_data)
|
Fix the Hypothesis test to work with new API.
|
Fix the Hypothesis test to work with new API.
The Hypothesis API has since moved on from the last time we pushed
a change. Fix the test suite to work with the new API.
|
Python
|
apache-2.0
|
Ayrx/python-aead,Ayrx/python-aead
|
python
|
## Code Before:
import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(bytes, bytes)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct, associated_data)
## Instruction:
Fix the Hypothesis test to work with new API.
The Hypothesis API has since moved on from the last time we pushed
a change. Fix the test suite to work with the new API.
## Code After:
import pytest
from aead import AEAD
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(
hypothesis.strategies.binary(),
hypothesis.strategies.binary()
)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct, associated_data)
|
# ... existing code ...
hypothesis = pytest.importorskip("hypothesis")
@hypothesis.given(
hypothesis.strategies.binary(),
hypothesis.strategies.binary()
)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
# ... rest of the code ...
|
9da01f39c8d9b73025d85be72b71399b6930b6fb
|
src/encoded/cache.py
|
src/encoded/cache.py
|
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return
cached = cache.get(key)
if cached is not None:
return cached[1]
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
|
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return default
try:
return cache[key]
except KeyError:
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
|
Use LRUCache correctly (minimal improvement)
|
Use LRUCache correctly (minimal improvement)
|
Python
|
mit
|
ENCODE-DCC/encoded,kidaa/encoded,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,4dn-dcic/fourfront,ClinGen/clincoded,ClinGen/clincoded,4dn-dcic/fourfront,ENCODE-DCC/snovault,4dn-dcic/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,4dn-dcic/fourfront,philiptzou/clincoded,kidaa/encoded,hms-dbmi/fourfront,ENCODE-DCC/snovault,ENCODE-DCC/encoded,kidaa/encoded,ENCODE-DCC/encoded,hms-dbmi/fourfront,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,hms-dbmi/fourfront,ClinGen/clincoded,kidaa/encoded,kidaa/encoded,ClinGen/clincoded,ClinGen/clincoded,T2DREAM/t2dream-portal,philiptzou/clincoded,philiptzou/clincoded
|
python
|
## Code Before:
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return
cached = cache.get(key)
if cached is not None:
return cached[1]
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
## Instruction:
Use LRUCache correctly (minimal improvement)
## Code After:
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return default
try:
return cache[key]
except KeyError:
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
|
...
def get(self, key, default=None):
cache = self.cache
if cache is None:
return default
try:
return cache[key]
except KeyError:
return default
def __contains__(self, key):
cache = self.cache
...
|
b0b4bad0ca68ebd1927229e85e7116fb63126c65
|
src/olympia/zadmin/helpers.py
|
src/olympia/zadmin/helpers.py
|
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
|
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
|
Remove generate error page from admin site
|
Remove generate error page from admin site
|
Python
|
bsd-3-clause
|
bqbn/addons-server,wagnerand/olympia,harry-7/addons-server,wagnerand/addons-server,harikishen/addons-server,psiinon/addons-server,lavish205/olympia,mstriemer/addons-server,kumar303/addons-server,Prashant-Surya/addons-server,mstriemer/olympia,mozilla/addons-server,harikishen/addons-server,Revanth47/addons-server,mstriemer/addons-server,mstriemer/olympia,lavish205/olympia,lavish205/olympia,wagnerand/olympia,diox/olympia,eviljeff/olympia,aviarypl/mozilla-l10n-addons-server,mozilla/olympia,tsl143/addons-server,Revanth47/addons-server,wagnerand/addons-server,psiinon/addons-server,eviljeff/olympia,wagnerand/addons-server,harry-7/addons-server,kumar303/addons-server,wagnerand/olympia,eviljeff/olympia,Prashant-Surya/addons-server,bqbn/addons-server,kumar303/addons-server,Revanth47/addons-server,kumar303/olympia,harry-7/addons-server,kumar303/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/addons-server,mstriemer/addons-server,harikishen/addons-server,mstriemer/olympia,Prashant-Surya/addons-server,mozilla/olympia,diox/olympia,psiinon/addons-server,harry-7/addons-server,wagnerand/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/olympia,mstriemer/olympia,mozilla/addons-server,bqbn/addons-server,Revanth47/addons-server,mstriemer/addons-server,diox/olympia,harikishen/addons-server,wagnerand/addons-server,diox/olympia,atiqueahmedziad/addons-server,psiinon/addons-server,eviljeff/olympia,tsl143/addons-server,mozilla/olympia,kumar303/olympia,lavish205/olympia,atiqueahmedziad/addons-server,tsl143/addons-server,tsl143/addons-server,mozilla/addons-server,mozilla/olympia,bqbn/addons-server,aviarypl/mozilla-l10n-addons-server,Prashant-Surya/addons-server,atiqueahmedziad/addons-server,mozilla/addons-server,atiqueahmedziad/addons-server
|
python
|
## Code Before:
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
## Instruction:
Remove generate error page from admin site
## Code After:
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
|
# ... existing code ...
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
# ... rest of the code ...
|
d9fc2cfdcfaf13f2e8491ace60680f3c94ad5c83
|
tests/test_async.py
|
tests/test_async.py
|
try:
import asyncio
loop = asyncio.get_event_loop()
except ImportError:
asyncio = None
import pexpect
import unittest
@unittest.skipIf(asyncio is None, "Requires asyncio")
class AsyncTests(unittest.TestCase):
def test_simple_expect(self):
p = pexpect.spawn('cat')
p.sendline('Hello asyncio')
coro = p.expect('Hello', async=True)
task = asyncio.Task(coro)
results = []
def complete(task):
results.append(task.result())
task.add_done_callback(complete)
loop.run_until_complete(task)
assert results == [0]
|
try:
import asyncio
except ImportError:
asyncio = None
import pexpect
import unittest
def run(coro):
return asyncio.get_event_loop().run_until_complete(coro)
@unittest.skipIf(asyncio is None, "Requires asyncio")
class AsyncTests(unittest.TestCase):
def test_simple_expect(self):
p = pexpect.spawn('cat')
p.sendline('Hello asyncio')
coro = p.expect(['Hello', pexpect.EOF] , async=True)
assert run(coro) == 0
print('Done')
def test_timeout(self):
p = pexpect.spawn('cat')
coro = p.expect('foo', timeout=1, async=True)
with self.assertRaises(pexpect.TIMEOUT):
run(coro)
p = pexpect.spawn('cat')
coro = p.expect(['foo', pexpect.TIMEOUT], timeout=1, async=True)
assert run(coro) == 1
def test_eof(self):
p = pexpect.spawn('cat')
p.sendline('Hi')
coro = p.expect(pexpect.EOF, async=True)
p.sendeof()
assert run(coro) == 0
p = pexpect.spawn('cat')
p.sendeof()
coro = p.expect('Blah', async=True)
with self.assertRaises(pexpect.EOF):
run(coro)
|
Expand tests for async expect
|
Expand tests for async expect
|
Python
|
isc
|
dongguangming/pexpect,quatanium/pexpect,crdoconnor/pexpect,Depado/pexpect,crdoconnor/pexpect,dongguangming/pexpect,crdoconnor/pexpect,Wakeupbuddy/pexpect,nodish/pexpect,Wakeupbuddy/pexpect,blink1073/pexpect,nodish/pexpect,quatanium/pexpect,bangi123/pexpect,dongguangming/pexpect,bangi123/pexpect,quatanium/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,blink1073/pexpect,dongguangming/pexpect,Wakeupbuddy/pexpect,nodish/pexpect,Depado/pexpect,blink1073/pexpect,bangi123/pexpect,Depado/pexpect,bangi123/pexpect
|
python
|
## Code Before:
try:
import asyncio
loop = asyncio.get_event_loop()
except ImportError:
asyncio = None
import pexpect
import unittest
@unittest.skipIf(asyncio is None, "Requires asyncio")
class AsyncTests(unittest.TestCase):
def test_simple_expect(self):
p = pexpect.spawn('cat')
p.sendline('Hello asyncio')
coro = p.expect('Hello', async=True)
task = asyncio.Task(coro)
results = []
def complete(task):
results.append(task.result())
task.add_done_callback(complete)
loop.run_until_complete(task)
assert results == [0]
## Instruction:
Expand tests for async expect
## Code After:
try:
import asyncio
except ImportError:
asyncio = None
import pexpect
import unittest
def run(coro):
return asyncio.get_event_loop().run_until_complete(coro)
@unittest.skipIf(asyncio is None, "Requires asyncio")
class AsyncTests(unittest.TestCase):
def test_simple_expect(self):
p = pexpect.spawn('cat')
p.sendline('Hello asyncio')
coro = p.expect(['Hello', pexpect.EOF] , async=True)
assert run(coro) == 0
print('Done')
def test_timeout(self):
p = pexpect.spawn('cat')
coro = p.expect('foo', timeout=1, async=True)
with self.assertRaises(pexpect.TIMEOUT):
run(coro)
p = pexpect.spawn('cat')
coro = p.expect(['foo', pexpect.TIMEOUT], timeout=1, async=True)
assert run(coro) == 1
def test_eof(self):
p = pexpect.spawn('cat')
p.sendline('Hi')
coro = p.expect(pexpect.EOF, async=True)
p.sendeof()
assert run(coro) == 0
p = pexpect.spawn('cat')
p.sendeof()
coro = p.expect('Blah', async=True)
with self.assertRaises(pexpect.EOF):
run(coro)
|
...
try:
import asyncio
except ImportError:
asyncio = None
...
import pexpect
import unittest
def run(coro):
return asyncio.get_event_loop().run_until_complete(coro)
@unittest.skipIf(asyncio is None, "Requires asyncio")
class AsyncTests(unittest.TestCase):
def test_simple_expect(self):
p = pexpect.spawn('cat')
p.sendline('Hello asyncio')
coro = p.expect(['Hello', pexpect.EOF] , async=True)
assert run(coro) == 0
print('Done')
def test_timeout(self):
p = pexpect.spawn('cat')
coro = p.expect('foo', timeout=1, async=True)
with self.assertRaises(pexpect.TIMEOUT):
run(coro)
p = pexpect.spawn('cat')
coro = p.expect(['foo', pexpect.TIMEOUT], timeout=1, async=True)
assert run(coro) == 1
def test_eof(self):
p = pexpect.spawn('cat')
p.sendline('Hi')
coro = p.expect(pexpect.EOF, async=True)
p.sendeof()
assert run(coro) == 0
p = pexpect.spawn('cat')
p.sendeof()
coro = p.expect('Blah', async=True)
with self.assertRaises(pexpect.EOF):
run(coro)
...
|
fdaabeaa3694103153c81a18971e6b55597cd66e
|
Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Synth.py
|
Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Synth.py
|
import Axon
from Kamaelia.Apps.Jam.Audio.Polyphony import Polyphoniser
from Kamaelia.Apps.Jam.Audio.Mixer import MonoMixer
class Synth(Axon.Component.component):
polyphony = 8
polyphoniser = Polyphoniser
def __init__(self, voiceGenerator, **argd):
super(Synth, self).__init__(**argd)
polyphoniser = self.polyphoniser(**argd).activate()
mixer = MonoMixer(channels=self.polyphony, **argd).activate()
self.link((self, "inbox"), (polyphoniser, "inbox"), passthrough=1)
self.link((mixer, "outbox"), (self, "outbox"), passthrough=2)
for index, voice in enumerate(voiceGenerator()):
voice = voice.activate()
self.link((polyphoniser, "voice%i" % index), (voice, "inbox"))
self.link((voice, "outbox"), (mixer, "in%i" % index))
def main(self):
while 1:
if not self.anyReady():
self.pause()
yield 1
|
import Axon
from Kamaelia.Apps.Jam.Audio.Polyphony import Polyphoniser
class Synth(Axon.Component.component):
polyphony = 8
polyphoniser = Polyphoniser
def __init__(self, voiceGenerator, **argd):
super(Synth, self).__init__(**argd)
polyphoniser = self.polyphoniser(**argd).activate()
self.link((self, "inbox"), (polyphoniser, "inbox"), passthrough=1)
for index, voice in enumerate(voiceGenerator()):
voice = voice.activate()
self.link((polyphoniser, "voice%i" % index), (voice, "inbox"))
def main(self):
while 1:
if not self.anyReady():
self.pause()
yield 1
|
Remove mixer section from synth code to reflect the components directly calling pygame mixer methods.
|
Remove mixer section from synth code to reflect the components directly calling pygame mixer methods.
|
Python
|
apache-2.0
|
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
|
python
|
## Code Before:
import Axon
from Kamaelia.Apps.Jam.Audio.Polyphony import Polyphoniser
from Kamaelia.Apps.Jam.Audio.Mixer import MonoMixer
class Synth(Axon.Component.component):
polyphony = 8
polyphoniser = Polyphoniser
def __init__(self, voiceGenerator, **argd):
super(Synth, self).__init__(**argd)
polyphoniser = self.polyphoniser(**argd).activate()
mixer = MonoMixer(channels=self.polyphony, **argd).activate()
self.link((self, "inbox"), (polyphoniser, "inbox"), passthrough=1)
self.link((mixer, "outbox"), (self, "outbox"), passthrough=2)
for index, voice in enumerate(voiceGenerator()):
voice = voice.activate()
self.link((polyphoniser, "voice%i" % index), (voice, "inbox"))
self.link((voice, "outbox"), (mixer, "in%i" % index))
def main(self):
while 1:
if not self.anyReady():
self.pause()
yield 1
## Instruction:
Remove mixer section from synth code to reflect the components directly calling pygame mixer methods.
## Code After:
import Axon
from Kamaelia.Apps.Jam.Audio.Polyphony import Polyphoniser
class Synth(Axon.Component.component):
polyphony = 8
polyphoniser = Polyphoniser
def __init__(self, voiceGenerator, **argd):
super(Synth, self).__init__(**argd)
polyphoniser = self.polyphoniser(**argd).activate()
self.link((self, "inbox"), (polyphoniser, "inbox"), passthrough=1)
for index, voice in enumerate(voiceGenerator()):
voice = voice.activate()
self.link((polyphoniser, "voice%i" % index), (voice, "inbox"))
def main(self):
while 1:
if not self.anyReady():
self.pause()
yield 1
|
# ... existing code ...
import Axon
from Kamaelia.Apps.Jam.Audio.Polyphony import Polyphoniser
class Synth(Axon.Component.component):
polyphony = 8
# ... modified code ...
def __init__(self, voiceGenerator, **argd):
super(Synth, self).__init__(**argd)
polyphoniser = self.polyphoniser(**argd).activate()
self.link((self, "inbox"), (polyphoniser, "inbox"), passthrough=1)
for index, voice in enumerate(voiceGenerator()):
voice = voice.activate()
self.link((polyphoniser, "voice%i" % index), (voice, "inbox"))
def main(self):
while 1:
# ... rest of the code ...
|
4aba316df350b493e13a776d1a9f7cc88a5b861c
|
elements-demo/src/main/java/org/vaadin/elements/demo/AbstractElementsDemo.java
|
elements-demo/src/main/java/org/vaadin/elements/demo/AbstractElementsDemo.java
|
package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
|
package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
layout.setSpacing(true);
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
|
Add spacing after demo description
|
Add spacing after demo description
|
Java
|
apache-2.0
|
vaadin/serverside-elements,vaadin/serverside-elements,vaadin/elements,vaadin/elements
|
java
|
## Code Before:
package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
## Instruction:
Add spacing after demo description
## Code After:
package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
layout.setSpacing(true);
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
|
# ... existing code ...
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
layout.setSpacing(true);
setCompositionRoot(layout);
}
# ... rest of the code ...
|
e51087bf04f56ae79a8af8ae059a2dbe28fb1d74
|
src/oscar/core/decorators.py
|
src/oscar/core/decorators.py
|
try:
from types import ClassType
except ImportError:
# Python 3
CHECK_TYPES = (type,)
else:
# Python 2: new and old-style classes
CHECK_TYPES = (type, ClassType)
import warnings
def deprecated(obj):
if isinstance(obj, CHECK_TYPES):
return _deprecated_cls(cls=obj)
else:
return _deprecated_func(f=obj)
def _deprecated_func(f):
def _deprecated(*args, **kwargs):
message = "Method '%s' is deprecated and will be " \
"removed in the next major version of django-oscar" \
% f.__name__
warnings.warn(message, DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
return _deprecated
def _deprecated_cls(cls):
class Deprecated(cls):
def __init__(self, *args, **kwargs):
message = "Class '%s' is deprecated and will be " \
"removed in the next major version of django-oscar" \
% cls.__name__
warnings.warn(message, DeprecationWarning, stacklevel=2)
super(Deprecated, self).__init__(*args, **kwargs)
return Deprecated
|
try:
from types import ClassType
except ImportError:
# Python 3
CHECK_TYPES = (type,)
else:
# Python 2: new and old-style classes
CHECK_TYPES = (type, ClassType)
import warnings
from oscar.utils.deprecation import RemovedInOscar15Warning
def deprecated(obj):
if isinstance(obj, CHECK_TYPES):
return _deprecated_cls(cls=obj)
else:
return _deprecated_func(f=obj)
def _deprecated_func(f):
def _deprecated(*args, **kwargs):
message = (
"Method '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (f.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
return f(*args, **kwargs)
return _deprecated
def _deprecated_cls(cls):
class Deprecated(cls):
def __init__(self, *args, **kwargs):
message = (
"Class '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (cls.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
super(Deprecated, self).__init__(*args, **kwargs)
return Deprecated
|
Set RemovedInOscar15Warning for existing deprecation warnings
|
Set RemovedInOscar15Warning for existing deprecation warnings
|
Python
|
bsd-3-clause
|
solarissmoke/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar
|
python
|
## Code Before:
try:
from types import ClassType
except ImportError:
# Python 3
CHECK_TYPES = (type,)
else:
# Python 2: new and old-style classes
CHECK_TYPES = (type, ClassType)
import warnings
def deprecated(obj):
if isinstance(obj, CHECK_TYPES):
return _deprecated_cls(cls=obj)
else:
return _deprecated_func(f=obj)
def _deprecated_func(f):
def _deprecated(*args, **kwargs):
message = "Method '%s' is deprecated and will be " \
"removed in the next major version of django-oscar" \
% f.__name__
warnings.warn(message, DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
return _deprecated
def _deprecated_cls(cls):
class Deprecated(cls):
def __init__(self, *args, **kwargs):
message = "Class '%s' is deprecated and will be " \
"removed in the next major version of django-oscar" \
% cls.__name__
warnings.warn(message, DeprecationWarning, stacklevel=2)
super(Deprecated, self).__init__(*args, **kwargs)
return Deprecated
## Instruction:
Set RemovedInOscar15Warning for existing deprecation warnings
## Code After:
try:
from types import ClassType
except ImportError:
# Python 3
CHECK_TYPES = (type,)
else:
# Python 2: new and old-style classes
CHECK_TYPES = (type, ClassType)
import warnings
from oscar.utils.deprecation import RemovedInOscar15Warning
def deprecated(obj):
if isinstance(obj, CHECK_TYPES):
return _deprecated_cls(cls=obj)
else:
return _deprecated_func(f=obj)
def _deprecated_func(f):
def _deprecated(*args, **kwargs):
message = (
"Method '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (f.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
return f(*args, **kwargs)
return _deprecated
def _deprecated_cls(cls):
class Deprecated(cls):
def __init__(self, *args, **kwargs):
message = (
"Class '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (cls.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
super(Deprecated, self).__init__(*args, **kwargs)
return Deprecated
|
// ... existing code ...
# Python 2: new and old-style classes
CHECK_TYPES = (type, ClassType)
import warnings
from oscar.utils.deprecation import RemovedInOscar15Warning
def deprecated(obj):
// ... modified code ...
def _deprecated_func(f):
def _deprecated(*args, **kwargs):
message = (
"Method '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (f.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
return f(*args, **kwargs)
return _deprecated
...
def _deprecated_cls(cls):
class Deprecated(cls):
def __init__(self, *args, **kwargs):
message = (
"Class '%s' is deprecated and will be " +
"removed in Oscar 1.5"
) % (cls.__name__)
warnings.warn(message, RemovedInOscar15Warning, stacklevel=2)
super(Deprecated, self).__init__(*args, **kwargs)
return Deprecated
// ... rest of the code ...
|
ad97fa93ad50bfb73c29798f9f1f24465c6a3683
|
_lua_paths.py
|
_lua_paths.py
|
import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
return []
paths=[]
if "folders" in project_data:
folders=project_data["folders"]
for f in folders:
if "path" in f and os.path.isabs(f["path"]):
paths.append(f["path"])
return paths
def __getViewPath(view):
searchpath=__commonprefix(view.window().folders())
for root, dirs, files in os.walk(searchpath):
for name in files:
if "main.lua"==name:
return root
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
paths.append(__getViewPath(view))
for path in paths:
for root, dirs, files in os.walk(path,followlinks=followlinks):
for name in files:
if ".lua" in name:
name=os.path.splitext(name)[0]
relpath=os.path.relpath(os.path.join(root, name),start=path)
luaPaths.append((name,_findBackslash.sub(".",relpath)))
return luaPaths
|
import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
return []
paths=[]
if "folders" in project_data:
folders=project_data["folders"]
for f in folders:
if "path" in f and os.path.isabs(f["path"]):
paths.append(f["path"])
return paths
def __getViewPath(view):
searchpath=__commonprefix(view.window().folders())
for root, dirs, files in os.walk(searchpath):
for name in files:
if "main.lua"==name:
return root
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
viewPath=__getViewPath(view)
if viewPath is not None:
paths.append(viewPath)
for path in paths:
for root, dirs, files in os.walk(path,followlinks=followlinks):
for name in files:
if ".lua" in name:
name=os.path.splitext(name)[0]
relpath=os.path.relpath(os.path.join(root, name),start=path)
luaPaths.append((name,_findBackslash.sub(".",relpath)))
return luaPaths
|
Fix crash if view returns no valid path
|
Fix crash if view returns no valid path
|
Python
|
mit
|
coronalabs/CoronaSDK-SublimeText,coronalabs/CoronaSDK-SublimeText
|
python
|
## Code Before:
import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
return []
paths=[]
if "folders" in project_data:
folders=project_data["folders"]
for f in folders:
if "path" in f and os.path.isabs(f["path"]):
paths.append(f["path"])
return paths
def __getViewPath(view):
searchpath=__commonprefix(view.window().folders())
for root, dirs, files in os.walk(searchpath):
for name in files:
if "main.lua"==name:
return root
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
paths.append(__getViewPath(view))
for path in paths:
for root, dirs, files in os.walk(path,followlinks=followlinks):
for name in files:
if ".lua" in name:
name=os.path.splitext(name)[0]
relpath=os.path.relpath(os.path.join(root, name),start=path)
luaPaths.append((name,_findBackslash.sub(".",relpath)))
return luaPaths
## Instruction:
Fix crash if view returns no valid path
## Code After:
import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
return []
paths=[]
if "folders" in project_data:
folders=project_data["folders"]
for f in folders:
if "path" in f and os.path.isabs(f["path"]):
paths.append(f["path"])
return paths
def __getViewPath(view):
searchpath=__commonprefix(view.window().folders())
for root, dirs, files in os.walk(searchpath):
for name in files:
if "main.lua"==name:
return root
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
viewPath=__getViewPath(view)
if viewPath is not None:
paths.append(viewPath)
for path in paths:
for root, dirs, files in os.walk(path,followlinks=followlinks):
for name in files:
if ".lua" in name:
name=os.path.splitext(name)[0]
relpath=os.path.relpath(os.path.join(root, name),start=path)
luaPaths.append((name,_findBackslash.sub(".",relpath)))
return luaPaths
|
// ... existing code ...
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
viewPath=__getViewPath(view)
if viewPath is not None:
paths.append(viewPath)
for path in paths:
for root, dirs, files in os.walk(path,followlinks=followlinks):
for name in files:
// ... rest of the code ...
|
afe792e50e6e30036f1ed718d7c3f5143a1e2da5
|
adhocracy4/follows/signals.py
|
adhocracy4/follows/signals.py
|
from django.conf import settings
from django.db.models.signals import post_save
from . import models
def autofollow_hook(instance, **kwargs):
if hasattr(instance.project, 'id'):
models.Follow.objects.get_or_create(
project=instance.project,
creator=instance.creator,
defaults={
'enabled': True,
})
for model in settings.A4_AUTO_FOLLOWABLES:
post_save.connect(autofollow_hook, model)
|
from django.apps import apps
from django.conf import settings
from django.db.models.signals import post_save
from . import models
def autofollow_hook(instance, **kwargs):
if hasattr(instance.project, 'id'):
models.Follow.objects.get_or_create(
project=instance.project,
creator=instance.creator,
defaults={
'enabled': True,
})
for app, model in settings.A4_AUTO_FOLLOWABLES:
post_save.connect(autofollow_hook, apps.get_model(app, model))
|
Fix setting up AUTO_FOLLOWABLES models
|
Fix setting up AUTO_FOLLOWABLES models
Note that `Signal.connect` expects the model class as the sender
argument.
Altough while using e.g. `post_save` it also works with a string
`"apname.model"`
|
Python
|
agpl-3.0
|
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
|
python
|
## Code Before:
from django.conf import settings
from django.db.models.signals import post_save
from . import models
def autofollow_hook(instance, **kwargs):
if hasattr(instance.project, 'id'):
models.Follow.objects.get_or_create(
project=instance.project,
creator=instance.creator,
defaults={
'enabled': True,
})
for model in settings.A4_AUTO_FOLLOWABLES:
post_save.connect(autofollow_hook, model)
## Instruction:
Fix setting up AUTO_FOLLOWABLES models
Note that `Signal.connect` expects the model class as the sender
argument.
Altough while using e.g. `post_save` it also works with a string
`"apname.model"`
## Code After:
from django.apps import apps
from django.conf import settings
from django.db.models.signals import post_save
from . import models
def autofollow_hook(instance, **kwargs):
if hasattr(instance.project, 'id'):
models.Follow.objects.get_or_create(
project=instance.project,
creator=instance.creator,
defaults={
'enabled': True,
})
for app, model in settings.A4_AUTO_FOLLOWABLES:
post_save.connect(autofollow_hook, apps.get_model(app, model))
|
# ... existing code ...
from django.apps import apps
from django.conf import settings
from django.db.models.signals import post_save
# ... modified code ...
})
for app, model in settings.A4_AUTO_FOLLOWABLES:
post_save.connect(autofollow_hook, apps.get_model(app, model))
# ... rest of the code ...
|
384822f44d0731f425698cc67115d179d8d13e4c
|
examples/mastery.py
|
examples/mastery.py
|
import cassiopeia as cass
from cassiopeia.core import Summoner
def test_cass():
name = "Kalturi"
masteries = cass.get_masteries()
for mastery in masteries:
print(mastery.name)
if __name__ == "__main__":
test_cass()
|
import cassiopeia as cass
def print_masteries():
for mastery in cass.get_masteries():
print(mastery.name)
if __name__ == "__main__":
print_masteries()
|
Remove redundant import, change function name.
|
Remove redundant import, change function name.
|
Python
|
mit
|
10se1ucgo/cassiopeia,meraki-analytics/cassiopeia,robrua/cassiopeia
|
python
|
## Code Before:
import cassiopeia as cass
from cassiopeia.core import Summoner
def test_cass():
name = "Kalturi"
masteries = cass.get_masteries()
for mastery in masteries:
print(mastery.name)
if __name__ == "__main__":
test_cass()
## Instruction:
Remove redundant import, change function name.
## Code After:
import cassiopeia as cass
def print_masteries():
for mastery in cass.get_masteries():
print(mastery.name)
if __name__ == "__main__":
print_masteries()
|
# ... existing code ...
import cassiopeia as cass
def print_masteries():
for mastery in cass.get_masteries():
print(mastery.name)
if __name__ == "__main__":
print_masteries()
# ... rest of the code ...
|
d9abb2f56720480169d394a2cadd3cb9a77ac4f6
|
app/main/views/frameworks.py
|
app/main/views/frameworks.py
|
from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_drafts': DraftService.query.filter(
DraftService.status == "not-submitted"
).count(),
'services_complete': DraftService.query.filter(
DraftService.status == "submitted"
).count(),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
|
from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_by_status': dict(db.session.query(
DraftService.status, func.count(DraftService.status)
).group_by(DraftService.status)),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
|
Use one query with group_by for service status
|
Use one query with group_by for service status
|
Python
|
mit
|
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
|
python
|
## Code Before:
from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_drafts': DraftService.query.filter(
DraftService.status == "not-submitted"
).count(),
'services_complete': DraftService.query.filter(
DraftService.status == "submitted"
).count(),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
## Instruction:
Use one query with group_by for service status
## Code After:
from flask import jsonify
from sqlalchemy.types import String
from sqlalchemy import func
import datetime
from .. import main
from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent
@main.route('/frameworks', methods=['GET'])
def list_frameworks():
frameworks = Framework.query.all()
return jsonify(
frameworks=[f.serialize() for f in frameworks]
)
@main.route('/frameworks/g-cloud-7/stats', methods=['GET'])
def get_framework_stats():
seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7)
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_by_status': dict(db.session.query(
DraftService.status, func.count(DraftService.status)
).group_by(DraftService.status)),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
'users': User.query.count(),
'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(),
'suppliers': Supplier.query.count(),
'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(),
'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count()
})
|
...
lot_column = DraftService.data['lot'].cast(String).label('lot')
return str({
'services_by_status': dict(db.session.query(
DraftService.status, func.count(DraftService.status)
).group_by(DraftService.status)),
'services_by_lot': dict(db.session.query(
lot_column, func.count(lot_column)
).group_by(lot_column).all()),
...
|
41c5040795c036bdc64a796f97e2618edda2c534
|
setup.py
|
setup.py
|
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
# also update in nsq/version.py
version = '0.6.5'
setup(
name='pynsq',
version=version,
description='official Python client library for NSQ',
keywords='python nsq',
author='Matt Reiferson',
author_email='[email protected]',
url='http://github.com/bitly/pynsq',
download_url='https://s3.amazonaws.com/bitly-downloads/nsq/pynsq-%s.tar.gz' % version,
packages=['nsq'],
requires=['tornado'],
include_package_data=True,
zip_safe=False,
tests_require=['pytest', 'mock', 'tornado'],
cmdclass={'test': PyTest},
classifiers=[
'License :: OSI Approved :: MIT License'
]
)
|
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
# also update in nsq/version.py
version = '0.6.5'
setup(
name='pynsq',
version=version,
description='official Python client library for NSQ',
keywords='python nsq',
author='Matt Reiferson',
author_email='[email protected]',
url='http://github.com/bitly/pynsq',
download_url=(
'https://s3.amazonaws.com/bitly-downloads/nsq/pynsq-%s.tar.gz' %
version
),
packages=['nsq'],
requires=['tornado'],
include_package_data=True,
zip_safe=False,
tests_require=['pytest', 'mock', 'tornado'],
cmdclass={'test': PyTest},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
]
)
|
Document Python 2.6, Python 2.7, CPython support. Document beta status.
|
Document Python 2.6, Python 2.7, CPython support. Document beta status.
|
Python
|
mit
|
bitly/pynsq,goller/pynsq,nsqio/pynsq,jonmorehouse/pynsq,protoss-player/pynsq,jehiah/pynsq,mreiferson/pynsq,protoss-player/pynsq,virtuald/pynsq,mreiferson/pynsq,bitly/pynsq,jonmorehouse/pynsq,virtuald/pynsq
|
python
|
## Code Before:
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
# also update in nsq/version.py
version = '0.6.5'
setup(
name='pynsq',
version=version,
description='official Python client library for NSQ',
keywords='python nsq',
author='Matt Reiferson',
author_email='[email protected]',
url='http://github.com/bitly/pynsq',
download_url='https://s3.amazonaws.com/bitly-downloads/nsq/pynsq-%s.tar.gz' % version,
packages=['nsq'],
requires=['tornado'],
include_package_data=True,
zip_safe=False,
tests_require=['pytest', 'mock', 'tornado'],
cmdclass={'test': PyTest},
classifiers=[
'License :: OSI Approved :: MIT License'
]
)
## Instruction:
Document Python 2.6, Python 2.7, CPython support. Document beta status.
## Code After:
from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
# also update in nsq/version.py
version = '0.6.5'
setup(
name='pynsq',
version=version,
description='official Python client library for NSQ',
keywords='python nsq',
author='Matt Reiferson',
author_email='[email protected]',
url='http://github.com/bitly/pynsq',
download_url=(
'https://s3.amazonaws.com/bitly-downloads/nsq/pynsq-%s.tar.gz' %
version
),
packages=['nsq'],
requires=['tornado'],
include_package_data=True,
zip_safe=False,
tests_require=['pytest', 'mock', 'tornado'],
cmdclass={'test': PyTest},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
]
)
|
# ... existing code ...
author='Matt Reiferson',
author_email='[email protected]',
url='http://github.com/bitly/pynsq',
download_url=(
'https://s3.amazonaws.com/bitly-downloads/nsq/pynsq-%s.tar.gz' %
version
),
packages=['nsq'],
requires=['tornado'],
include_package_data=True,
# ... modified code ...
tests_require=['pytest', 'mock', 'tornado'],
cmdclass={'test': PyTest},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
]
)
# ... rest of the code ...
|
9ad85a6986c8350cb082f23d9508301c40ca440d
|
resolwe_bio/api/views.py
|
resolwe_bio/api/views.py
|
from django.db.models import Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_schema__slug='sample').prefetch_related('descriptor_schema')
@list_route(methods=[u'get'])
def annotated(self, request):
"""Return list of annotated `Samples`."""
queryset = self.get_queryset().filter(
Q(descriptor__has_key='geo') & Q(descriptor__geo__has_key='annotator'))
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
@list_route(methods=[u'get'])
def unannotated(self, request):
"""Return list of unannotated `Samples`."""
queryset = self.get_queryset().filter(
~Q(descriptor__has_key='geo') | ~Q(descriptor__geo__has_key='annotator'))
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
|
from django.db.models import Max, Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_schema__slug='sample').prefetch_related('descriptor_schema')
@list_route(methods=[u'get'])
def annotated(self, request):
"""Return list of annotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
Q(descriptor__has_key='geo') & Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
@list_route(methods=[u'get'])
def unannotated(self, request):
"""Return list of unannotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
~Q(descriptor__has_key='geo') | ~Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
|
Order samples by date created of the newest Data
|
Order samples by date created of the newest Data
|
Python
|
apache-2.0
|
genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio
|
python
|
## Code Before:
from django.db.models import Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_schema__slug='sample').prefetch_related('descriptor_schema')
@list_route(methods=[u'get'])
def annotated(self, request):
"""Return list of annotated `Samples`."""
queryset = self.get_queryset().filter(
Q(descriptor__has_key='geo') & Q(descriptor__geo__has_key='annotator'))
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
@list_route(methods=[u'get'])
def unannotated(self, request):
"""Return list of unannotated `Samples`."""
queryset = self.get_queryset().filter(
~Q(descriptor__has_key='geo') | ~Q(descriptor__geo__has_key='annotator'))
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
## Instruction:
Order samples by date created of the newest Data
## Code After:
from django.db.models import Max, Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_schema__slug='sample').prefetch_related('descriptor_schema')
@list_route(methods=[u'get'])
def annotated(self, request):
"""Return list of annotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
Q(descriptor__has_key='geo') & Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
@list_route(methods=[u'get'])
def unannotated(self, request):
"""Return list of unannotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
~Q(descriptor__has_key='geo') | ~Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
|
...
from django.db.models import Max, Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
...
@list_route(methods=[u'get'])
def annotated(self, request):
"""Return list of annotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
Q(descriptor__has_key='geo') & Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
...
@list_route(methods=[u'get'])
def unannotated(self, request):
"""Return list of unannotated `Samples`."""
queryset = self.get_queryset().annotate(
latest_date=Max('data__created')
).filter(
~Q(descriptor__has_key='geo') | ~Q(descriptor__geo__has_key='annotator')
).order_by('-latest_date')
serializer = self.serializer_class(queryset, many=True, context={'request': request})
return Response(serializer.data)
...
|
713851196e36a1c0911bef2b7e95c34a857c29b6
|
idea-plugin/src/com/reason/bs/BsColoredProcessHandler.java
|
idea-plugin/src/com/reason/bs/BsColoredProcessHandler.java
|
package com.reason.bs;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;
class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;
BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
super(commandLine);
m_onProcessTerminated = onProcessTerminated;
}
@Override
protected void onOSProcessTerminated(int exitCode) {
super.onOSProcessTerminated(exitCode);
if (m_onProcessTerminated != null) {
m_onProcessTerminated.run();
}
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
m_ansiEscapeDecoder.escapeText(text, outputType, super::notifyTextAvailable);
}
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
super.notifyTextAvailable(text, attributes);
}
}
|
package com.reason.bs;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;
class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;
BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
super(commandLine);
m_onProcessTerminated = onProcessTerminated;
}
@Override
protected void onOSProcessTerminated(int exitCode) {
super.onOSProcessTerminated(exitCode);
if (m_onProcessTerminated != null) {
m_onProcessTerminated.run();
}
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
m_ansiEscapeDecoder.escapeText(
text,
outputType,
(chunk, attributes) -> {
if (":".equals(chunk)) {
// Suppose this is the separator in output: C:\xxx\xxx\File.re : 1:13-14
super.notifyTextAvailable(" ", attributes);
} else {
super.notifyTextAvailable(chunk, attributes);
}
});
}
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
super.notifyTextAvailable(text, attributes);
}
}
|
Fix file pattern introduced in 8.3.0
|
Fix file pattern introduced in 8.3.0
|
Java
|
mit
|
reasonml-editor/reasonml-idea-plugin,giraud/reasonml-idea-plugin,giraud/reasonml-idea-plugin,giraud/reasonml-idea-plugin,reasonml-editor/reasonml-idea-plugin
|
java
|
## Code Before:
package com.reason.bs;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;
class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;
BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
super(commandLine);
m_onProcessTerminated = onProcessTerminated;
}
@Override
protected void onOSProcessTerminated(int exitCode) {
super.onOSProcessTerminated(exitCode);
if (m_onProcessTerminated != null) {
m_onProcessTerminated.run();
}
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
m_ansiEscapeDecoder.escapeText(text, outputType, super::notifyTextAvailable);
}
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
super.notifyTextAvailable(text, attributes);
}
}
## Instruction:
Fix file pattern introduced in 8.3.0
## Code After:
package com.reason.bs;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;
class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;
BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
super(commandLine);
m_onProcessTerminated = onProcessTerminated;
}
@Override
protected void onOSProcessTerminated(int exitCode) {
super.onOSProcessTerminated(exitCode);
if (m_onProcessTerminated != null) {
m_onProcessTerminated.run();
}
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
m_ansiEscapeDecoder.escapeText(
text,
outputType,
(chunk, attributes) -> {
if (":".equals(chunk)) {
// Suppose this is the separator in output: C:\xxx\xxx\File.re : 1:13-14
super.notifyTextAvailable(" ", attributes);
} else {
super.notifyTextAvailable(chunk, attributes);
}
});
}
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
super.notifyTextAvailable(text, attributes);
}
}
|
# ... existing code ...
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
m_ansiEscapeDecoder.escapeText(
text,
outputType,
(chunk, attributes) -> {
if (":".equals(chunk)) {
// Suppose this is the separator in output: C:\xxx\xxx\File.re : 1:13-14
super.notifyTextAvailable(" ", attributes);
} else {
super.notifyTextAvailable(chunk, attributes);
}
});
}
@Override
# ... rest of the code ...
|
121c886dfe02ed8cd71075a03e268d51bcb137fc
|
institutions/respondants/search_indexes.py
|
institutions/respondants/search_indexes.py
|
from haystack import indexes
from respondants.models import Institution
class InstitutionIndex(indexes.SearchIndex, indexes.Indexable):
"""Search Index associated with an institution. Allows for searching by
name or lender id"""
text = indexes.CharField(document=True, model_attr='name')
text_auto = indexes.EdgeNgramField(model_attr='name')
lender_id = indexes.CharField()
assets = indexes.IntegerField(model_attr='assets')
num_loans = indexes.IntegerField(model_attr='num_loans')
def get_model(self):
return Institution
def index_queryset(self, using=None):
"""To account for the somewhat complicated count query, we need to add
an "extra" annotation"""
subquery_tail = """
FROM hmda_hmdarecord
WHERE year = 2013 AND hmda_hmdarecord.lender
= CAST(respondants_institution.agency_id AS VARCHAR(1))
|| respondants_institution.ffiec_id"""
return self.get_model().objects.extra(
select={"num_loans": "SELECT COUNT(*) " + subquery_tail},
where=["SELECT COUNT(*) > 0 " + subquery_tail])
def read_queryset(self, using=None):
"""A more efficient query than the index query -- makes use of select
related and does not include the num_loans calculation."""
return self.get_model().objects.select_related('zip_code', 'agency')
def prepare_lender_id(self, institution):
return str(institution.agency_id) + institution.ffiec_id
|
from haystack import indexes
from respondants.models import Institution
class InstitutionIndex(indexes.SearchIndex, indexes.Indexable):
"""Search Index associated with an institution. Allows for searching by
name or lender id"""
text = indexes.CharField(document=True, model_attr='name')
text_auto = indexes.EdgeNgramField(model_attr='name')
lender_id = indexes.CharField()
assets = indexes.IntegerField(model_attr='assets')
num_loans = indexes.IntegerField(model_attr='num_loans')
def get_model(self):
return Institution
def index_queryset(self, using=None):
"""To account for the somewhat complicated count query, we need to add
an "extra" annotation"""
subquery_tail = """
FROM hmda_hmdarecord
WHERE hmda_hmdarecord.lender
= CAST(respondants_institution.agency_id AS VARCHAR(1))
|| respondants_institution.ffiec_id"""
return self.get_model().objects.extra(
select={"num_loans": "SELECT COUNT(*) " + subquery_tail},
where=["SELECT COUNT(*) > 0 " + subquery_tail])
def read_queryset(self, using=None):
"""A more efficient query than the index query -- makes use of select
related and does not include the num_loans calculation."""
return self.get_model().objects.select_related('zip_code', 'agency')
def prepare_lender_id(self, institution):
return str(institution.agency_id) + institution.ffiec_id
|
Revert "adding 2013 to search query"
|
Revert "adding 2013 to search query"
|
Python
|
cc0-1.0
|
mehtadev17/mapusaurus,mehtadev17/mapusaurus,mehtadev17/mapusaurus
|
python
|
## Code Before:
from haystack import indexes
from respondants.models import Institution
class InstitutionIndex(indexes.SearchIndex, indexes.Indexable):
"""Search Index associated with an institution. Allows for searching by
name or lender id"""
text = indexes.CharField(document=True, model_attr='name')
text_auto = indexes.EdgeNgramField(model_attr='name')
lender_id = indexes.CharField()
assets = indexes.IntegerField(model_attr='assets')
num_loans = indexes.IntegerField(model_attr='num_loans')
def get_model(self):
return Institution
def index_queryset(self, using=None):
"""To account for the somewhat complicated count query, we need to add
an "extra" annotation"""
subquery_tail = """
FROM hmda_hmdarecord
WHERE year = 2013 AND hmda_hmdarecord.lender
= CAST(respondants_institution.agency_id AS VARCHAR(1))
|| respondants_institution.ffiec_id"""
return self.get_model().objects.extra(
select={"num_loans": "SELECT COUNT(*) " + subquery_tail},
where=["SELECT COUNT(*) > 0 " + subquery_tail])
def read_queryset(self, using=None):
"""A more efficient query than the index query -- makes use of select
related and does not include the num_loans calculation."""
return self.get_model().objects.select_related('zip_code', 'agency')
def prepare_lender_id(self, institution):
return str(institution.agency_id) + institution.ffiec_id
## Instruction:
Revert "adding 2013 to search query"
## Code After:
from haystack import indexes
from respondants.models import Institution
class InstitutionIndex(indexes.SearchIndex, indexes.Indexable):
"""Search Index associated with an institution. Allows for searching by
name or lender id"""
text = indexes.CharField(document=True, model_attr='name')
text_auto = indexes.EdgeNgramField(model_attr='name')
lender_id = indexes.CharField()
assets = indexes.IntegerField(model_attr='assets')
num_loans = indexes.IntegerField(model_attr='num_loans')
def get_model(self):
return Institution
def index_queryset(self, using=None):
"""To account for the somewhat complicated count query, we need to add
an "extra" annotation"""
subquery_tail = """
FROM hmda_hmdarecord
WHERE hmda_hmdarecord.lender
= CAST(respondants_institution.agency_id AS VARCHAR(1))
|| respondants_institution.ffiec_id"""
return self.get_model().objects.extra(
select={"num_loans": "SELECT COUNT(*) " + subquery_tail},
where=["SELECT COUNT(*) > 0 " + subquery_tail])
def read_queryset(self, using=None):
"""A more efficient query than the index query -- makes use of select
related and does not include the num_loans calculation."""
return self.get_model().objects.select_related('zip_code', 'agency')
def prepare_lender_id(self, institution):
return str(institution.agency_id) + institution.ffiec_id
|
// ... existing code ...
an "extra" annotation"""
subquery_tail = """
FROM hmda_hmdarecord
WHERE hmda_hmdarecord.lender
= CAST(respondants_institution.agency_id AS VARCHAR(1))
|| respondants_institution.ffiec_id"""
return self.get_model().objects.extra(
// ... rest of the code ...
|
a9f5603b9134a6daa757fd85c1600ac3aa67f5df
|
time_test.py
|
time_test.py
|
import timeit
setup="""
from _ppeg import Pattern
text = open('kjv10.txt').read()
pat = Pattern()
pat.setdummy()
pat.dump()
"""
t = timeit.Timer(stmt='print pat.match(text)', setup=setup)
N=5
print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
|
import timeit
setup="""
from _ppeg import Pattern
text = open('kjv10.txt').read()
pat = Pattern.Dummy()
pat.dump()
"""
t = timeit.Timer(stmt='print pat(text)', setup=setup)
N=5
print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
|
Update timing test to new pattern API
|
Update timing test to new pattern API
|
Python
|
mit
|
moreati/ppeg,moreati/ppeg
|
python
|
## Code Before:
import timeit
setup="""
from _ppeg import Pattern
text = open('kjv10.txt').read()
pat = Pattern()
pat.setdummy()
pat.dump()
"""
t = timeit.Timer(stmt='print pat.match(text)', setup=setup)
N=5
print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
## Instruction:
Update timing test to new pattern API
## Code After:
import timeit
setup="""
from _ppeg import Pattern
text = open('kjv10.txt').read()
pat = Pattern.Dummy()
pat.dump()
"""
t = timeit.Timer(stmt='print pat(text)', setup=setup)
N=5
print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
|
// ... existing code ...
text = open('kjv10.txt').read()
pat = Pattern.Dummy()
pat.dump()
"""
t = timeit.Timer(stmt='print pat(text)', setup=setup)
N=5
print "Time taken: %.2f sec" % (t.timeit(N)/float(N))
// ... rest of the code ...
|
603cfbe46f99949f2dd17984772d73c211463d04
|
example/src/main/java/io/github/jakriz/derrick/example/DocsMethods.java
|
example/src/main/java/io/github/jakriz/derrick/example/DocsMethods.java
|
package io.github.jakriz.derrick.example;
import io.github.jakriz.derrick.annotation.DerrickInterface;
import io.github.jakriz.derrick.annotation.SourceFrom;
@DerrickInterface(baseUrl = "https://github.com/jakriz/derrick", imports = {"io.github.jakriz.derrick.example.*"})
public interface DocsMethods {
@SourceFrom(selector = "#sample-math-wizard-add", addReturn = true)
int add(MathWizard mathWizard);
}
|
package io.github.jakriz.derrick.example;
import io.github.jakriz.derrick.annotation.DerrickInterface;
import io.github.jakriz.derrick.annotation.SourceFrom;
@DerrickInterface(baseUrl = "https://github.com/jakriz/derrick", imports = {"io.github.jakriz.derrick.example.*"})
public interface DocsMethods {
@SourceFrom(selector = "#user-content-sample-math-wizard-add", addReturn = true)
int add(MathWizard mathWizard);
}
|
Change example id to fit github's naming
|
Change example id to fit github's naming
|
Java
|
mit
|
jakriz/derrick,jakriz/derrick
|
java
|
## Code Before:
package io.github.jakriz.derrick.example;
import io.github.jakriz.derrick.annotation.DerrickInterface;
import io.github.jakriz.derrick.annotation.SourceFrom;
@DerrickInterface(baseUrl = "https://github.com/jakriz/derrick", imports = {"io.github.jakriz.derrick.example.*"})
public interface DocsMethods {
@SourceFrom(selector = "#sample-math-wizard-add", addReturn = true)
int add(MathWizard mathWizard);
}
## Instruction:
Change example id to fit github's naming
## Code After:
package io.github.jakriz.derrick.example;
import io.github.jakriz.derrick.annotation.DerrickInterface;
import io.github.jakriz.derrick.annotation.SourceFrom;
@DerrickInterface(baseUrl = "https://github.com/jakriz/derrick", imports = {"io.github.jakriz.derrick.example.*"})
public interface DocsMethods {
@SourceFrom(selector = "#user-content-sample-math-wizard-add", addReturn = true)
int add(MathWizard mathWizard);
}
|
# ... existing code ...
@DerrickInterface(baseUrl = "https://github.com/jakriz/derrick", imports = {"io.github.jakriz.derrick.example.*"})
public interface DocsMethods {
@SourceFrom(selector = "#user-content-sample-math-wizard-add", addReturn = true)
int add(MathWizard mathWizard);
}
# ... rest of the code ...
|
f75db89abe15ca62633a6824c712a7bc7a39a883
|
src/com/obidea/semantika/cli2/command/ShowPrefixesCommand.java
|
src/com/obidea/semantika/cli2/command/ShowPrefixesCommand.java
|
package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String prefix : map.keySet()) {
out.println(prefix + ": " + map.get(prefix));
}
}
out.println();
}
}
|
package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
}
}
|
Change the show prefixes commmand output.
|
Change the show prefixes commmand output.
|
Java
|
apache-2.0
|
obidea/semantika-cli2
|
java
|
## Code Before:
package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String prefix : map.keySet()) {
out.println(prefix + ": " + map.get(prefix));
}
}
out.println();
}
}
## Instruction:
Change the show prefixes commmand output.
## Code After:
package com.obidea.semantika.cli2.command;
import java.io.PrintStream;
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
private ConsoleSession mSession;
public ShowPrefixesCommand(String command, ConsoleSession session)
{
mSession = session;
}
@Override
public Object execute() throws Exception
{
return mSession.getPrefixMapper();
}
@Override
public void printOutput(PrintStream out, Object output)
{
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
}
}
|
...
import java.util.Map;
import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;
public class ShowPrefixesCommand extends Command
{
...
if (output instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) output;
for (String key : map.keySet()) {
String prefix = key;
if (StringUtils.isEmpty(prefix)) {
prefix = "(default)"; //
}
out.println(prefix + " = " + map.get(key));
}
}
out.println();
...
|
d4c8b0f15cd1694b84f8dab7936571d9f9bca42f
|
tests/people/test_managers.py
|
tests/people/test_managers.py
|
import pytest
from components.people.factories import IdolFactory
from components.people.models import Idol
from components.people.constants import STATUS
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def idols(self):
idols = []
[idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
[idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
return idols
def test_active_manager(self, idols):
assert len(Idol.objects.active()) == 3
def test_inactive_manager(self, idols):
assert len(Idol.objects.inactive()) == 2
|
import datetime
import pytest
from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def status(self):
idols = []
[idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
[idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
return idols
def test_active_manager(self, status):
assert len(Idol.objects.active()) == 3
def test_inactive_manager(self, status):
assert len(Idol.objects.inactive()) == 2
class TestGroups:
@pytest.fixture
def status(self):
groups = [
GroupFactory(),
GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
]
return groups
def test_active_manager(self, status):
assert len(Group.objects.active()) == 2
def test_inactive_manager(self, status):
assert len(Group.objects.inactive()) == 1
|
Test group managers. Rename idols() => status().
|
Test group managers. Rename idols() => status().
|
Python
|
apache-2.0
|
hello-base/web,hello-base/web,hello-base/web,hello-base/web
|
python
|
## Code Before:
import pytest
from components.people.factories import IdolFactory
from components.people.models import Idol
from components.people.constants import STATUS
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def idols(self):
idols = []
[idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
[idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
return idols
def test_active_manager(self, idols):
assert len(Idol.objects.active()) == 3
def test_inactive_manager(self, idols):
assert len(Idol.objects.inactive()) == 2
## Instruction:
Test group managers. Rename idols() => status().
## Code After:
import datetime
import pytest
from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def status(self):
idols = []
[idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
[idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
return idols
def test_active_manager(self, status):
assert len(Idol.objects.active()) == 3
def test_inactive_manager(self, status):
assert len(Idol.objects.inactive()) == 2
class TestGroups:
@pytest.fixture
def status(self):
groups = [
GroupFactory(),
GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
]
return groups
def test_active_manager(self, status):
assert len(Group.objects.active()) == 2
def test_inactive_manager(self, status):
assert len(Group.objects.inactive()) == 1
|
...
import datetime
import pytest
from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol
pytestmark = pytest.mark.django_db
...
class TestIdols:
@pytest.fixture
def status(self):
idols = []
[idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
[idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
return idols
def test_active_manager(self, status):
assert len(Idol.objects.active()) == 3
def test_inactive_manager(self, status):
assert len(Idol.objects.inactive()) == 2
class TestGroups:
@pytest.fixture
def status(self):
groups = [
GroupFactory(),
GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
]
return groups
def test_active_manager(self, status):
assert len(Group.objects.active()) == 2
def test_inactive_manager(self, status):
assert len(Group.objects.inactive()) == 1
...
|
3c3fc9bff5c4417f7aa48e29d27ea1a963967c0a
|
examples/java-calculator-testng/src/test/java/cucumber/examples/java/calculator/RunCukesByFeatureAndCompositionTest.java
|
examples/java-calculator-testng/src/test/java/cucumber/examples/java/calculator/RunCukesByFeatureAndCompositionTest.java
|
package cucumber.examples.java.calculator;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;
import cucumber.api.testng.CucumberFeatureWrapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* An example of using TestNG when the test class does not inherit from
* AbstractTestNGCucumberTests but still executes each feature as a separate
* TestNG test.
*/
@CucumberOptions(format = "json:target/cucumber-report-feature-composite.json")
public class RunCukesByFeatureAndCompositionTest extends RunCukesByCompositionBase {
private TestNGCucumberRunner testNGCucumberRunner;
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
@Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
@DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
@AfterClass
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
|
package cucumber.examples.java.calculator;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;
import cucumber.api.testng.CucumberFeatureWrapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* An example of using TestNG when the test class does not inherit from
* AbstractTestNGCucumberTests but still executes each feature as a separate
* TestNG test.
*/
@CucumberOptions(format = "json:target/cucumber-report-feature-composite.json")
public class RunCukesByFeatureAndCompositionTest extends RunCukesByCompositionBase {
private TestNGCucumberRunner testNGCucumberRunner;
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
@Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
@DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
@AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
|
Add alwaysRun=true to the TestNG example's AfterClass method
|
Add alwaysRun=true to the TestNG example's AfterClass method
|
Java
|
mit
|
HendrikSP/cucumber-jvm,paoloambrosio/cucumber-jvm,andyb-ge/cucumber-jvm,cucumber/cucumber-jvm,dkowis/cucumber-jvm,DPUkyle/cucumber-jvm,danielwegener/cucumber-jvm,danielwegener/cucumber-jvm,HendrikSP/cucumber-jvm,joansmith/cucumber-jvm,cucumber/cucumber-jvm,joansmith/cucumber-jvm,cucumber/cucumber-jvm,danielwegener/cucumber-jvm,danielwegener/cucumber-jvm,joansmith/cucumber-jvm,DPUkyle/cucumber-jvm,dkowis/cucumber-jvm,HendrikSP/cucumber-jvm,cucumber/cucumber-jvm,HendrikSP/cucumber-jvm,joansmith/cucumber-jvm,andyb-ge/cucumber-jvm,DPUkyle/cucumber-jvm,danielwegener/cucumber-jvm,HendrikSP/cucumber-jvm,joansmith/cucumber-jvm,dkowis/cucumber-jvm,andyb-ge/cucumber-jvm,andyb-ge/cucumber-jvm,paoloambrosio/cucumber-jvm,cucumber/cucumber-jvm,DPUkyle/cucumber-jvm,dkowis/cucumber-jvm,HendrikSP/cucumber-jvm,dkowis/cucumber-jvm,paoloambrosio/cucumber-jvm,paoloambrosio/cucumber-jvm,dkowis/cucumber-jvm,danielwegener/cucumber-jvm,andyb-ge/cucumber-jvm,DPUkyle/cucumber-jvm,DPUkyle/cucumber-jvm,andyb-ge/cucumber-jvm,joansmith/cucumber-jvm
|
java
|
## Code Before:
package cucumber.examples.java.calculator;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;
import cucumber.api.testng.CucumberFeatureWrapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* An example of using TestNG when the test class does not inherit from
* AbstractTestNGCucumberTests but still executes each feature as a separate
* TestNG test.
*/
@CucumberOptions(format = "json:target/cucumber-report-feature-composite.json")
public class RunCukesByFeatureAndCompositionTest extends RunCukesByCompositionBase {
private TestNGCucumberRunner testNGCucumberRunner;
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
@Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
@DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
@AfterClass
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
## Instruction:
Add alwaysRun=true to the TestNG example's AfterClass method
## Code After:
package cucumber.examples.java.calculator;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;
import cucumber.api.testng.CucumberFeatureWrapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* An example of using TestNG when the test class does not inherit from
* AbstractTestNGCucumberTests but still executes each feature as a separate
* TestNG test.
*/
@CucumberOptions(format = "json:target/cucumber-report-feature-composite.json")
public class RunCukesByFeatureAndCompositionTest extends RunCukesByCompositionBase {
private TestNGCucumberRunner testNGCucumberRunner;
@BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
@Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
@DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
@AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}
|
...
return testNGCucumberRunner.provideFeatures();
}
@AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
...
|
c00fcf14b9f1904f96ab5d84601d3bbb9323267c
|
src/main/java/com/vtence/molecule/testing/http/TextContent.java
|
src/main/java/com/vtence/molecule/testing/http/TextContent.java
|
package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private final String contentType;
public TextContent(String text, String contentType) {
this.text = text;
this.contentType = contentType;
}
@Override
public long contentLength() {
return content().length;
}
public String contentType() {
return contentType;
}
private byte[] content() {
return text.getBytes(charset());
}
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(content());
}
private Charset charset() {
ContentType contentType = ContentType.parse(contentType());
if (contentType == null || contentType.charset() == null) return StandardCharsets.ISO_8859_1;
return contentType.charset();
}
}
|
package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private final String contentType;
public TextContent(String text, String contentType) {
this.text = text;
this.contentType = contentType;
}
@Override
public long contentLength() {
return content().length;
}
public String contentType() {
return contentType;
}
private byte[] content() {
return text.getBytes(charset());
}
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(content());
}
private Charset charset() {
if (contentType() == null) return StandardCharsets.ISO_8859_1;
ContentType contentType = ContentType.parse(contentType());
if (contentType.charset() == null) return StandardCharsets.ISO_8859_1;
return contentType.charset();
}
}
|
Fix potential issue when parsing text content charset
|
Fix potential issue when parsing text content charset
|
Java
|
mit
|
testinfected/molecule,testinfected/molecule,testinfected/molecule,testinfected/molecule,testinfected/molecule
|
java
|
## Code Before:
package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private final String contentType;
public TextContent(String text, String contentType) {
this.text = text;
this.contentType = contentType;
}
@Override
public long contentLength() {
return content().length;
}
public String contentType() {
return contentType;
}
private byte[] content() {
return text.getBytes(charset());
}
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(content());
}
private Charset charset() {
ContentType contentType = ContentType.parse(contentType());
if (contentType == null || contentType.charset() == null) return StandardCharsets.ISO_8859_1;
return contentType.charset();
}
}
## Instruction:
Fix potential issue when parsing text content charset
## Code After:
package com.vtence.molecule.testing.http;
import com.vtence.molecule.http.ContentType;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TextContent implements HttpContent {
private final String text;
private final String contentType;
public TextContent(String text, String contentType) {
this.text = text;
this.contentType = contentType;
}
@Override
public long contentLength() {
return content().length;
}
public String contentType() {
return contentType;
}
private byte[] content() {
return text.getBytes(charset());
}
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(content());
}
private Charset charset() {
if (contentType() == null) return StandardCharsets.ISO_8859_1;
ContentType contentType = ContentType.parse(contentType());
if (contentType.charset() == null) return StandardCharsets.ISO_8859_1;
return contentType.charset();
}
}
|
# ... existing code ...
}
private Charset charset() {
if (contentType() == null) return StandardCharsets.ISO_8859_1;
ContentType contentType = ContentType.parse(contentType());
if (contentType.charset() == null) return StandardCharsets.ISO_8859_1;
return contentType.charset();
}
# ... rest of the code ...
|
26e26e50ddd8b64fd3206788ef1defbf337698e5
|
app/urls.py
|
app/urls.py
|
"""Define URLs and handlers to server them."""
from tornado.web import url
from handlers import (
DefConfHandler,
JobHandler,
SubscriptionHandler
)
APP_URLS = [
url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'),
url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'),
url(r'/api/subscription', SubscriptionHandler, name='subscription')
]
|
"""Define URLs and handlers to server them."""
from tornado.web import url
from handlers import (
DefConfHandler,
JobHandler,
SubscriptionHandler
)
APP_URLS = [
url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'),
url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'),
url(
r'/api/subscription(?P<sl>/)?(?P<id>.*)',
SubscriptionHandler,
name='subscription'
)
]
|
Add ID support for subscription/ URLs.
|
Add ID support for subscription/ URLs.
|
Python
|
agpl-3.0
|
joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend
|
python
|
## Code Before:
"""Define URLs and handlers to server them."""
from tornado.web import url
from handlers import (
DefConfHandler,
JobHandler,
SubscriptionHandler
)
APP_URLS = [
url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'),
url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'),
url(r'/api/subscription', SubscriptionHandler, name='subscription')
]
## Instruction:
Add ID support for subscription/ URLs.
## Code After:
"""Define URLs and handlers to server them."""
from tornado.web import url
from handlers import (
DefConfHandler,
JobHandler,
SubscriptionHandler
)
APP_URLS = [
url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'),
url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'),
url(
r'/api/subscription(?P<sl>/)?(?P<id>.*)',
SubscriptionHandler,
name='subscription'
)
]
|
...
APP_URLS = [
url(r'/api/defconfig(?P<sl>/)?(?P<id>.*)', DefConfHandler, name='defconf'),
url(r'/api/job(?P<sl>/)?(?P<id>.*)', JobHandler, name='job'),
url(
r'/api/subscription(?P<sl>/)?(?P<id>.*)',
SubscriptionHandler,
name='subscription'
)
]
...
|
936987c951fcd2ff64fbfed9f89c5d6a835b443b
|
bbvm-core/src/test/java/me/wener/bbvm/vm/BasmSpecTest.java
|
bbvm-core/src/test/java/me/wener/bbvm/vm/BasmSpecTest.java
|
package me.wener.bbvm.vm;
import me.wener.bbvm.asm.ParseException;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author wener
* @since 15/12/18
*/
public class BasmSpecTest {
@Test
public void in() throws IOException, ParseException {
BasmTester test = new BasmTester();
Files.walk(Paths.get("../bbvm-test/case/in"))
.filter(p -> !p.toFile().isDirectory())
.filter(p -> p.toFile().getName().endsWith(".basm"))
.forEach(p -> test.init(p.toFile()).run());
}
}
|
package me.wener.bbvm.vm;
import me.wener.bbvm.asm.ParseException;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author wener
* @since 15/12/18
*/
public class BasmSpecTest {
@Test
public void in() throws IOException, ParseException {
doTest("../bbvm-test/case/in");
}
@Test
public void out() throws IOException, ParseException {
doTest("../bbvm-test/case/out");
}
@Test
public void file() throws IOException, ParseException {
doTest("../bbvm-test/case/file");
}
@Test
public void graph() throws IOException, ParseException {
doTest("../bbvm-test/case/graph");
}
@Test
public void basic() throws IOException, ParseException {
doTest("../bbvm-test/case/basic");
}
private void doTest(String first) throws IOException {
BasmTester test = new BasmTester();
Files.walk(Paths.get(first))
.filter(p -> !p.toFile().isDirectory())
.filter(p -> p.toFile().getName().endsWith(".basm"))
.forEach(p -> test.init(p.toFile()).run());
}
}
|
Add file basic graph basm test.
|
Add file basic graph basm test.
|
Java
|
apache-2.0
|
wenerme/bbvm,wenerme/bbvm
|
java
|
## Code Before:
package me.wener.bbvm.vm;
import me.wener.bbvm.asm.ParseException;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author wener
* @since 15/12/18
*/
public class BasmSpecTest {
@Test
public void in() throws IOException, ParseException {
BasmTester test = new BasmTester();
Files.walk(Paths.get("../bbvm-test/case/in"))
.filter(p -> !p.toFile().isDirectory())
.filter(p -> p.toFile().getName().endsWith(".basm"))
.forEach(p -> test.init(p.toFile()).run());
}
}
## Instruction:
Add file basic graph basm test.
## Code After:
package me.wener.bbvm.vm;
import me.wener.bbvm.asm.ParseException;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author wener
* @since 15/12/18
*/
public class BasmSpecTest {
@Test
public void in() throws IOException, ParseException {
doTest("../bbvm-test/case/in");
}
@Test
public void out() throws IOException, ParseException {
doTest("../bbvm-test/case/out");
}
@Test
public void file() throws IOException, ParseException {
doTest("../bbvm-test/case/file");
}
@Test
public void graph() throws IOException, ParseException {
doTest("../bbvm-test/case/graph");
}
@Test
public void basic() throws IOException, ParseException {
doTest("../bbvm-test/case/basic");
}
private void doTest(String first) throws IOException {
BasmTester test = new BasmTester();
Files.walk(Paths.get(first))
.filter(p -> !p.toFile().isDirectory())
.filter(p -> p.toFile().getName().endsWith(".basm"))
.forEach(p -> test.init(p.toFile()).run());
}
}
|
...
public class BasmSpecTest {
@Test
public void in() throws IOException, ParseException {
doTest("../bbvm-test/case/in");
}
@Test
public void out() throws IOException, ParseException {
doTest("../bbvm-test/case/out");
}
@Test
public void file() throws IOException, ParseException {
doTest("../bbvm-test/case/file");
}
@Test
public void graph() throws IOException, ParseException {
doTest("../bbvm-test/case/graph");
}
@Test
public void basic() throws IOException, ParseException {
doTest("../bbvm-test/case/basic");
}
private void doTest(String first) throws IOException {
BasmTester test = new BasmTester();
Files.walk(Paths.get(first))
.filter(p -> !p.toFile().isDirectory())
.filter(p -> p.toFile().getName().endsWith(".basm"))
.forEach(p -> test.init(p.toFile()).run());
...
|
cb673c3c6074a319cac538cf688a016fbde79e1f
|
app/src/main/java/com/nicoladefiorenze/room/MainActivity.kt
|
app/src/main/java/com/nicoladefiorenze/room/MainActivity.kt
|
package com.nicoladefiorenze.room
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import com.nicoladefiorenze.room.business.datasource.UserDataSource
import com.nicoladefiorenze.room.database.DatabaseProvider
import com.nicoladefiorenze.room.database.entity.Email
import com.nicoladefiorenze.room.database.entity.User
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Project: Room<br/>
* created on: 2017-05-20
*
* @author Nicola De Fiorenze
*/
class MainActivity : AppCompatActivity() {
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val database = DatabaseProvider.getDatabase(applicationContext)
UserDataSource(database).getAllUsers().subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread())
.subscribe(
{ user -> println(user) },
{ error -> println(error.message) }
)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
|
package com.nicoladefiorenze.room
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import com.nicoladefiorenze.room.business.datasource.UserDataSource
import com.nicoladefiorenze.room.database.DatabaseProvider
import com.nicoladefiorenze.room.database.entity.Email
import com.nicoladefiorenze.room.database.entity.User
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Project: Room<br/>
* created on: 2017-05-20
*
* @author Nicola De Fiorenze
*/
class MainActivity : AppCompatActivity() {
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val database = DatabaseProvider.getDatabase(applicationContext)
disposables.add(UserDataSource(database).getAllUsers().subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread())
.subscribe(
{ user -> println(user) },
{ error -> println(error.message) }
)
)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
|
Add the flowable to the composite disposable
|
Add the flowable to the composite disposable
|
Kotlin
|
apache-2.0
|
defio/Room-experimets-in-kotlin,defio/Room-experimets-in-kotlin
|
kotlin
|
## Code Before:
package com.nicoladefiorenze.room
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import com.nicoladefiorenze.room.business.datasource.UserDataSource
import com.nicoladefiorenze.room.database.DatabaseProvider
import com.nicoladefiorenze.room.database.entity.Email
import com.nicoladefiorenze.room.database.entity.User
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Project: Room<br/>
* created on: 2017-05-20
*
* @author Nicola De Fiorenze
*/
class MainActivity : AppCompatActivity() {
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val database = DatabaseProvider.getDatabase(applicationContext)
UserDataSource(database).getAllUsers().subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread())
.subscribe(
{ user -> println(user) },
{ error -> println(error.message) }
)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
## Instruction:
Add the flowable to the composite disposable
## Code After:
package com.nicoladefiorenze.room
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import com.nicoladefiorenze.room.business.datasource.UserDataSource
import com.nicoladefiorenze.room.database.DatabaseProvider
import com.nicoladefiorenze.room.database.entity.Email
import com.nicoladefiorenze.room.database.entity.User
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Project: Room<br/>
* created on: 2017-05-20
*
* @author Nicola De Fiorenze
*/
class MainActivity : AppCompatActivity() {
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val database = DatabaseProvider.getDatabase(applicationContext)
disposables.add(UserDataSource(database).getAllUsers().subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread())
.subscribe(
{ user -> println(user) },
{ error -> println(error.message) }
)
)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
|
...
val database = DatabaseProvider.getDatabase(applicationContext)
disposables.add(UserDataSource(database).getAllUsers().subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread())
.subscribe(
{ user -> println(user) },
{ error -> println(error.message) }
)
)
}
...
|
f525d04e978c35132db6ff77f455cf22b486482f
|
mod/httpserver.py
|
mod/httpserver.py
|
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
|
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
|
Allow resuse-addr at http server start
|
Allow resuse-addr at http server start
|
Python
|
mit
|
floooh/fips,floooh/fips,michaKFromParis/fips,floooh/fips,michaKFromParis/fips,anthraxx/fips,mgerhardy/fips,anthraxx/fips,mgerhardy/fips,code-disaster/fips,code-disaster/fips
|
python
|
## Code Before:
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
## Instruction:
Allow resuse-addr at http server start
## Code After:
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
|
// ... existing code ...
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
// ... rest of the code ...
|
202027ac9a2680ba8825d488c146d152beaa4b5d
|
tests/test_coursera.py
|
tests/test_coursera.py
|
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_sessions_response(self):
self.assertEqual(self.coursera_test_object.response_sessions.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
Remove test for sessions for Coursera API
|
Remove test for sessions for Coursera API
|
Python
|
mit
|
ueg1990/mooc_aggregator_restful_api
|
python
|
## Code Before:
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_sessions_response(self):
self.assertEqual(self.coursera_test_object.response_sessions.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
## Instruction:
Remove test for sessions for Coursera API
## Code After:
import unittest
from mooc_aggregator_restful_api import coursera
class CourseraTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.coursera_test_object = coursera.CourseraAPI()
def test_coursera_api_courses_response(self):
self.assertEqual(self.coursera_test_object.response_courses.status_code, 200)
def test_coursera_api_universities_response(self):
self.assertEqual(self.coursera_test_object.response_universities.status_code, 200)
def test_coursera_api_categories_response(self):
self.assertEqual(self.coursera_test_object.response_categories.status_code, 200)
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
def test_coursera_api_instructors_response(self):
self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200)
def test_coursera_api_mongofy_courses(self):
pass
// ... rest of the code ...
|
f1aabcad9e6f6daae23c158c2fba7b28f0e57416
|
message_view.py
|
message_view.py
|
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
window = self.window
if is_panel_active(window):
panel = window.find_output_panel(PANEL_NAME)
else:
panel = window.create_output_panel(PANEL_NAME)
syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax"
try: # Try the resource first, in case we're in the middle of an upgrade
sublime.load_resource(syntax_path)
except Exception:
return
panel.assign_syntax(syntax_path)
scroll_to = panel.size()
msg = msg.rstrip() + '\n\n\n'
panel.set_read_only(False)
panel.run_command('append', {'characters': msg})
panel.set_read_only(True)
panel.show(scroll_to)
window.run_command("show_panel", {"panel": OUTPUT_PANEL})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
def is_panel_active(window):
return window.active_panel() == OUTPUT_PANEL
|
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
window = self.window
if is_panel_active(window):
panel = window.find_output_panel(PANEL_NAME)
assert panel
else:
panel = window.create_output_panel(PANEL_NAME)
syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax"
try: # Try the resource first, in case we're in the middle of an upgrade
sublime.load_resource(syntax_path)
except Exception:
return
panel.assign_syntax(syntax_path)
scroll_to = panel.size()
msg = msg.rstrip() + '\n\n\n'
panel.set_read_only(False)
panel.run_command('append', {'characters': msg})
panel.set_read_only(True)
panel.show(scroll_to)
window.run_command("show_panel", {"panel": OUTPUT_PANEL})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
def is_panel_active(window):
return window.active_panel() == OUTPUT_PANEL
|
Fix mypy error by asserting
|
Fix mypy error by asserting
Since we just asked `is_panel_active`, the following `find_output_panel`
*must* succeed. So we `assert panel` to tell it mypy.
|
Python
|
mit
|
SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3
|
python
|
## Code Before:
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
window = self.window
if is_panel_active(window):
panel = window.find_output_panel(PANEL_NAME)
else:
panel = window.create_output_panel(PANEL_NAME)
syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax"
try: # Try the resource first, in case we're in the middle of an upgrade
sublime.load_resource(syntax_path)
except Exception:
return
panel.assign_syntax(syntax_path)
scroll_to = panel.size()
msg = msg.rstrip() + '\n\n\n'
panel.set_read_only(False)
panel.run_command('append', {'characters': msg})
panel.set_read_only(True)
panel.show(scroll_to)
window.run_command("show_panel", {"panel": OUTPUT_PANEL})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
def is_panel_active(window):
return window.active_panel() == OUTPUT_PANEL
## Instruction:
Fix mypy error by asserting
Since we just asked `is_panel_active`, the following `find_output_panel`
*must* succeed. So we `assert panel` to tell it mypy.
## Code After:
import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
window = self.window
if is_panel_active(window):
panel = window.find_output_panel(PANEL_NAME)
assert panel
else:
panel = window.create_output_panel(PANEL_NAME)
syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax"
try: # Try the resource first, in case we're in the middle of an upgrade
sublime.load_resource(syntax_path)
except Exception:
return
panel.assign_syntax(syntax_path)
scroll_to = panel.size()
msg = msg.rstrip() + '\n\n\n'
panel.set_read_only(False)
panel.run_command('append', {'characters': msg})
panel.set_read_only(True)
panel.show(scroll_to)
window.run_command("show_panel", {"panel": OUTPUT_PANEL})
class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.destroy_output_panel(PANEL_NAME)
def is_panel_active(window):
return window.active_panel() == OUTPUT_PANEL
|
# ... existing code ...
if is_panel_active(window):
panel = window.find_output_panel(PANEL_NAME)
assert panel
else:
panel = window.create_output_panel(PANEL_NAME)
syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax"
# ... rest of the code ...
|
cefe2cf59a90662a4c707366a99f4221fc32cba5
|
src/test/java/com/github/vbauer/herald/ext/spring/SpringBootTest.java
|
src/test/java/com/github/vbauer/herald/ext/spring/SpringBootTest.java
|
package com.github.vbauer.herald.ext.spring;
import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Vladislav Bauer
*/
@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {
@Autowired
private CheckerBean checkerBean;
@Test
public void testAll() {
checkerBean.checkBeans();
checkerBean.checkPostProcessor();
}
}
|
package com.github.vbauer.herald.ext.spring;
import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Vladislav Bauer
*/
@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {
@Autowired
private CheckerBean checkerBean;
@Test
public void testAll() {
checkerBean.checkBeans();
checkerBean.checkPostProcessor();
}
@Test
public void testAutoConfiguration() {
final LogAutoConfiguration configuration = new LogAutoConfiguration();
final LogBeanPostProcessor processor = configuration.logBeanPostProcessor();
assertThat(processor, notNullValue());
}
}
|
Add unit test for LogAutoConfiguration
|
Add unit test for LogAutoConfiguration
|
Java
|
apache-2.0
|
vbauer/herald,vbauer/herald
|
java
|
## Code Before:
package com.github.vbauer.herald.ext.spring;
import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Vladislav Bauer
*/
@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {
@Autowired
private CheckerBean checkerBean;
@Test
public void testAll() {
checkerBean.checkBeans();
checkerBean.checkPostProcessor();
}
}
## Instruction:
Add unit test for LogAutoConfiguration
## Code After:
package com.github.vbauer.herald.ext.spring;
import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Vladislav Bauer
*/
@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {
@Autowired
private CheckerBean checkerBean;
@Test
public void testAll() {
checkerBean.checkBeans();
checkerBean.checkPostProcessor();
}
@Test
public void testAutoConfiguration() {
final LogAutoConfiguration configuration = new LogAutoConfiguration();
final LogBeanPostProcessor processor = configuration.logBeanPostProcessor();
assertThat(processor, notNullValue());
}
}
|
...
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Vladislav Bauer
...
checkerBean.checkPostProcessor();
}
@Test
public void testAutoConfiguration() {
final LogAutoConfiguration configuration = new LogAutoConfiguration();
final LogBeanPostProcessor processor = configuration.logBeanPostProcessor();
assertThat(processor, notNullValue());
}
}
...
|
fd0479742afd994bfb241415f7db9c0c971a09b3
|
conanfile.py
|
conanfile.py
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
|
Copy find modules to root of module path
|
conan: Copy find modules to root of module path
|
Python
|
mit
|
polysquare/clang-tidy-target-cmake,polysquare/clang-tidy-target-cmake
|
python
|
## Code Before:
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
## Instruction:
conan: Copy find modules to root of module path
## Code After:
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ClangTidyTargetCMakeConan(ConanFile):
name = "clang-tidy-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/clang-tidy-target-cmake"
license = "MIT"
def source(self):
zip_name = "clang-tidy-target-cmake.zip"
download("https://github.com/polysquare/"
"clang-tidy-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
|
...
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="clang-tidy-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/clang-tidy-target-cmake",
src="clang-tidy-target-cmake-" + VERSION,
...
|
257134bdaea7c250d5956c4095adf0b917b65aa6
|
database/dict_converters/event_details_converter.py
|
database/dict_converters/event_details_converter.py
|
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections,
'district_points': event_details.district_points,
'rankings': event_details.renderable_rankings,
'stats': event_details.matchstats,
}
return event_details_dict
|
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
|
Fix null case for event details
|
Fix null case for event details
|
Python
|
mit
|
verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance
|
python
|
## Code Before:
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections,
'district_points': event_details.district_points,
'rankings': event_details.renderable_rankings,
'stats': event_details.matchstats,
}
return event_details_dict
## Instruction:
Fix null case for event details
## Code After:
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
|
...
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
...
|
b917a5ba927a09de7e916978e3689a23ccd035ac
|
count_word_api/helpers/text.py
|
count_word_api/helpers/text.py
|
from bs4 import BeautifulSoup
def html_to_text(html_text):
"""Receive pure html and convert to text without tags"""
soup = BeautifulSoup(html_text, "html.parser")
clean_html = ' '.join(soup.find_all(text=True))
return clean_html
def remove_punctuation(text):
translate_table = {ord(c): ""
for c in "!@#$%^&*()[]{}';:,./<>?\|`~-=_+\""}
return text.translate(translate_table)
|
from bs4 import BeautifulSoup
def html_to_text(html_text):
"""Receive pure html and convert to text without tags"""
soup = BeautifulSoup(html_text, "html.parser")
clean_html = ' '.join(soup.find_all(text=True))
return clean_html
def remove_punctuation(text):
"""Receive text and remove punctuation"""
translate_table = {ord(c): ""
for c in "!@#$%^&*()[]{}';:,./<>?\|`~-=_+\""}
return text.translate(translate_table)
|
Add missing docstring on remove_punctuation
|
Add missing docstring on remove_punctuation
|
Python
|
mit
|
rafaelhenrique/count_word_api
|
python
|
## Code Before:
from bs4 import BeautifulSoup
def html_to_text(html_text):
"""Receive pure html and convert to text without tags"""
soup = BeautifulSoup(html_text, "html.parser")
clean_html = ' '.join(soup.find_all(text=True))
return clean_html
def remove_punctuation(text):
translate_table = {ord(c): ""
for c in "!@#$%^&*()[]{}';:,./<>?\|`~-=_+\""}
return text.translate(translate_table)
## Instruction:
Add missing docstring on remove_punctuation
## Code After:
from bs4 import BeautifulSoup
def html_to_text(html_text):
"""Receive pure html and convert to text without tags"""
soup = BeautifulSoup(html_text, "html.parser")
clean_html = ' '.join(soup.find_all(text=True))
return clean_html
def remove_punctuation(text):
"""Receive text and remove punctuation"""
translate_table = {ord(c): ""
for c in "!@#$%^&*()[]{}';:,./<>?\|`~-=_+\""}
return text.translate(translate_table)
|
# ... existing code ...
def remove_punctuation(text):
"""Receive text and remove punctuation"""
translate_table = {ord(c): ""
for c in "!@#$%^&*()[]{}';:,./<>?\|`~-=_+\""}
return text.translate(translate_table)
# ... rest of the code ...
|
7d621db3618db90679461550fb0c952417616402
|
bot.py
|
bot.py
|
import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
config.read(filepath)
self.email = config['LOGIN']['email']
self.password = config['LOGIN']['password']
self.owner_ID = config['OWNER']['id']
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
def run(self):
pass
|
import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
config.read(filepath)
self.email = config['LOGIN']['email']
self.password = config['LOGIN']['password']
self.owner_ID = config['OWNER']['id']
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
async def on_ready(self):
print("Logged in as {}".format(self.user.name))
print("User ID: {}".format(self.user.id))
print("Library: {} - {}".format(discord.__title__, discord.__version__))
def run(self):
try:
self.loop.run_until_complete(self.start(self.email, self.password))
except KeyboardInterrupt:
self.loop.run_until_complete(self.logout())
finally:
self.loop.close()
|
Add Bot.run and an on_ready message
|
Add Bot.run and an on_ready message
|
Python
|
mit
|
MagiChau/ZonBot
|
python
|
## Code Before:
import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
config.read(filepath)
self.email = config['LOGIN']['email']
self.password = config['LOGIN']['password']
self.owner_ID = config['OWNER']['id']
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
def run(self):
pass
## Instruction:
Add Bot.run and an on_ready message
## Code After:
import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
config.read(filepath)
self.email = config['LOGIN']['email']
self.password = config['LOGIN']['password']
self.owner_ID = config['OWNER']['id']
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
async def on_ready(self):
print("Logged in as {}".format(self.user.name))
print("User ID: {}".format(self.user.id))
print("Library: {} - {}".format(discord.__title__, discord.__version__))
def run(self):
try:
self.loop.run_until_complete(self.start(self.email, self.password))
except KeyboardInterrupt:
self.loop.run_until_complete(self.logout())
finally:
self.loop.close()
|
# ... existing code ...
self.twitch_ID = config['TWITCH']['client_id']
self.carbon_key = config['CARBON']['key']
async def on_ready(self):
print("Logged in as {}".format(self.user.name))
print("User ID: {}".format(self.user.id))
print("Library: {} - {}".format(discord.__title__, discord.__version__))
def run(self):
try:
self.loop.run_until_complete(self.start(self.email, self.password))
except KeyboardInterrupt:
self.loop.run_until_complete(self.logout())
finally:
self.loop.close()
# ... rest of the code ...
|
2342cd5ede9fac66007d2b15025feeff52c2400b
|
flexget/plugins/operate/verify_ssl_certificates.py
|
flexget/plugins/operate/verify_ssl_certificates.py
|
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('verify_ssl')
class VerifySSLCertificates(object):
"""
Plugin that can off SSL certificate verification.
Example::
verify_ssl_certificates: no
"""
schema = {'type': 'boolean'}
@plugin.priority(253)
def on_task_start(self, task, config):
if config is False:
task.requests.verify = False
@event('plugin.register')
def register_plugin():
plugin.register(VerifySSLCertificates, 'verify_ssl_certificates', api_ver=2)
|
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from requests.packages import urllib3
from flexget import plugin
from flexget.event import event
log = logging.getLogger('verify_ssl')
class VerifySSLCertificates(object):
"""
Plugin that can off SSL certificate verification.
Example::
verify_ssl_certificates: no
"""
schema = {'type': 'boolean'}
@plugin.priority(253)
def on_task_start(self, task, config):
if config is False:
task.requests.verify = False
# Disabling verification results in a warning for every HTTPS
# request:
# "InsecureRequestWarning: Unverified HTTPS request is being made.
# Adding certificate verification is strongly advised. See:
# https://urllib3.readthedocs.io/en/latest/security.html"
# Disable those warnings because the user has explicitly disabled
# verification and the warning is not beneficial.
# This change is permanent rather than task scoped, but there won't
# be any warnings to disable when verification is enabled.
urllib3.disable_warnings()
@event('plugin.register')
def register_plugin():
plugin.register(VerifySSLCertificates, 'verify_ssl_certificates', api_ver=2)
|
Disable warnings about disabling SSL verification.
|
Disable warnings about disabling SSL verification.
Disabling SSL certificate verification results in a warning for every
HTTPS request:
"InsecureRequestWarning: Unverified HTTPS request is being made. Adding
certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/latest/security.html"
Disable those warnings because the user has explicitly disabled
verification and so the warning is not beneficial.
|
Python
|
mit
|
OmgOhnoes/Flexget,qk4l/Flexget,jacobmetrick/Flexget,jacobmetrick/Flexget,Flexget/Flexget,LynxyssCZ/Flexget,crawln45/Flexget,Flexget/Flexget,ianstalk/Flexget,OmgOhnoes/Flexget,poulpito/Flexget,drwyrm/Flexget,malkavi/Flexget,jawilson/Flexget,malkavi/Flexget,LynxyssCZ/Flexget,jawilson/Flexget,ianstalk/Flexget,gazpachoking/Flexget,sean797/Flexget,crawln45/Flexget,Danfocus/Flexget,JorisDeRieck/Flexget,drwyrm/Flexget,Danfocus/Flexget,JorisDeRieck/Flexget,JorisDeRieck/Flexget,sean797/Flexget,jawilson/Flexget,LynxyssCZ/Flexget,tobinjt/Flexget,tobinjt/Flexget,jacobmetrick/Flexget,qk4l/Flexget,qk4l/Flexget,ianstalk/Flexget,tobinjt/Flexget,malkavi/Flexget,jawilson/Flexget,Danfocus/Flexget,Flexget/Flexget,JorisDeRieck/Flexget,poulpito/Flexget,drwyrm/Flexget,malkavi/Flexget,sean797/Flexget,Danfocus/Flexget,crawln45/Flexget,poulpito/Flexget,crawln45/Flexget,OmgOhnoes/Flexget,tobinjt/Flexget,LynxyssCZ/Flexget,Flexget/Flexget,gazpachoking/Flexget
|
python
|
## Code Before:
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('verify_ssl')
class VerifySSLCertificates(object):
"""
Plugin that can off SSL certificate verification.
Example::
verify_ssl_certificates: no
"""
schema = {'type': 'boolean'}
@plugin.priority(253)
def on_task_start(self, task, config):
if config is False:
task.requests.verify = False
@event('plugin.register')
def register_plugin():
plugin.register(VerifySSLCertificates, 'verify_ssl_certificates', api_ver=2)
## Instruction:
Disable warnings about disabling SSL verification.
Disabling SSL certificate verification results in a warning for every
HTTPS request:
"InsecureRequestWarning: Unverified HTTPS request is being made. Adding
certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/latest/security.html"
Disable those warnings because the user has explicitly disabled
verification and so the warning is not beneficial.
## Code After:
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from requests.packages import urllib3
from flexget import plugin
from flexget.event import event
log = logging.getLogger('verify_ssl')
class VerifySSLCertificates(object):
"""
Plugin that can off SSL certificate verification.
Example::
verify_ssl_certificates: no
"""
schema = {'type': 'boolean'}
@plugin.priority(253)
def on_task_start(self, task, config):
if config is False:
task.requests.verify = False
# Disabling verification results in a warning for every HTTPS
# request:
# "InsecureRequestWarning: Unverified HTTPS request is being made.
# Adding certificate verification is strongly advised. See:
# https://urllib3.readthedocs.io/en/latest/security.html"
# Disable those warnings because the user has explicitly disabled
# verification and the warning is not beneficial.
# This change is permanent rather than task scoped, but there won't
# be any warnings to disable when verification is enabled.
urllib3.disable_warnings()
@event('plugin.register')
def register_plugin():
plugin.register(VerifySSLCertificates, 'verify_ssl_certificates', api_ver=2)
|
...
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from requests.packages import urllib3
from flexget import plugin
from flexget.event import event
...
def on_task_start(self, task, config):
if config is False:
task.requests.verify = False
# Disabling verification results in a warning for every HTTPS
# request:
# "InsecureRequestWarning: Unverified HTTPS request is being made.
# Adding certificate verification is strongly advised. See:
# https://urllib3.readthedocs.io/en/latest/security.html"
# Disable those warnings because the user has explicitly disabled
# verification and the warning is not beneficial.
# This change is permanent rather than task scoped, but there won't
# be any warnings to disable when verification is enabled.
urllib3.disable_warnings()
@event('plugin.register')
...
|
0343c07262e1334e296850aee21f6702b13233e0
|
SearchResultsView/WindowClassHolder.h
|
SearchResultsView/WindowClassHolder.h
|
class WindowClassHolder
{
private:
ATOM m_WindowClass;
public:
WindowClassHolder() :
m_WindowClass(0)
{
}
WindowClassHolder(ATOM windowClass) :
m_WindowClass(windowClass)
{
}
WindowClassHolder& operator=(ATOM windowClass)
{
if (m_WindowClass != 0)
UnregisterClassW(*this, GetModuleHandleW(nullptr));
m_WindowClass = windowClass;
return *this;
}
WindowClassHolder(const WindowClassHolder&) = delete;
WindowClassHolder& operator=(const WindowClassHolder&) = delete;
inline operator ATOM() const
{
return m_WindowClass;
}
inline operator const wchar_t*() const
{
return reinterpret_cast<const wchar_t*>(m_WindowClass);
}
};
|
class WindowClassHolder
{
private:
ATOM m_WindowClass;
public:
WindowClassHolder() :
m_WindowClass(0)
{
}
WindowClassHolder(ATOM windowClass) :
m_WindowClass(windowClass)
{
}
~WindowClassHolder()
{
if (m_WindowClass != 0)
UnregisterClassW(*this, GetModuleHandleW(nullptr));
}
WindowClassHolder& operator=(ATOM windowClass)
{
this->~WindowClassHolder();
m_WindowClass = windowClass;
return *this;
}
WindowClassHolder(const WindowClassHolder&) = delete;
WindowClassHolder& operator=(const WindowClassHolder&) = delete;
inline operator ATOM() const
{
return m_WindowClass;
}
inline operator const wchar_t*() const
{
return reinterpret_cast<const wchar_t*>(m_WindowClass);
}
};
|
Fix WindowsClassHolder destructor doing nothing.
|
Fix WindowsClassHolder destructor doing nothing.
|
C
|
mit
|
TautvydasZilys/FileSystemSearch,TautvydasZilys/FileSystemSearch,TautvydasZilys/FileSystemSearch
|
c
|
## Code Before:
class WindowClassHolder
{
private:
ATOM m_WindowClass;
public:
WindowClassHolder() :
m_WindowClass(0)
{
}
WindowClassHolder(ATOM windowClass) :
m_WindowClass(windowClass)
{
}
WindowClassHolder& operator=(ATOM windowClass)
{
if (m_WindowClass != 0)
UnregisterClassW(*this, GetModuleHandleW(nullptr));
m_WindowClass = windowClass;
return *this;
}
WindowClassHolder(const WindowClassHolder&) = delete;
WindowClassHolder& operator=(const WindowClassHolder&) = delete;
inline operator ATOM() const
{
return m_WindowClass;
}
inline operator const wchar_t*() const
{
return reinterpret_cast<const wchar_t*>(m_WindowClass);
}
};
## Instruction:
Fix WindowsClassHolder destructor doing nothing.
## Code After:
class WindowClassHolder
{
private:
ATOM m_WindowClass;
public:
WindowClassHolder() :
m_WindowClass(0)
{
}
WindowClassHolder(ATOM windowClass) :
m_WindowClass(windowClass)
{
}
~WindowClassHolder()
{
if (m_WindowClass != 0)
UnregisterClassW(*this, GetModuleHandleW(nullptr));
}
WindowClassHolder& operator=(ATOM windowClass)
{
this->~WindowClassHolder();
m_WindowClass = windowClass;
return *this;
}
WindowClassHolder(const WindowClassHolder&) = delete;
WindowClassHolder& operator=(const WindowClassHolder&) = delete;
inline operator ATOM() const
{
return m_WindowClass;
}
inline operator const wchar_t*() const
{
return reinterpret_cast<const wchar_t*>(m_WindowClass);
}
};
|
...
{
}
~WindowClassHolder()
{
if (m_WindowClass != 0)
UnregisterClassW(*this, GetModuleHandleW(nullptr));
}
WindowClassHolder& operator=(ATOM windowClass)
{
this->~WindowClassHolder();
m_WindowClass = windowClass;
return *this;
}
...
|
91555cbe336706d381af22561180b751923b1330
|
cursor.all.h
|
cursor.all.h
|
// File created: 2011-09-02 23:36:23
#ifndef MUSHSPACE_CURSOR_H
#define MUSHSPACE_CURSOR_H
#include "space.all.h"
#define mushcursor MUSHSPACE_NAME(mushcursor)
// What kind of an area is the cursor in?
typedef enum MushCursorMode {
MushCursorMode_static,
MushCursorMode_dynamic,
MushCursorMode_bak,
} MushCursorMode;
#if MUSHSPACE_93
#define MUSHCURSOR_MODE(x) MushCursorMode_static
#else
#define MUSHCURSOR_MODE(x) ((x)->mode)
#endif
typedef struct mushcursor {
#if !MUSHSPACE_93
MushCursorMode mode;
#endif
mushspace *space;
mushcoords pos;
} mushcursor;
#define mushcursor_sizeof MUSHSPACE_CAT(mushcursor,_sizeof)
#define mushcursor_init MUSHSPACE_CAT(mushcursor,_init)
extern const size_t mushcursor_sizeof;
mushcursor* mushcursor_init(mushspace*, mushcoords, mushcoords, void*);
#endif
|
// File created: 2011-09-02 23:36:23
#ifndef MUSHSPACE_CURSOR_H
#define MUSHSPACE_CURSOR_H
#include "space.all.h"
#define mushcursor MUSHSPACE_NAME(mushcursor)
// What kind of an area is the cursor in?
typedef enum MushCursorMode {
MushCursorMode_static,
MushCursorMode_dynamic,
MushCursorMode_bak,
} MushCursorMode;
#if MUSHSPACE_93
#define MUSHCURSOR_MODE(x) MushCursorMode_static
#else
#define MUSHCURSOR_MODE(x) ((x)->mode)
#endif
typedef struct mushcursor {
#if !MUSHSPACE_93
MushCursorMode mode;
#endif
mushspace *space;
mushcoords pos;
#if !MUSHSPACE_93
size_t box_idx;
#endif
} mushcursor;
#define mushcursor_sizeof MUSHSPACE_CAT(mushcursor,_sizeof)
#define mushcursor_init MUSHSPACE_CAT(mushcursor,_init)
extern const size_t mushcursor_sizeof;
mushcursor* mushcursor_init(mushspace*, mushcoords, mushcoords, void*);
#endif
|
Add mushcursor.box_idx, for Funge-98 only
|
Add mushcursor.box_idx, for Funge-98 only
|
C
|
mit
|
Deewiant/mushspace,Deewiant/mushspace,Deewiant/mushspace
|
c
|
## Code Before:
// File created: 2011-09-02 23:36:23
#ifndef MUSHSPACE_CURSOR_H
#define MUSHSPACE_CURSOR_H
#include "space.all.h"
#define mushcursor MUSHSPACE_NAME(mushcursor)
// What kind of an area is the cursor in?
typedef enum MushCursorMode {
MushCursorMode_static,
MushCursorMode_dynamic,
MushCursorMode_bak,
} MushCursorMode;
#if MUSHSPACE_93
#define MUSHCURSOR_MODE(x) MushCursorMode_static
#else
#define MUSHCURSOR_MODE(x) ((x)->mode)
#endif
typedef struct mushcursor {
#if !MUSHSPACE_93
MushCursorMode mode;
#endif
mushspace *space;
mushcoords pos;
} mushcursor;
#define mushcursor_sizeof MUSHSPACE_CAT(mushcursor,_sizeof)
#define mushcursor_init MUSHSPACE_CAT(mushcursor,_init)
extern const size_t mushcursor_sizeof;
mushcursor* mushcursor_init(mushspace*, mushcoords, mushcoords, void*);
#endif
## Instruction:
Add mushcursor.box_idx, for Funge-98 only
## Code After:
// File created: 2011-09-02 23:36:23
#ifndef MUSHSPACE_CURSOR_H
#define MUSHSPACE_CURSOR_H
#include "space.all.h"
#define mushcursor MUSHSPACE_NAME(mushcursor)
// What kind of an area is the cursor in?
typedef enum MushCursorMode {
MushCursorMode_static,
MushCursorMode_dynamic,
MushCursorMode_bak,
} MushCursorMode;
#if MUSHSPACE_93
#define MUSHCURSOR_MODE(x) MushCursorMode_static
#else
#define MUSHCURSOR_MODE(x) ((x)->mode)
#endif
typedef struct mushcursor {
#if !MUSHSPACE_93
MushCursorMode mode;
#endif
mushspace *space;
mushcoords pos;
#if !MUSHSPACE_93
size_t box_idx;
#endif
} mushcursor;
#define mushcursor_sizeof MUSHSPACE_CAT(mushcursor,_sizeof)
#define mushcursor_init MUSHSPACE_CAT(mushcursor,_init)
extern const size_t mushcursor_sizeof;
mushcursor* mushcursor_init(mushspace*, mushcoords, mushcoords, void*);
#endif
|
# ... existing code ...
#endif
mushspace *space;
mushcoords pos;
#if !MUSHSPACE_93
size_t box_idx;
#endif
} mushcursor;
#define mushcursor_sizeof MUSHSPACE_CAT(mushcursor,_sizeof)
# ... rest of the code ...
|
0b3c7183e7f8543de3e9875384c5623c24279c4d
|
setup.py
|
setup.py
|
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'rsa==3.1.4',
'pyserial==2.7',
'six==1.9.0',
'websocket-client==0.32.0',
'wheel==0.24.0',
'colorama==0.3.3',
]
if sys.version_info < (3, 4, 0):
requires.append('enum34==1.0.4')
setup(name='pebble-tool',
version='3.6',
description='Tool for interacting with pebbles.',
url='https://github.com/pebble/pebble-tool',
author='Pebble Technology Corporation',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=requires,
entry_points={
'console_scripts': ['pebble=pebble_tool:run_tool'],
},
zip_safe=True)
|
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'rsa==3.1.4',
'pyserial==2.7',
'six==1.9.0',
'websocket-client==0.32.0',
'wheel==0.24.0',
'colorama==0.3.3',
]
if sys.version_info < (3, 4, 0):
requires.append('enum34==1.0.4')
setup(name='pebble-tool',
version='3.6',
description='Tool for interacting with pebbles.',
url='https://github.com/pebble/pebble-tool',
author='Pebble Technology Corporation',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
package_data={
'pebble_tool.commands.sdk': ['python'],
},
install_requires=requires,
entry_points={
'console_scripts': ['pebble=pebble_tool:run_tool'],
},
zip_safe=False)
|
Make sure our python alias is included in packaged versions.
|
Make sure our python alias is included in packaged versions.
|
Python
|
mit
|
pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool
|
python
|
## Code Before:
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'rsa==3.1.4',
'pyserial==2.7',
'six==1.9.0',
'websocket-client==0.32.0',
'wheel==0.24.0',
'colorama==0.3.3',
]
if sys.version_info < (3, 4, 0):
requires.append('enum34==1.0.4')
setup(name='pebble-tool',
version='3.6',
description='Tool for interacting with pebbles.',
url='https://github.com/pebble/pebble-tool',
author='Pebble Technology Corporation',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=requires,
entry_points={
'console_scripts': ['pebble=pebble_tool:run_tool'],
},
zip_safe=True)
## Instruction:
Make sure our python alias is included in packaged versions.
## Code After:
__author__ = 'katharine'
import sys
from setuptools import setup, find_packages
requires = [
'libpebble2==0.0.14',
'httplib2==0.9.1',
'oauth2client==1.4.12',
'progressbar2==2.7.3',
'pyasn1==0.1.8',
'pyasn1-modules==0.0.6',
'pypng==0.0.17',
'pyqrcode==1.1',
'requests==2.7.0',
'rsa==3.1.4',
'pyserial==2.7',
'six==1.9.0',
'websocket-client==0.32.0',
'wheel==0.24.0',
'colorama==0.3.3',
]
if sys.version_info < (3, 4, 0):
requires.append('enum34==1.0.4')
setup(name='pebble-tool',
version='3.6',
description='Tool for interacting with pebbles.',
url='https://github.com/pebble/pebble-tool',
author='Pebble Technology Corporation',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
package_data={
'pebble_tool.commands.sdk': ['python'],
},
install_requires=requires,
entry_points={
'console_scripts': ['pebble=pebble_tool:run_tool'],
},
zip_safe=False)
|
// ... existing code ...
author_email='[email protected]',
license='MIT',
packages=find_packages(),
package_data={
'pebble_tool.commands.sdk': ['python'],
},
install_requires=requires,
entry_points={
'console_scripts': ['pebble=pebble_tool:run_tool'],
},
zip_safe=False)
// ... rest of the code ...
|
6308603c3cde63ed79ea3c68c99b443562756244
|
src/main/java/com/kryptnostic/api/v1/client/FileStore.java
|
src/main/java/com/kryptnostic/api/v1/client/FileStore.java
|
package com.kryptnostic.api.v1.client;
import java.io.File;
import java.io.IOException;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;
/**
* A simple implementation of the client datastore. The keys are used to generate filenames.
*
* @author Nick Hewitt <[email protected]>
*
*/
public class FileStore implements DataStore {
private final File rootDirectory;
private static HashFunction hf = Hashing.murmur3_128();
public FileStore(String name) {
this.rootDirectory = new File(System.getProperty("user.home"), name);
this.rootDirectory.mkdir();
}
@Override
public byte[] get(byte[] key) throws IOException {
File keyFile = keyToFile(key);
if (keyFile.isFile()) {
byte[] data = Files.toByteArray(keyFile);
return data;
}
return null;
}
@Override
public void put(byte[] key, byte[] value) throws IOException {
File keyFile = keyToFile(key);
Files.write(value, keyFile);
}
private File keyToFile(byte[] key) {
Long longEncodedKey = hf.hashBytes(key).asLong();
return new File(rootDirectory, longEncodedKey.toString());
}
}
|
package com.kryptnostic.api.v1.client;
import java.io.File;
import java.io.IOException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;
/**
* A simple implementation of the client datastore. The keys are used to generate filenames.
*
* @author Nick Hewitt <[email protected]>
*
*/
public class FileStore implements DataStore {
private final File rootDirectory;
public FileStore(String name) {
this.rootDirectory = new File(".kryptnostic", name);
this.rootDirectory.mkdir();
}
@Override
public byte[] get(byte[] key) throws IOException {
File keyFile = keyToFile(key);
if (keyFile.isFile()) {
byte[] data = Files.toByteArray(keyFile);
return data;
}
return null;
}
@Override
public void put(byte[] key, byte[] value) throws IOException {
File keyFile = keyToFile(key);
Files.write(value, keyFile);
}
private File keyToFile(byte[] key) {
return new File(rootDirectory, Hex.encodeHexString( key ) );
}
}
|
Switch to hex encoding for key values
|
Switch to hex encoding for key values
|
Java
|
apache-2.0
|
kryptnostic/iris
|
java
|
## Code Before:
package com.kryptnostic.api.v1.client;
import java.io.File;
import java.io.IOException;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;
/**
* A simple implementation of the client datastore. The keys are used to generate filenames.
*
* @author Nick Hewitt <[email protected]>
*
*/
public class FileStore implements DataStore {
private final File rootDirectory;
private static HashFunction hf = Hashing.murmur3_128();
public FileStore(String name) {
this.rootDirectory = new File(System.getProperty("user.home"), name);
this.rootDirectory.mkdir();
}
@Override
public byte[] get(byte[] key) throws IOException {
File keyFile = keyToFile(key);
if (keyFile.isFile()) {
byte[] data = Files.toByteArray(keyFile);
return data;
}
return null;
}
@Override
public void put(byte[] key, byte[] value) throws IOException {
File keyFile = keyToFile(key);
Files.write(value, keyFile);
}
private File keyToFile(byte[] key) {
Long longEncodedKey = hf.hashBytes(key).asLong();
return new File(rootDirectory, longEncodedKey.toString());
}
}
## Instruction:
Switch to hex encoding for key values
## Code After:
package com.kryptnostic.api.v1.client;
import java.io.File;
import java.io.IOException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;
/**
* A simple implementation of the client datastore. The keys are used to generate filenames.
*
* @author Nick Hewitt <[email protected]>
*
*/
public class FileStore implements DataStore {
private final File rootDirectory;
public FileStore(String name) {
this.rootDirectory = new File(".kryptnostic", name);
this.rootDirectory.mkdir();
}
@Override
public byte[] get(byte[] key) throws IOException {
File keyFile = keyToFile(key);
if (keyFile.isFile()) {
byte[] data = Files.toByteArray(keyFile);
return data;
}
return null;
}
@Override
public void put(byte[] key, byte[] value) throws IOException {
File keyFile = keyToFile(key);
Files.write(value, keyFile);
}
private File keyToFile(byte[] key) {
return new File(rootDirectory, Hex.encodeHexString( key ) );
}
}
|
# ... existing code ...
import java.io.File;
import java.io.IOException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
# ... modified code ...
*/
public class FileStore implements DataStore {
private final File rootDirectory;
public FileStore(String name) {
this.rootDirectory = new File(".kryptnostic", name);
this.rootDirectory.mkdir();
}
...
}
private File keyToFile(byte[] key) {
return new File(rootDirectory, Hex.encodeHexString( key ) );
}
}
# ... rest of the code ...
|
0e817e574ddd4123137abe120cccb5e1a08e031c
|
test/org/callimachusproject/webdriver/pages/DigestUserEdit.java
|
test/org/callimachusproject/webdriver/pages/DigestUserEdit.java
|
package org.callimachusproject.webdriver.pages;
import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;
public class DigestUserEdit extends CalliPage {
public DigestUserEdit(WebBrowserDriver driver) {
super(driver);
}
public FileUploadForm openPhotoUpload() {
driver.click(By.cssSelector("#photo label.control-label a"));
driver.waitForScript();
driver.focusInFrame("photo");
driver.waitForScript();
final DigestUserEdit edit = this;
return new FileUploadForm(driver) {
@Override
public DigestUserEdit uploadAs(String fileName) {
driver.click(By.id("upload"));
driver.focusInFrame("photo", "save-as___");
driver.type(By.id("label"), fileName);
driver.focusInFrame("photo");
driver.click(By.xpath("(//button[@type='button'])[2]"));
return edit;
}
};
}
public CalliPage save() {
driver.click(By.id("save"));
return page();
}
}
|
package org.callimachusproject.webdriver.pages;
import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;
public class DigestUserEdit extends CalliPage {
public DigestUserEdit(WebBrowserDriver driver) {
super(driver);
}
public FileUploadForm openPhotoUpload() {
driver.click(By.cssSelector("#photo label.control-label a"));
driver.waitForScript();
driver.focusInFrame("photo");
driver.waitForScript();
final DigestUserEdit edit = this;
return new FileUploadForm(driver) {
@Override
public DigestUserEdit uploadAs(String fileName) {
driver.click(By.id("upload"));
driver.focusInFrame("photo", "save-as___");
driver.type(By.id("label"), fileName);
driver.focusInFrame("photo");
driver.click(By.xpath("(//button[@type='button'])[2]"));
return edit;
}
};
}
public CalliPage save() {
driver.focusInTopWindow();
driver.click(By.id("save"));
return page();
}
}
|
Switch focus back to top window
|
Switch focus back to top window
|
Java
|
apache-2.0
|
Thellmann/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,Thellmann/callimachus,jimmccusker/callimachus,jimmccusker/callimachus,Thellmann/callimachus,jimmccusker/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,edwardsph/callimachus,edwardsph/callimachus,Thellmann/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,jimmccusker/callimachus,edwardsph/callimachus,Thellmann/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus
|
java
|
## Code Before:
package org.callimachusproject.webdriver.pages;
import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;
public class DigestUserEdit extends CalliPage {
public DigestUserEdit(WebBrowserDriver driver) {
super(driver);
}
public FileUploadForm openPhotoUpload() {
driver.click(By.cssSelector("#photo label.control-label a"));
driver.waitForScript();
driver.focusInFrame("photo");
driver.waitForScript();
final DigestUserEdit edit = this;
return new FileUploadForm(driver) {
@Override
public DigestUserEdit uploadAs(String fileName) {
driver.click(By.id("upload"));
driver.focusInFrame("photo", "save-as___");
driver.type(By.id("label"), fileName);
driver.focusInFrame("photo");
driver.click(By.xpath("(//button[@type='button'])[2]"));
return edit;
}
};
}
public CalliPage save() {
driver.click(By.id("save"));
return page();
}
}
## Instruction:
Switch focus back to top window
## Code After:
package org.callimachusproject.webdriver.pages;
import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;
public class DigestUserEdit extends CalliPage {
public DigestUserEdit(WebBrowserDriver driver) {
super(driver);
}
public FileUploadForm openPhotoUpload() {
driver.click(By.cssSelector("#photo label.control-label a"));
driver.waitForScript();
driver.focusInFrame("photo");
driver.waitForScript();
final DigestUserEdit edit = this;
return new FileUploadForm(driver) {
@Override
public DigestUserEdit uploadAs(String fileName) {
driver.click(By.id("upload"));
driver.focusInFrame("photo", "save-as___");
driver.type(By.id("label"), fileName);
driver.focusInFrame("photo");
driver.click(By.xpath("(//button[@type='button'])[2]"));
return edit;
}
};
}
public CalliPage save() {
driver.focusInTopWindow();
driver.click(By.id("save"));
return page();
}
}
|
...
}
public CalliPage save() {
driver.focusInTopWindow();
driver.click(By.id("save"));
return page();
}
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.