Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
b722fe0d5b84eeb5c9e7279679826ff5097bfd91
contentdensity/textifai/urls.py
contentdensity/textifai/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), url(r'^general-insights$', views.general_insights, name='general-insights'), ]
Add URL mapping for general-insights page
Add URL mapping for general-insights page
Python
mit
CS326-important/space-deer,CS326-important/space-deer
- from django.conf.urls import url + from django.conf.urls import url - from . import views + from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), + url(r'^general-insights$', views.general_insights, name='general-insights'), ]
Add URL mapping for general-insights page
## Code Before: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), ] ## Instruction: Add URL mapping for general-insights page ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^textinput', views.textinput, name='textinput'), url(r'^featureoutput', views.featureoutput, name='featureoutput'), url(r'^account', views.account, name='account'), url(r'^general-insights$', views.general_insights, name='general-insights'), ]
a85beb35d7296b0a8bd5a385b44fa13fb9f178ed
imgur-clean.py
imgur-clean.py
import hashlib import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)') def get_hash(fn): with open(fn, 'rb') as fh: hashsum = hashlib.md5(fh.read()).digest() return hashsum if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) sums = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match.group(1)}.{match.group(2)}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) hashsum = get_hash(new_fn) files = sums.get(hashsum, []) files.append(new_fn) sums[hashsum] = files for hashsum, files in sums.items(): if len(files) > 1: files_quoted = [f"'{x}'" for x in files] print(f"Found duplicates: {', '.join(files_quoted)}") files.sort() for fn in files[1:]: os.remove(fn)
import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)') if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) ids = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match[1]}.{match[3]}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) id = match[2] files = ids.get(id, []) files.append(new_fn) ids[id] = files for _, files in ids.items(): if len(files) > 1: files_quoted = ', '.join(f"'{fn}'" for fn in files) print(f"Found duplicates: {files_quoted}") files.sort() for fn in files[1:]: print(f"Removing {fn}") os.remove(fn)
Remove imgur duplicates based on ID.
Remove imgur duplicates based on ID.
Python
mit
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
- import hashlib import re import os import sys - IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)') + IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)') - - def get_hash(fn): - with open(fn, 'rb') as fh: - hashsum = hashlib.md5(fh.read()).digest() - return hashsum if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) - sums = {} + ids = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue - new_fn = f'{match.group(1)}.{match.group(2)}' + new_fn = f'{match[1]}.{match[3]}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) - hashsum = get_hash(new_fn) + id = match[2] - files = sums.get(hashsum, []) + files = ids.get(id, []) files.append(new_fn) - sums[hashsum] = files + ids[id] = files - for hashsum, files in sums.items(): + for _, files in ids.items(): if len(files) > 1: - files_quoted = [f"'{x}'" for x in files] + files_quoted = ', '.join(f"'{fn}'" for fn in files) - print(f"Found duplicates: {', '.join(files_quoted)}") + print(f"Found duplicates: {files_quoted}") files.sort() for fn in files[1:]: + print(f"Removing {fn}") os.remove(fn)
Remove imgur duplicates based on ID.
## Code Before: import hashlib import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)') def get_hash(fn): with open(fn, 'rb') as fh: hashsum = hashlib.md5(fh.read()).digest() return hashsum if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) sums = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match.group(1)}.{match.group(2)}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) hashsum = get_hash(new_fn) files = sums.get(hashsum, []) files.append(new_fn) sums[hashsum] = files for hashsum, files in sums.items(): if len(files) > 1: files_quoted = [f"'{x}'" for x in files] print(f"Found duplicates: {', '.join(files_quoted)}") files.sort() for fn in files[1:]: os.remove(fn) ## Instruction: Remove imgur duplicates based on ID. ## Code After: import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)') if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) ids = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match[1]}.{match[3]}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) id = match[2] files = ids.get(id, []) files.append(new_fn) ids[id] = files for _, files in ids.items(): if len(files) > 1: files_quoted = ', '.join(f"'{fn}'" for fn in files) print(f"Found duplicates: {files_quoted}") files.sort() for fn in files[1:]: print(f"Removing {fn}") os.remove(fn)
6144ac22f7b07cb1bd322bb05391a530f128768f
tests/integration/fileserver/fileclient_test.py
tests/integration/fileserver/fileclient_test.py
''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.helpers import (ensure_in_syspath, destructiveTest) from salttesting.mock import MagicMock, patch ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient # Import Python libs import os class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.unit import skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient @skipIf(NO_MOCK, NO_MOCK_REASON) class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
Remove unused imports & Skip if no mock available
Remove unused imports & Skip if no mock available
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs + from salttesting.unit import skipIf - from salttesting.helpers import (ensure_in_syspath, destructiveTest) + from salttesting.helpers import ensure_in_syspath - from salttesting.mock import MagicMock, patch + from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient - # Import Python libs - import os - + @skipIf(NO_MOCK, NO_MOCK_REASON) class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
Remove unused imports & Skip if no mock available
## Code Before: ''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.helpers import (ensure_in_syspath, destructiveTest) from salttesting.mock import MagicMock, patch ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient # Import Python libs import os class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest) ## Instruction: Remove unused imports & Skip if no mock available ## Code After: ''' :codauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting.unit import skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient @skipIf(NO_MOCK, NO_MOCK_REASON) class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
98bdb678a9092c5c19bc2b379cca74a2ed33c457
libqtile/layout/subverttile.py
libqtile/layout/subverttile.py
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): ratio = self.ratio expand = self.expand master_windows = self.master_windows arrangement = self.arrangement class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if self.parent.arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
Refactor SubVertTile - make sublayout use the parents' variables
Refactor SubVertTile - make sublayout use the parents' variables
Python
mit
rxcomm/qtile,de-vri-es/qtile,EndPointCorp/qtile,zordsdavini/qtile,bavardage/qtile,nxnfufunezn/qtile,encukou/qtile,andrewyoung1991/qtile,ramnes/qtile,himaaaatti/qtile,de-vri-es/qtile,frostidaho/qtile,encukou/qtile,andrewyoung1991/qtile,w1ndy/qtile,frostidaho/qtile,nxnfufunezn/qtile,StephenBarnes/qtile,farebord/qtile,kopchik/qtile,rxcomm/qtile,jdowner/qtile,flacjacket/qtile,w1ndy/qtile,cortesi/qtile,aniruddhkanojia/qtile,qtile/qtile,himaaaatti/qtile,ramnes/qtile,xplv/qtile,flacjacket/qtile,soulchainer/qtile,kynikos/qtile,dequis/qtile,cortesi/qtile,jdowner/qtile,kseistrup/qtile,kiniou/qtile,apinsard/qtile,kiniou/qtile,kynikos/qtile,qtile/qtile,kopchik/qtile,kseistrup/qtile,tych0/qtile,tych0/qtile,apinsard/qtile,xplv/qtile,zordsdavini/qtile,soulchainer/qtile,dequis/qtile,farebord/qtile,aniruddhkanojia/qtile,EndPointCorp/qtile,StephenBarnes/qtile
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): - ratio = self.ratio - expand = self.expand - master_windows = self.master_windows - arrangement = self.arrangement - class MasterWindows(HorizontalStack): def filter(self, client): - return self.index_of(client) < master_windows + return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): - return self.index_of(client) >= master_windows + return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: - if arrangement == "top": + if self.parent.arrangement == "top": - rmaster, rslave = r.split_horizontal(ratio=ratio) + rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: - rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) + rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
Refactor SubVertTile - make sublayout use the parents' variables
## Code Before: from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): ratio = self.ratio expand = self.expand master_windows = self.master_windows arrangement = self.arrangement class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) ## Instruction: Refactor SubVertTile - make sublayout use the parents' variables ## Code After: from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if self.parent.arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
9a6b06d4a69bf5a7fb59d93000dc2aba02035957
tests/test_helpers.py
tests/test_helpers.py
import unittest from contextlib import redirect_stdout from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
import unittest from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
Fix redirect_stdout not available in python2.
Fix redirect_stdout not available in python2.
Python
mit
EmilStenstrom/conllu
import unittest - from contextlib import redirect_stdout from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO + try: + from contextlib import redirect_stdout + except ImportError: + import sys + import contextlib + + @contextlib.contextmanager + def redirect_stdout(target): + original = sys.stdout + sys.stdout = target + yield + sys.stdout = original class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
Fix redirect_stdout not available in python2.
## Code Before: import unittest from contextlib import redirect_stdout from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue() ## Instruction: Fix redirect_stdout not available in python2. ## Code After: import unittest from conllu import print_tree from conllu.tree_helpers import TreeNode from io import StringIO try: from contextlib import redirect_stdout except ImportError: import sys import contextlib @contextlib.contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original class TestPrintTree(unittest.TestCase): def test_print_empty_list(self): result = self._capture_print(print_tree, []) self.assertEqual(result, "") def test_print_simple_treenode(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) result = self._capture_print(print_tree, node) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n") def test_print_list_of_nodes(self): node = TreeNode(data={"id": "X", "deprel": "Y"}, children={}) nodes = [node, node] result = self._capture_print(print_tree, nodes) self.assertEqual(result, "(deprel:Y) id:X deprel:Y [X]\n" * 2) def _capture_print(self, func, args): f = StringIO() with redirect_stdout(f): func(args) return f.getvalue()
621ae7f7ff7d4b81af192ded1beec193748cfd90
rest_framework_ember/renderers.py
rest_framework_ember/renderers.py
import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) if resource_name == False: return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
Return data when ``resource_name`` == False
Return data when ``resource_name`` == False
Python
bsd-2-clause
django-json-api/django-rest-framework-json-api,aquavitae/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,coUrbanize/rest_framework_ember,abdulhaq-e/django-rest-framework-json-api,pattisdr/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,leo-naeka/rest_framework_ember,lukaslundgren/django-rest-framework-json-api,grapo/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,kaldras/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api
import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) + if resource_name == False: + return super(JSONRenderer, self).render( + data, accepted_media_type, renderer_context) + try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
Return data when ``resource_name`` == False
## Code Before: import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context) ## Instruction: Return data when ``resource_name`` == False ## Code After: import copy from rest_framework import renderers from rest_framework_ember.utils import get_resource_name class JSONRenderer(renderers.JSONRenderer): """ Render a JSON response the way Ember Data wants it. Such as: { "company": { "id": 1, "name": "nGen Works", "slug": "ngen-works", "date_created": "2014-03-13 16:33:37" } } """ def render(self, data, accepted_media_type=None, renderer_context=None): view = renderer_context.get('view') resource_name = get_resource_name(view) if resource_name == False: return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context) try: data_copy = copy.copy(data) content = data_copy.pop('results') data = {resource_name : content, "meta" : data_copy} except (TypeError, KeyError, AttributeError) as e: data = {resource_name : data} return super(JSONRenderer, self).render( data, accepted_media_type, renderer_context)
2a5cc23be491fa3f42fe039b421ad436a94d59c2
corehq/messaging/smsbackends/smsgh/views.py
corehq/messaging/smsbackends/smsgh/views.py
from corehq.apps.sms.api import incoming from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(IncomingBackendView): urlname = 'smsgh_sms_in' def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id()) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
from corehq.apps.sms.api import incoming from corehq.apps.sms.views import NewIncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(NewIncomingBackendView): urlname = 'smsgh_sms_in' @property def backend_class(self): return SQLSMSGHBackend def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id(), domain_scope=self.domain) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
Update SMSGH Backend view to be NewIncomingBackendView
Update SMSGH Backend view to be NewIncomingBackendView
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from corehq.apps.sms.api import incoming - from corehq.apps.sms.views import IncomingBackendView + from corehq.apps.sms.views import NewIncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest - class SMSGHIncomingView(IncomingBackendView): + class SMSGHIncomingView(NewIncomingBackendView): urlname = 'smsgh_sms_in' + + @property + def backend_class(self): + return SQLSMSGHBackend def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") - incoming(snr, msg, SQLSMSGHBackend.get_api_id()) + incoming(snr, msg, SQLSMSGHBackend.get_api_id(), domain_scope=self.domain) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
Update SMSGH Backend view to be NewIncomingBackendView
## Code Before: from corehq.apps.sms.api import incoming from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(IncomingBackendView): urlname = 'smsgh_sms_in' def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id()) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs) ## Instruction: Update SMSGH Backend view to be NewIncomingBackendView ## Code After: from corehq.apps.sms.api import incoming from corehq.apps.sms.views import NewIncomingBackendView from corehq.messaging.smsbackends.smsgh.models import SQLSMSGHBackend from django.http import HttpResponse, HttpResponseBadRequest class SMSGHIncomingView(NewIncomingBackendView): urlname = 'smsgh_sms_in' @property def backend_class(self): return SQLSMSGHBackend def get(self, request, api_key, *args, **kwargs): msg = request.GET.get('msg', None) snr = request.GET.get('snr', None) # We don't have a place to put this right now, but leaving it here # so we remember the parameter name in case we need it later to = request.GET.get('to', None) if not msg or not snr: return HttpResponseBadRequest("ERROR: Missing msg or snr") incoming(snr, msg, SQLSMSGHBackend.get_api_id(), domain_scope=self.domain) return HttpResponse("") def post(self, request, api_key, *args, **kwargs): return self.get(request, api_key, *args, **kwargs)
1779970872afd457336334231bef3c8629dcd375
gem/tests/test_profiles.py
gem/tests/test_profiles.py
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.user.profile.gender = 'female' self.user.profile.alias = 'useralias' self.user.profile.save() self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) print response self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) self.assertNotContains(response, 'useralias') self.assertContains(response, '<option value="f">female</option>') self.user.gem_profile.gender = 'f' self.user.profile.alias = 'useralias' self.user.gem_profile.save() self.user.profile.save() response = self.client.get(reverse('edit_my_profile')) self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
Update tests and fix the failing test
Update tests and fix the failing test
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') - self.user.profile.gender = 'female' - self.user.profile.alias = 'useralias' - self.user.profile.save() self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) - print response + self.assertNotContains(response, 'useralias') + self.assertContains(response, '<option value="f">female</option>') + self.user.gem_profile.gender = 'f' + self.user.profile.alias = 'useralias' + self.user.gem_profile.save() + self.user.profile.save() + response = self.client.get(reverse('edit_my_profile')) self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
Update tests and fix the failing test
## Code Before: from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.user.profile.gender = 'female' self.user.profile.alias = 'useralias' self.user.profile.save() self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) print response self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>') ## Instruction: Update tests and fix the failing test ## Code After: from molo.core.tests.base import MoloTestCaseMixin from django.test import TestCase, Client from django.contrib.auth.models import User from django.core.urlresolvers import reverse class GemRegistrationViewTest(TestCase, MoloTestCaseMixin): def setUp(self): self.client = Client() self.mk_main() def test_user_info_displaying_after_registration(self): self.user = User.objects.create_user( username='tester', email='tester@example.com', password='tester') self.client.login(username='tester', password='tester') response = self.client.get(reverse('edit_my_profile')) self.assertNotContains(response, 'useralias') self.assertContains(response, '<option value="f">female</option>') self.user.gem_profile.gender = 'f' self.user.profile.alias = 'useralias' self.user.gem_profile.save() self.user.profile.save() response = self.client.get(reverse('edit_my_profile')) self.assertContains(response, 'useralias') self.assertNotContains(response, '<option value="f">female</option>')
2880e0b8c38af68cfb17bbcc112f1a40b6a03a11
cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py
cinder/db/sqlalchemy/migrate_repo/versions/088_add_replication_info_to_cluster.py
from sqlalchemy import Boolean, Column, MetaData, String, Table, text def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=text('false')) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
from sqlalchemy import Boolean, Column, MetaData, String, Table from sqlalchemy.sql import expression def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=expression.false()) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
Fix cannot add a column with non-constant default
Fix cannot add a column with non-constant default With newer versions of sqlite tests are failing on sqlite3.OperationalError : Cannot add a column with non-constant default. In SQL queries is boolean without apostrophes which causes sqlite3 error. This fix is solving this issue by replacing text('false') to expression.false() from sqlalchemy.sql which is working correct. Change-Id: Ia96255a2a61994a18b21acc235931ad03a8501ea Closes-Bug: #1773123
Python
apache-2.0
openstack/cinder,mahak/cinder,mahak/cinder,openstack/cinder
- from sqlalchemy import Boolean, Column, MetaData, String, Table, text + from sqlalchemy import Boolean, Column, MetaData, String, Table + from sqlalchemy.sql import expression def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, - server_default=text('false')) + server_default=expression.false()) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
Fix cannot add a column with non-constant default
## Code Before: from sqlalchemy import Boolean, Column, MetaData, String, Table, text def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=text('false')) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id) ## Instruction: Fix cannot add a column with non-constant default ## Code After: from sqlalchemy import Boolean, Column, MetaData, String, Table from sqlalchemy.sql import expression def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=expression.false()) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
7173d3cf67bfd9a3b01f42c0832ce299c090f1d6
opendebates/tests/test_context_processors.py
opendebates/tests/test_context_processors.py
from django.core.cache import cache from django.test import TestCase from opendebates.context_processors import global_vars from opendebates.models import NUMBER_OF_VOTES_CACHE_ENTRY class NumberOfVotesTest(TestCase): def test_number_of_votes(self): cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, 2) context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
from django.test import TestCase from mock import patch from opendebates.context_processors import global_vars class NumberOfVotesTest(TestCase): def test_number_of_votes(self): with patch('opendebates.utils.cache') as mock_cache: mock_cache.get.return_value = 2 context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
Fix new test to work without cache
Fix new test to work without cache
Python
apache-2.0
ejucovy/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates
- from django.core.cache import cache from django.test import TestCase + from mock import patch from opendebates.context_processors import global_vars - from opendebates.models import NUMBER_OF_VOTES_CACHE_ENTRY class NumberOfVotesTest(TestCase): def test_number_of_votes(self): - cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, 2) + with patch('opendebates.utils.cache') as mock_cache: + mock_cache.get.return_value = 2 - context = global_vars(None) + context = global_vars(None) - self.assertEqual(2, int(context['NUMBER_OF_VOTES'])) + self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
Fix new test to work without cache
## Code Before: from django.core.cache import cache from django.test import TestCase from opendebates.context_processors import global_vars from opendebates.models import NUMBER_OF_VOTES_CACHE_ENTRY class NumberOfVotesTest(TestCase): def test_number_of_votes(self): cache.set(NUMBER_OF_VOTES_CACHE_ENTRY, 2) context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES'])) ## Instruction: Fix new test to work without cache ## Code After: from django.test import TestCase from mock import patch from opendebates.context_processors import global_vars class NumberOfVotesTest(TestCase): def test_number_of_votes(self): with patch('opendebates.utils.cache') as mock_cache: mock_cache.get.return_value = 2 context = global_vars(None) self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
3bddeade05ca5ddc799733baa1545aa2b8b68060
hoomd/tune/custom_tuner.py
hoomd/tune/custom_tuner.py
from hoomd import _hoomd from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def updater(self): return self._action @updater.setter def updater(self, updater): if isinstance(updater, Action): self._action = updater else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) super().attach(simulation) self._action.attach(simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner'
from hoomd import _hoomd from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def tuner(self): return self._action @tuner.setter def tuner(self, tuner): if isinstance(tuner, Action): self._action = tuner else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation)
Fix attaching on custom tuners
Fix attaching on custom tuners
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
from hoomd import _hoomd + from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property - def updater(self): + def tuner(self): return self._action - @updater.setter + @tuner.setter - def updater(self, updater): + def tuner(self, tuner): - if isinstance(updater, Action): + if isinstance(tuner, Action): - self._action = updater + self._action = tuner else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) - super().attach(simulation) self._action.attach(simulation) + _Operation.attach(self, simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' + def attach(self, simulation): + self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( + simulation.state._cpp_sys_def, self.trigger, self._action) + self._action.attach(simulation) + _Operation.attach(self, simulation) +
Fix attaching on custom tuners
## Code Before: from hoomd import _hoomd from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def updater(self): return self._action @updater.setter def updater(self, updater): if isinstance(updater, Action): self._action = updater else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) super().attach(simulation) self._action.attach(simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' ## Instruction: Fix attaching on custom tuners ## Code After: from hoomd import _hoomd from hoomd.operation import _Operation from hoomd.custom import ( _CustomOperation, _InternalCustomOperation, Action) from hoomd.operation import _Tuner class _TunerProperty: @property def tuner(self): return self._action @tuner.setter def tuner(self, tuner): if isinstance(tuner, Action): self._action = tuner else: raise ValueError( "updater must be an instance of hoomd.custom.Action") class CustomTuner(_CustomOperation, _TunerProperty, _Tuner): """Tuner wrapper for `hoomd.custom.Action` objects. For usage see `hoomd.custom._CustomOperation`. """ _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation) class _InternalCustomTuner( _InternalCustomOperation, _TunerProperty, _Tuner): _cpp_list_name = 'tuners' _cpp_class_name = 'PythonTuner' def attach(self, simulation): self._cpp_obj = getattr(_hoomd, self._cpp_class_name)( simulation.state._cpp_sys_def, self.trigger, self._action) self._action.attach(simulation) _Operation.attach(self, simulation)
074c83285bba8a8805bf35dec9893771220b1715
foodsaving/users/stats.py
foodsaving/users/stats.py
from django.contrib.auth import get_user_model from django.db.models import Count from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.annotate(groups_count=Count('groupmembership')).filter(groups_count=0, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
from django.contrib.auth import get_user_model from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.filter(groupmembership=None, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
Use slightly better approach to count users without groups
Use slightly better approach to count users without groups
Python
agpl-3.0
yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core
from django.contrib.auth import get_user_model - from django.db.models import Count from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { - 'active_count': - active_users_count, + 'active_count': active_users_count, - 'active_unverified_count': - active_users.filter(mail_verified=False).count(), + 'active_unverified_count': active_users.filter(mail_verified=False).count(), - 'active_ignored_email_count': - active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), + 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), - 'active_with_location_count': - active_users.exclude(latitude=None).exclude(longitude=None).count(), + 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), - 'active_with_mobile_number_count': - active_users.exclude(mobile_number='').count(), + 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), - 'active_with_description_count': - active_users.exclude(description='').count(), + 'active_with_description_count': active_users.exclude(description='').count(), - 'active_with_photo_count': - active_users.exclude(photo='').count(), + 'active_with_photo_count': active_users.exclude(photo='').count(), + 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, + 'no_membership_count': User.objects.filter(groupmembership=None, deleted=False).count(), - 'active_memberships_per_active_user_avg': - active_membership_count / active_users_count, - 'no_membership_count': - User.objects.annotate(groups_count=Count('groupmembership')).filter(groups_count=0, deleted=False).count(), - 'deleted_count': - User.objects.filter(deleted=True).count(), + 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
Use slightly better approach to count users without groups
## Code Before: from django.contrib.auth import get_user_model from django.db.models import Count from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.annotate(groups_count=Count('groupmembership')).filter(groups_count=0, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields ## Instruction: Use slightly better approach to count users without groups ## Code After: from django.contrib.auth import get_user_model from foodsaving.groups.models import GroupMembership from foodsaving.webhooks.models import EmailEvent def get_users_stats(): User = get_user_model() active_users = User.objects.filter(groupmembership__in=GroupMembership.objects.active(), deleted=False).distinct() active_membership_count = GroupMembership.objects.active().count() active_users_count = active_users.count() fields = { 'active_count': active_users_count, 'active_unverified_count': active_users.filter(mail_verified=False).count(), 'active_ignored_email_count': active_users.filter(email__in=EmailEvent.objects.ignored_addresses()).count(), 'active_with_location_count': active_users.exclude(latitude=None).exclude(longitude=None).count(), 'active_with_mobile_number_count': active_users.exclude(mobile_number='').count(), 'active_with_description_count': active_users.exclude(description='').count(), 'active_with_photo_count': active_users.exclude(photo='').count(), 'active_memberships_per_active_user_avg': active_membership_count / active_users_count, 'no_membership_count': User.objects.filter(groupmembership=None, deleted=False).count(), 'deleted_count': User.objects.filter(deleted=True).count(), } return fields
48ab9fa0e54103a08fec54d8a4d4870dc701d918
genes/systemd/commands.py
genes/systemd/commands.py
from subprocess import Popen from typing import List def systemctl(*args: List[str]): Popen(['systemctl'] + list(args)) def start(service: str): systemctl('start', service) def stop(service: str): systemctl('stop', service) def restart(service: str): systemctl('restart', service) def reload(service: str): systemctl('reload', service)
from subprocess import Popen from typing import Tuple def systemctl(*args: Tuple[str, ...]) -> None: Popen(['systemctl'] + list(args)) def disable(*services: Tuple[str, ...]) -> None: return systemctl('disable', *services) def enable(*services: Tuple[str, ...]) -> None: return systemctl('enable', *services) def start(*services: Tuple[str, ...]) -> None: return systemctl('start', *services) def stop(*services: Tuple[str, ...]) -> None: return systemctl('stop', *services) def reload(*services: Tuple[str, ...]) -> None: return systemctl('reload', *services) def restart(services: Tuple[str, ...]) -> None: return systemctl('restart', *services)
Add more functions, improve type checking
Add more functions, improve type checking
Python
mit
hatchery/genepool,hatchery/Genepool2
from subprocess import Popen - from typing import List + from typing import Tuple - def systemctl(*args: List[str]): + def systemctl(*args: Tuple[str, ...]) -> None: Popen(['systemctl'] + list(args)) - def start(service: str): + def disable(*services: Tuple[str, ...]) -> None: - systemctl('start', service) + return systemctl('disable', *services) - def stop(service: str): - systemctl('stop', service) + def enable(*services: Tuple[str, ...]) -> None: + return systemctl('enable', *services) - def restart(service: str): + def start(*services: Tuple[str, ...]) -> None: - systemctl('restart', service) + return systemctl('start', *services) - def reload(service: str): + def stop(*services: Tuple[str, ...]) -> None: - systemctl('reload', service) + return systemctl('stop', *services) + + def reload(*services: Tuple[str, ...]) -> None: + return systemctl('reload', *services) + + + def restart(services: Tuple[str, ...]) -> None: + return systemctl('restart', *services) +
Add more functions, improve type checking
## Code Before: from subprocess import Popen from typing import List def systemctl(*args: List[str]): Popen(['systemctl'] + list(args)) def start(service: str): systemctl('start', service) def stop(service: str): systemctl('stop', service) def restart(service: str): systemctl('restart', service) def reload(service: str): systemctl('reload', service) ## Instruction: Add more functions, improve type checking ## Code After: from subprocess import Popen from typing import Tuple def systemctl(*args: Tuple[str, ...]) -> None: Popen(['systemctl'] + list(args)) def disable(*services: Tuple[str, ...]) -> None: return systemctl('disable', *services) def enable(*services: Tuple[str, ...]) -> None: return systemctl('enable', *services) def start(*services: Tuple[str, ...]) -> None: return systemctl('start', *services) def stop(*services: Tuple[str, ...]) -> None: return systemctl('stop', *services) def reload(*services: Tuple[str, ...]) -> None: return systemctl('reload', *services) def restart(services: Tuple[str, ...]) -> None: return systemctl('restart', *services)
1dc1be8c5f705ff97d6b83171327fa5d1c59a385
src/utils/management/commands/run_upgrade.py
src/utils/management/commands/run_upgrade.py
from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('upgrade_module') def handle(self, *args, **options): translation.activate('en') upgrade_module_name = options.get('upgrade_module') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
Upgrade path is now not required, help text is output if no path supp.
Upgrade path is now not required, help text is output if no path supp.
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
+ import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation + from django.conf import settings + + + def get_modules(): + path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') + root, dirs, files = next(os.walk(path)) + return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ - parser.add_argument('upgrade_module') + parser.add_argument('--path', required=False) def handle(self, *args, **options): - translation.activate('en') - upgrade_module_name = options.get('upgrade_module') - upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) + if not options.get('path'): + print('No upgrade selected. Available upgrade paths: ') + for file in get_modules(): + module_name = file.split('.')[0] + print('- {module_name}'.format(module_name=module_name)) + print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') + else: + translation.activate('en') + upgrade_module_name = options.get('path') + upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) + - try: + try: - upgrade_module = import_module(upgrade_module_path) + upgrade_module = import_module(upgrade_module_path) - upgrade_module.execute() + upgrade_module.execute() - except ImportError as e: + except ImportError as e: - print('There was an error running the requested upgrade: ') + print('There was an error running the requested upgrade: ') - print(e) + print(e)
Upgrade path is now not required, help text is output if no path supp.
## Code Before: from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('upgrade_module') def handle(self, *args, **options): translation.activate('en') upgrade_module_name = options.get('upgrade_module') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) ## Instruction: Upgrade path is now not required, help text is output if no path supp. ## Code After: import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
11323a28d90ed59f32d1120224c2f63bdbed0564
learning/stock/ethstock.py
learning/stock/ethstock.py
import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) def main(): data = gettingData() print("Retrieved data:") print(data.tail()) if __name__ == "__main__": main()
import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) ''' In some cases there is no sample for a certain date. ''' #Generate all the possible days and use them to reindex start = data.index[data.index.argmin()] end = data.index[data.index.argmax()] index_complete = pd.date_range(start, end) data = data.reindex(index_complete) #Fill the blanks with the mean between the previous and the day after print("\nLooking if the index is complete...") for idx in data.index: dayloc = data.index.get_loc(idx) day = data.loc[idx] if day.hasnans: #updating rg = slice(dayloc-1, dayloc+2) data.loc[idx] = data.iloc[rg].mean() print("Day <{}> updated with the mean".format(idx)) def main(): data = gettingData() print("\nRetrieved data:") print(data.tail()) preprocessing(data) if __name__ == "__main__": main()
Index is completed if there is no sample for a date
Index is completed if there is no sample for a date
Python
mit
samuxiii/prototypes,samuxiii/prototypes
import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) + ''' + In some cases there is no sample for a certain date. + ''' + #Generate all the possible days and use them to reindex + start = data.index[data.index.argmin()] + end = data.index[data.index.argmax()] + + index_complete = pd.date_range(start, end) + data = data.reindex(index_complete) + + #Fill the blanks with the mean between the previous and the day after + print("\nLooking if the index is complete...") + for idx in data.index: + dayloc = data.index.get_loc(idx) + day = data.loc[idx] + if day.hasnans: + #updating + rg = slice(dayloc-1, dayloc+2) + data.loc[idx] = data.iloc[rg].mean() + print("Day <{}> updated with the mean".format(idx)) + def main(): data = gettingData() - print("Retrieved data:") + print("\nRetrieved data:") print(data.tail()) + + preprocessing(data) if __name__ == "__main__": main()
Index is completed if there is no sample for a date
## Code Before: import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) def main(): data = gettingData() print("Retrieved data:") print(data.tail()) if __name__ == "__main__": main() ## Instruction: Index is completed if there is no sample for a date ## Code After: import io import random import numpy as np import pandas as pd import sklearn import requests def gettingData(): url = "https://www.coingecko.com/price_charts/export/279/eur.csv" content = requests.get(url).content data = pd.read_csv(io.StringIO(content.decode('utf-8'))) return data def preprocessing(data): #customize index data.snapped_at[0].split()[0] data.snapped_at = data.snapped_at.apply(lambda x: x.split()[0]) data.set_index('snapped_at', inplace=True) data.index = pd.to_datetime(data.index) ''' In some cases there is no sample for a certain date. ''' #Generate all the possible days and use them to reindex start = data.index[data.index.argmin()] end = data.index[data.index.argmax()] index_complete = pd.date_range(start, end) data = data.reindex(index_complete) #Fill the blanks with the mean between the previous and the day after print("\nLooking if the index is complete...") for idx in data.index: dayloc = data.index.get_loc(idx) day = data.loc[idx] if day.hasnans: #updating rg = slice(dayloc-1, dayloc+2) data.loc[idx] = data.iloc[rg].mean() print("Day <{}> updated with the mean".format(idx)) def main(): data = gettingData() print("\nRetrieved data:") print(data.tail()) preprocessing(data) if __name__ == "__main__": main()
b88abd98834529f1342d69e2e91b79efd68e5e8d
backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py
backend/uclapi/dashboard/middleware/fake_shibboleth_middleware.py
from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key]
from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key] if request.GET.get("convert-get-headers") == "1": for key in request.GET: http_key = key.upper() http_key.replace("-", "_") http_key = "HTTP_" + http_key request.META[http_key] = request.GET[key]
Add get parameter parsing for fakeshibboleth auto mode
Add get parameter parsing for fakeshibboleth auto mode
Python
mit
uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi
from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key] + if request.GET.get("convert-get-headers") == "1": + for key in request.GET: + http_key = key.upper() + http_key.replace("-", "_") + http_key = "HTTP_" + http_key + request.META[http_key] = request.GET[key] +
Add get parameter parsing for fakeshibboleth auto mode
## Code Before: from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key] ## Instruction: Add get parameter parsing for fakeshibboleth auto mode ## Code After: from django.utils.deprecation import MiddlewareMixin class FakeShibbolethMiddleWare(MiddlewareMixin): def process_request(self, request): if request.POST.get("convert-post-headers") == "1": for key in request.POST: request.META[key] = request.POST[key] if request.GET.get("convert-get-headers") == "1": for key in request.GET: http_key = key.upper() http_key.replace("-", "_") http_key = "HTTP_" + http_key request.META[http_key] = request.GET[key]
2ba9eaba0bcb229055db09147f1cb654190badbf
notebooks/style_helpers.py
notebooks/style_helpers.py
import brewer2mpl import itertools from cycler import cycler cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle) cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)
import brewer2mpl from cycler import cycler N = 5 cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N] cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
Python
mit
maxalbert/paper-supplement-nanoparticle-sensing
import brewer2mpl - import itertools from cycler import cycler + N = 5 - cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False) + cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) - style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle) + style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N] cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) - style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle) + style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
## Code Before: import brewer2mpl import itertools from cycler import cycler cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle) cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle) ## Instruction: Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles. ## Code After: import brewer2mpl from cycler import cycler N = 5 cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N] cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
019d33092226d1ff8fe36897c03d25ddd48e34b1
serve.py
serve.py
import datetime as dt import sys import flask import sqlalchemy as sa import coils import tables import mapping app = flask.Flask(__name__) # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" # Connect to database engine. engine = sa.create_engine( 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name'])) Session = sa.orm.sessionmaker(bind=engine) session = Session() now = dt.datetime.now() datum = session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
import datetime as dt import sys import flask from flask.ext.sqlalchemy import SQLAlchemy import coils import mapping # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) # Initialize Flask and SQLAlchemy. app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name']) db = SQLAlchemy(app) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" now = dt.datetime.now() datum = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
Use SQLAlchemy extension in Flask app.
Use SQLAlchemy extension in Flask app.
Python
mit
vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit
import datetime as dt import sys import flask - import sqlalchemy as sa + from flask.ext.sqlalchemy import SQLAlchemy import coils - import tables import mapping - - app = flask.Flask(__name__) # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) + + # Initialize Flask and SQLAlchemy. + app = flask.Flask(__name__) + app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format( + config['username'], config['password'], + config['host'], config['db_name']) + db = SQLAlchemy(app) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" - # Connect to database engine. - engine = sa.create_engine( - 'mysql://{}:{}@{}/{}'.format( - config['username'], config['password'], - config['host'], config['db_name'])) - Session = sa.orm.sessionmaker(bind=engine) - session = Session() now = dt.datetime.now() - datum = session.query(mapping.Datum).\ + datum = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
Use SQLAlchemy extension in Flask app.
## Code Before: import datetime as dt import sys import flask import sqlalchemy as sa import coils import tables import mapping app = flask.Flask(__name__) # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" # Connect to database engine. engine = sa.create_engine( 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name'])) Session = sa.orm.sessionmaker(bind=engine) session = Session() now = dt.datetime.now() datum = session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run() ## Instruction: Use SQLAlchemy extension in Flask app. ## Code After: import datetime as dt import sys import flask from flask.ext.sqlalchemy import SQLAlchemy import coils import mapping # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) # Initialize Flask and SQLAlchemy. app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name']) db = SQLAlchemy(app) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" now = dt.datetime.now() datum = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
0b1bcf6305f808f3ed1b862a1673e774dce67879
setup.py
setup.py
from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], )
from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', install_requires=["six"], license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], )
Add six as a requirement
Add six as a requirement
Python
apache-2.0
amir-zeldes/DepEdit
from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', + install_requires=["six"], license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], ) +
Add six as a requirement
## Code Before: from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], ) ## Instruction: Add six as a requirement ## Code After: from distutils.core import setup setup( name = 'depedit', packages = ['depedit'], version = '2.1.2', description = 'A simple configurable tool for manipulating dependency trees', author = 'Amir Zeldes', author_email = 'amir.zeldes@georgetown.edu', url = 'https://github.com/amir-zeldes/depedit', install_requires=["six"], license='Apache License, Version 2.0', download_url = 'https://github.com/amir-zeldes/depedit/releases/tag/2.1.2', keywords = ['NLP', 'parsing', 'syntax', 'dependencies', 'dependency', 'tree', 'treebank', 'conll', 'conllu', 'ud'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent'], )
5c5e49797358e7020d409adf74209c0647050465
setup.py
setup.py
from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'])
from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'], classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ) )
Add classifiers for python versions
Add classifiers for python versions
Python
mit
jayhetee/fuzzywuzzy,salilnavgire/fuzzywuzzy,beni55/fuzzywuzzy,beni55/fuzzywuzzy,blakejennings/fuzzywuzzy,shalecraig/fuzzywuzzy,pombredanne/fuzzywuzzy,salilnavgire/fuzzywuzzy,pombredanne/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,medecau/fuzzywuzzy,zhahaoyu/fuzzywuzzy,zhahaoyu/fuzzywuzzy,jayhetee/fuzzywuzzy,shalecraig/fuzzywuzzy,aeeilllmrx/fuzzywuzzy,blakejennings/fuzzywuzzy
from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', - packages=['fuzzywuzzy']) + packages=['fuzzywuzzy'], + classifiers=( + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3' + ) + )
Add classifiers for python versions
## Code Before: from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy']) ## Instruction: Add classifiers for python versions ## Code After: from distutils.core import setup setup(name='fuzzywuzzy', version='0.2', description='Fuzzy string matching in python', author='Adam Cohen', author_email='adam@seatgeek.com', url='https://github.com/seatgeek/fuzzywuzzy/', packages=['fuzzywuzzy'], classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ) )
d041ab4a09da6a2181e1b14f3d0f323ed9c29c6f
applications/templatetags/applications_tags.py
applications/templatetags/applications_tags.py
from django import template from applications.models import Score register = template.Library() @register.filter def scored_by_user(value, arg): try: score = Score.objects.get(application=value, user=arg) return True if score.score else False except Score.DoesNotExist: return False @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
from django import template register = template.Library() @register.filter def scored_by_user(application, user): return application.is_scored_by_user(user) @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
Make scored_by_user filter call model method
Make scored_by_user filter call model method Ref #113
Python
bsd-3-clause
DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls
from django import template - - from applications.models import Score register = template.Library() + @register.filter - def scored_by_user(value, arg): + def scored_by_user(application, user): + return application.is_scored_by_user(user) - try: - score = Score.objects.get(application=value, user=arg) - return True if score.score else False - except Score.DoesNotExist: - return False @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
Make scored_by_user filter call model method
## Code Before: from django import template from applications.models import Score register = template.Library() @register.filter def scored_by_user(value, arg): try: score = Score.objects.get(application=value, user=arg) return True if score.score else False except Score.DoesNotExist: return False @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name) ## Instruction: Make scored_by_user filter call model method ## Code After: from django import template register = template.Library() @register.filter def scored_by_user(application, user): return application.is_scored_by_user(user) @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if '-{}'.format(name) == current_order: is_reversed = True if is_reversed: return '<a href="?order={}">▼</a>'.format(name) else: return '<a href="?order=-{}">▲</a>'.format(name)
4bf218a843c61886c910504a47cbc86c8a4982ae
bulbs/content/management/commands/migrate_to_ia.py
bulbs/content/management/commands/migrate_to_ia.py
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all() feature = options['feature'][0] if feature: feature_types.objects.filter(slug=feature) for ft in feature_types: if ft.instant_article: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all(instant_article=True) feature = options['feature'][0] if feature: feature_types = feature_types.objects.filter(slug=feature) for ft in feature_types: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
Fix migrate to ia script
Fix migrate to ia script
Python
mit
theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs
from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): - feature_types = FeatureType.objects.all() + feature_types = FeatureType.objects.all(instant_article=True) feature = options['feature'][0] if feature: - feature_types.objects.filter(slug=feature) + feature_types = feature_types.objects.filter(slug=feature) for ft in feature_types: - if ft.instant_article: - # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
Fix migrate to ia script
## Code Before: from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all() feature = options['feature'][0] if feature: feature_types.objects.filter(slug=feature) for ft in feature_types: if ft.instant_article: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id) ## Instruction: Fix migrate to ia script ## Code After: from django.core.management.base import BaseCommand from bulbs.content.models import Content, FeatureType from bulbs.content.tasks import post_to_instant_articles_api import timezone class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('feature', nargs="+", type=str) def handle(self, *args, **options): feature_types = FeatureType.objects.all(instant_article=True) feature = options['feature'][0] if feature: feature_types = feature_types.objects.filter(slug=feature) for ft in feature_types: # All published content belonging to feature type content = Content.objects.filter( feature_type=ft, published__isnull=False, published__lte=timezone.now()) for c in content: post_to_instant_articles_api.delay(c.id)
9343dbfa0d822cdf2f00deab8b18cf4d2e809063
services/display_routes.py
services/display_routes.py
from database.database_access import get_dao from gtfslib.model import Route from gtfsplugins import decret_2015_1610 from database.database_access import get_dao def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): parsedRoute = dict() parsedRoute["name"] = route.route_long_name parsedRoutes.append(parsedRoute) return parsedRoutes
from database.database_access import get_dao from gtfslib.model import Route from services.check_urban import check_urban_category def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): print(route) parsedRoute = dict() parsedRoute["id"] = route.route_id parsedRoute["name"] = route.route_long_name parsedRoute["category"] = check_urban_category(route.trips) parsedRoutes.append(parsedRoute) return parsedRoutes
Add id & category to routes list
Add id & category to routes list
Python
mit
LoveXanome/urbanbus-rest,LoveXanome/urbanbus-rest
from database.database_access import get_dao from gtfslib.model import Route + from services.check_urban import check_urban_category - from gtfsplugins import decret_2015_1610 - from database.database_access import get_dao def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): + print(route) parsedRoute = dict() + parsedRoute["id"] = route.route_id parsedRoute["name"] = route.route_long_name + parsedRoute["category"] = check_urban_category(route.trips) parsedRoutes.append(parsedRoute) return parsedRoutes
Add id & category to routes list
## Code Before: from database.database_access import get_dao from gtfslib.model import Route from gtfsplugins import decret_2015_1610 from database.database_access import get_dao def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): parsedRoute = dict() parsedRoute["name"] = route.route_long_name parsedRoutes.append(parsedRoute) return parsedRoutes ## Instruction: Add id & category to routes list ## Code After: from database.database_access import get_dao from gtfslib.model import Route from services.check_urban import check_urban_category def get_routes(agency_id): dao = get_dao(agency_id) parsedRoutes = list() for route in dao.routes(fltr=Route.route_type == Route.TYPE_BUS): print(route) parsedRoute = dict() parsedRoute["id"] = route.route_id parsedRoute["name"] = route.route_long_name parsedRoute["category"] = check_urban_category(route.trips) parsedRoutes.append(parsedRoute) return parsedRoutes
564d2eedf6e2b62152869c60bf1f3ba18287d8c0
fullcalendar/templatetags/fullcalendar.py
fullcalendar/templatetags/fullcalendar.py
from django import template from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs
from django import template from django.utils import timezone from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.simple_tag def occurrence_duration(occurrence): start = timezone.localtime(occurrence.start_time) end = timezone.localtime(occurrence.end_time) result = start.strftime('%A, %d %B %Y %H:%M') if (start.day == end.day and start.month == end.month and start.year == end.year): result += ' - {:%H:%M}'.format(end) else: result += ' - {:%A, %d %B %Y %H:%M}'.format(end) return result
Add extra tag which displays the occurrence duration in a smart way
Add extra tag which displays the occurrence duration in a smart way
Python
mit
jonge-democraten/mezzanine-fullcalendar
from django import template + from django.utils import timezone from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs + @register.simple_tag + def occurrence_duration(occurrence): + start = timezone.localtime(occurrence.start_time) + end = timezone.localtime(occurrence.end_time) + result = start.strftime('%A, %d %B %Y %H:%M') + if (start.day == end.day and start.month == end.month and + start.year == end.year): + result += ' - {:%H:%M}'.format(end) + else: + result += ' - {:%A, %d %B %Y %H:%M}'.format(end) + + return result +
Add extra tag which displays the occurrence duration in a smart way
## Code Before: from django import template from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs ## Instruction: Add extra tag which displays the occurrence duration in a smart way ## Code After: from django import template from django.utils import timezone from fullcalendar.models import Occurrence register = template.Library() @register.inclusion_tag('events/agenda_tag.html') def show_agenda(*args, **kwargs): qs = Occurrence.objects.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs, 'all_sites': True, } @register.assignment_tag def get_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.inclusion_tag('events/agenda_tag.html') def show_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: qs = qs[:int(kwargs['limit'])] return { 'occurrences': qs } @register.assignment_tag def get_site_agenda(*args, **kwargs): qs = Occurrence.site_related.upcoming() if 'limit' in kwargs: return qs[:int(kwargs['limit'])] return qs @register.simple_tag def occurrence_duration(occurrence): start = timezone.localtime(occurrence.start_time) end = timezone.localtime(occurrence.end_time) result = start.strftime('%A, %d %B %Y %H:%M') if (start.day == end.day and start.month == end.month and start.year == end.year): result += ' - {:%H:%M}'.format(end) else: result += ' - {:%A, %d %B %Y %H:%M}'.format(end) return result
27f47ef27654dfa9c68bb90d3b8fae2e3a281396
pitchfork/__init__.py
pitchfork/__init__.py
from flask import Flask, g from happymongo import HapPyMongo from config import config from adminbp import bp as admin_bp from manage_globals import bp as manage_bp from engine import bp as engine_bp from inspect import getmembers, isfunction import context_functions import views import template_filters app = Flask(__name__) app.config.from_object(config) app.register_blueprint(admin_bp, url_prefix='/admin') app.register_blueprint(manage_bp, url_prefix='/manage') app.register_blueprint(engine_bp, url_prefix='/engine') # Setup DB based on the app name mongo, db = HapPyMongo(config) custom_filters = { name: function for name, function in getmembers(template_filters) if isfunction(function) } app.jinja_env.filters.update(custom_filters) app.context_processor(context_functions.utility_processor) views.ProductsView.register(app) views.MiscView.register(app) @app.before_request def before_request(): g.db = db
import setup_application app, db = setup_application.create_app()
Move out app setup to setup file to finish cleaning up the init file
Move out app setup to setup file to finish cleaning up the init file
Python
apache-2.0
rackerlabs/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork
+ import setup_application - from flask import Flask, g - from happymongo import HapPyMongo - from config import config - from adminbp import bp as admin_bp - from manage_globals import bp as manage_bp - from engine import bp as engine_bp - from inspect import getmembers, isfunction + app, db = setup_application.create_app() - import context_functions - import views - import template_filters - - app = Flask(__name__) - app.config.from_object(config) - app.register_blueprint(admin_bp, url_prefix='/admin') - app.register_blueprint(manage_bp, url_prefix='/manage') - app.register_blueprint(engine_bp, url_prefix='/engine') - - # Setup DB based on the app name - mongo, db = HapPyMongo(config) - custom_filters = { - name: function for name, function in getmembers(template_filters) - if isfunction(function) - } - app.jinja_env.filters.update(custom_filters) - app.context_processor(context_functions.utility_processor) - - views.ProductsView.register(app) - views.MiscView.register(app) - - - @app.before_request - def before_request(): - g.db = db -
Move out app setup to setup file to finish cleaning up the init file
## Code Before: from flask import Flask, g from happymongo import HapPyMongo from config import config from adminbp import bp as admin_bp from manage_globals import bp as manage_bp from engine import bp as engine_bp from inspect import getmembers, isfunction import context_functions import views import template_filters app = Flask(__name__) app.config.from_object(config) app.register_blueprint(admin_bp, url_prefix='/admin') app.register_blueprint(manage_bp, url_prefix='/manage') app.register_blueprint(engine_bp, url_prefix='/engine') # Setup DB based on the app name mongo, db = HapPyMongo(config) custom_filters = { name: function for name, function in getmembers(template_filters) if isfunction(function) } app.jinja_env.filters.update(custom_filters) app.context_processor(context_functions.utility_processor) views.ProductsView.register(app) views.MiscView.register(app) @app.before_request def before_request(): g.db = db ## Instruction: Move out app setup to setup file to finish cleaning up the init file ## Code After: import setup_application app, db = setup_application.create_app()
16d6dd0ba2b5218d211c25e3e197d65fe163b09a
helusers/providers/helsinki_oidc/views.py
helusers/providers/helsinki_oidc/views.py
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso-test/openid/token/' authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/' profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso/openid/token/' authorize_url = 'https://api.hel.fi/sso/openid/authorize/' profile_url = 'https://api.hel.fi/sso/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
Fix broken Helsinki OIDC provider links
Fix broken Helsinki OIDC provider links
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id - access_token_url = 'https://api.hel.fi/sso-test/openid/token/' + access_token_url = 'https://api.hel.fi/sso/openid/token/' - authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/' + authorize_url = 'https://api.hel.fi/sso/openid/authorize/' - profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/' + profile_url = 'https://api.hel.fi/sso/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
Fix broken Helsinki OIDC provider links
## Code Before: import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso-test/openid/token/' authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/' profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter) ## Instruction: Fix broken Helsinki OIDC provider links ## Code After: import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso/openid/token/' authorize_url = 'https://api.hel.fi/sso/openid/authorize/' profile_url = 'https://api.hel.fi/sso/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
3e280e64874d1a68b6bc5fc91a8b6b28968b74e3
meinberlin/apps/dashboard2/contents.py
meinberlin/apps/dashboard2/contents.py
class DashboardContents: _registry = {} content = DashboardContents()
class DashboardContents: _registry = {'project': {}, 'module': {}} def __getitem__(self, identifier): component = self._registry['project'].get(identifier, None) if not component: component = self._registry['module'].get(identifier) return component def __contains__(self, identifier): return (identifier in self._registry['project'] or identifier in self._registry['module']) def register_project(self, component): self._registry['project'][component.identifier] = component def register_module(self, component): self._registry['module'][component.identifier] = component def get_project_components(self): return self._registry['project'].items() def get_module_components(self): return self._registry['module'].items() content = DashboardContents()
Store project and module componentes separately
Store project and module componentes separately
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
class DashboardContents: - _registry = {} + _registry = {'project': {}, 'module': {}} + + def __getitem__(self, identifier): + component = self._registry['project'].get(identifier, None) + if not component: + component = self._registry['module'].get(identifier) + return component + + def __contains__(self, identifier): + return (identifier in self._registry['project'] or + identifier in self._registry['module']) + + def register_project(self, component): + self._registry['project'][component.identifier] = component + + def register_module(self, component): + self._registry['module'][component.identifier] = component + + def get_project_components(self): + return self._registry['project'].items() + + def get_module_components(self): + return self._registry['module'].items() content = DashboardContents()
Store project and module componentes separately
## Code Before: class DashboardContents: _registry = {} content = DashboardContents() ## Instruction: Store project and module componentes separately ## Code After: class DashboardContents: _registry = {'project': {}, 'module': {}} def __getitem__(self, identifier): component = self._registry['project'].get(identifier, None) if not component: component = self._registry['module'].get(identifier) return component def __contains__(self, identifier): return (identifier in self._registry['project'] or identifier in self._registry['module']) def register_project(self, component): self._registry['project'][component.identifier] = component def register_module(self, component): self._registry['module'][component.identifier] = component def get_project_components(self): return self._registry['project'].items() def get_module_components(self): return self._registry['module'].items() content = DashboardContents()
d7c41853277c1df53192b2f879f47f75f3c62fd5
server/covmanager/urls.py
server/covmanager/urls.py
from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), )
from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', views.index, name='index'), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), )
Add redirect for / to collections
[CovManager] Add redirect for / to collections
Python
mpl-2.0
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), + url(r'^$', views.index, name='index'), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), ) +
Add redirect for / to collections
## Code Before: from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), ) ## Instruction: Add redirect for / to collections ## Code After: from django.conf.urls import patterns, include, url from rest_framework import routers from covmanager import views router = routers.DefaultRouter() router.register(r'collections', views.CollectionViewSet, base_name='collections') router.register(r'repositories', views.RepositoryViewSet, base_name='repositories') urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', views.index, name='index'), url(r'^repositories/', views.repositories, name="repositories"), url(r'^collections/$', views.collections, name="collections"), url(r'^collections/api/$', views.CollectionViewSet.as_view({'get': 'list'}), name="collections_api"), url(r'^collections/(?P<collectionid>\d+)/browse/$', views.collections_browse, name="collections_browse"), url(r'^collections/(?P<collectionid>\d+)/browse/api/(?P<path>.*)', views.collections_browse_api, name="collections_browse_api"), url(r'^rest/', include(router.urls)), )
9940a61cd7dbe9b66dcd4c7e07f967e53d2951d4
pybossa/auth/token.py
pybossa/auth/token.py
from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token=None): return False def delete(token=None): return False
from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token): return False def delete(token): return False
Change signature to match other resources auth functions
Change signature to match other resources auth functions
Python
agpl-3.0
geotagx/pybossa,jean/pybossa,stefanhahmann/pybossa,harihpr/tweetclickers,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,Scifabric/pybossa,geotagx/pybossa,jean/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,OpenNewsLabs/pybossa,inteligencia-coletiva-lsd/pybossa,PyBossa/pybossa
from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() - def update(token=None): + def update(token): return False - def delete(token=None): + def delete(token): return False
Change signature to match other resources auth functions
## Code Before: from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token=None): return False def delete(token=None): return False ## Instruction: Change signature to match other resources auth functions ## Code After: from flask.ext.login import current_user def create(token=None): return False def read(token=None): return not current_user.is_anonymous() def update(token): return False def delete(token): return False
6fe48fc7499327d27f69204b7f8ec927fc975177
python/lexPythonMQ.py
python/lexPythonMQ.py
import tokenize; import zmq; context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://lo:32132") while True: # Wait for next request from client message = socket.recv()
import re, sys, tokenize, zmq; from StringIO import StringIO def err(msg): sys.err.write(str(msg) + '\n') class LexPyMQ(object): def __init__(self): self.zctx = zmq.Context() self.socket = self.zctx.socket(zmq.REP) def run(self): self.socket.bind("tcp://lo:32132") while True: msg = self.socket.recv_json(0) # there are definitely new lines in the code if not msg.get('python'): err('received non-python code') code = msg.get('body', '') self.socket.send_json(tokenize.generate_tokens(StringIO(code))) if __name__ == '__main__': LexPyMQ().run()
Implement python lexer ZMQ service.
Implement python lexer ZMQ service.
Python
agpl-3.0
orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,abramhindle/UnnaturalCodeFork,orezpraw/estimate-charm,naturalness/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork,naturalness/unnaturalcode,abramhindle/UnnaturalCodeFork
- import tokenize; - import zmq; + import re, sys, tokenize, zmq; + from StringIO import StringIO - context = zmq.Context() - socket = context.socket(zmq.REP) - socket.bind("tcp://lo:32132") + def err(msg): + sys.err.write(str(msg) + '\n') + + class LexPyMQ(object): + def __init__(self): + self.zctx = zmq.Context() + self.socket = self.zctx.socket(zmq.REP) + + def run(self): + self.socket.bind("tcp://lo:32132") + - while True: + while True: - # Wait for next request from client - message = socket.recv() + msg = self.socket.recv_json(0) + # there are definitely new lines in the code + if not msg.get('python'): + err('received non-python code') + code = msg.get('body', '') + self.socket.send_json(tokenize.generate_tokens(StringIO(code))) + + if __name__ == '__main__': + LexPyMQ().run() +
Implement python lexer ZMQ service.
## Code Before: import tokenize; import zmq; context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://lo:32132") while True: # Wait for next request from client message = socket.recv() ## Instruction: Implement python lexer ZMQ service. ## Code After: import re, sys, tokenize, zmq; from StringIO import StringIO def err(msg): sys.err.write(str(msg) + '\n') class LexPyMQ(object): def __init__(self): self.zctx = zmq.Context() self.socket = self.zctx.socket(zmq.REP) def run(self): self.socket.bind("tcp://lo:32132") while True: msg = self.socket.recv_json(0) # there are definitely new lines in the code if not msg.get('python'): err('received non-python code') code = msg.get('body', '') self.socket.send_json(tokenize.generate_tokens(StringIO(code))) if __name__ == '__main__': LexPyMQ().run()
15de2fe886c52f0900deeb519f944d22bb5c6db4
mysite/project/views.py
mysite/project/views.py
from mysite.search.models import Project from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 def project(request, project__name = None): p = Project.objects.get(name=project__name) return render_to_response('project/project.html', { 'the_user': request.user, 'project': p, 'contributors': p.get_contributors() } )
from mysite.search.models import Project import django.template import mysite.base.decorators from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 @mysite.base.decorators.view def project(request, project__name = None): p = Project.objects.get(name=project__name) return (request, 'project/project.html', { 'project': p, 'contributors': p.get_contributors() }, )
Use the @view decorator to ensure that the project page gets user data.
Use the @view decorator to ensure that the project page gets user data.
Python
agpl-3.0
onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,sudheesh001/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,SnappleCap/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,sudheesh001/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,Changaco/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,campbe13/openhatch,mzdaniel/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,onceuponatimeforever/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,heeraj123/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,moijes12/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,Changaco/oh-mainline,moijes12/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,willingc/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,moijes12/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline
from mysite.search.models import Project + import django.template + import mysite.base.decorators from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 + @mysite.base.decorators.view def project(request, project__name = None): p = Project.objects.get(name=project__name) - return render_to_response('project/project.html', + return (request, + 'project/project.html', { - 'the_user': request.user, 'project': p, 'contributors': p.get_contributors() - } + }, )
Use the @view decorator to ensure that the project page gets user data.
## Code Before: from mysite.search.models import Project from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 def project(request, project__name = None): p = Project.objects.get(name=project__name) return render_to_response('project/project.html', { 'the_user': request.user, 'project': p, 'contributors': p.get_contributors() } ) ## Instruction: Use the @view decorator to ensure that the project page gets user data. ## Code After: from mysite.search.models import Project import django.template import mysite.base.decorators from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 @mysite.base.decorators.view def project(request, project__name = None): p = Project.objects.get(name=project__name) return (request, 'project/project.html', { 'project': p, 'contributors': p.get_contributors() }, )
fa14c040e6483087f5b2c78bc1a7aeee9ad2274a
Instanssi/kompomaatti/misc/time_formatting.py
Instanssi/kompomaatti/misc/time_formatting.py
import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo
import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo def competition_times_formatter(competition): competition.start_time = awesometime.format_single(competition.start) competition.participation_end_time = awesometime.format_single(competition.participation_end) return competition
Add time formatter for competitions
kompomaatti: Add time formatter for competitions
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo + def competition_times_formatter(competition): + competition.start_time = awesometime.format_single(competition.start) + competition.participation_end_time = awesometime.format_single(competition.participation_end) + return competition +
Add time formatter for competitions
## Code Before: import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo ## Instruction: Add time formatter for competitions ## Code After: import awesometime def compo_times_formatter(compo): compo.compo_time = awesometime.format_single(compo.compo_start) compo.adding_time = awesometime.format_single(compo.adding_end) compo.editing_time = awesometime.format_single(compo.editing_end) compo.voting_time = awesometime.format_between(compo.voting_start, compo.voting_end) return compo def competition_times_formatter(competition): competition.start_time = awesometime.format_single(competition.start) competition.participation_end_time = awesometime.format_single(competition.participation_end) return competition
ae78bd758c690e28abaae2c07e8a3890e76044e0
pylearn2/scripts/papers/maxout/tests/test_mnist.py
pylearn2/scripts/papers/maxout/tests/test_mnist.py
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.main_loop()
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.algorithm._set_monitoring_dataset(train.dataset) train.main_loop()
Allow papers/maxout to be tested without MNIST data
Allow papers/maxout to be tested without MNIST data
Python
bsd-3-clause
KennethPierce/pylearnk,KennethPierce/pylearnk,Refefer/pylearn2,JesseLivezey/plankton,goodfeli/pylearn2,theoryno3/pylearn2,alexjc/pylearn2,pkainz/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,alexjc/pylearn2,kastnerkyle/pylearn2,ddboline/pylearn2,se4u/pylearn2,hantek/pylearn2,jeremyfix/pylearn2,nouiz/pylearn2,abergeron/pylearn2,sandeepkbhat/pylearn2,chrish42/pylearn,msingh172/pylearn2,caidongyun/pylearn2,fulmicoton/pylearn2,Refefer/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,mclaughlin6464/pylearn2,hantek/pylearn2,sandeepkbhat/pylearn2,fyffyt/pylearn2,bartvm/pylearn2,fulmicoton/pylearn2,jamessergeant/pylearn2,se4u/pylearn2,mkraemer67/pylearn2,TNick/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,hyqneuron/pylearn2-maxsom,woozzu/pylearn2,CIFASIS/pylearn2,pombredanne/pylearn2,fishcorn/pylearn2,JesseLivezey/pylearn2,ashhher3/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,lisa-lab/pylearn2,pombredanne/pylearn2,daemonmaker/pylearn2,ddboline/pylearn2,junbochen/pylearn2,JesseLivezey/plankton,hantek/pylearn2,msingh172/pylearn2,ashhher3/pylearn2,ddboline/pylearn2,matrogers/pylearn2,abergeron/pylearn2,ashhher3/pylearn2,shiquanwang/pylearn2,goodfeli/pylearn2,pombredanne/pylearn2,nouiz/pylearn2,nouiz/pylearn2,matrogers/pylearn2,cosmoharrigan/pylearn2,kastnerkyle/pylearn2,shiquanwang/pylearn2,kose-y/pylearn2,aalmah/pylearn2,abergeron/pylearn2,junbochen/pylearn2,w1kke/pylearn2,fyffyt/pylearn2,daemonmaker/pylearn2,fyffyt/pylearn2,skearnes/pylearn2,JesseLivezey/plankton,mclaughlin6464/pylearn2,nouiz/pylearn2,hantek/pylearn2,se4u/pylearn2,lamblin/pylearn2,ddboline/pylearn2,lisa-lab/pylearn2,kastnerkyle/pylearn2,aalmah/pylearn2,lamblin/pylearn2,theoryno3/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,JesseLivezey/plankton,shiquanwang/pylearn2,chrish42/pylearn,CIFASIS/pylearn2,chrish42/pylearn,mclaughlin6464/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,lisa-lab/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,matrogers/pylearn2,mkraemer67/pylearn2,theoryno3/pylearn2,junbochen/pylearn2,daemonmaker/pylearn2,pkainz/pylearn2,theoryno3/pylearn2,CIFASIS/pylearn2,cosmoharrigan/pylearn2,jeremyfix/pylearn2,caidongyun/pylearn2,bartvm/pylearn2,se4u/pylearn2,kose-y/pylearn2,msingh172/pylearn2,KennethPierce/pylearnk,hyqneuron/pylearn2-maxsom,hyqneuron/pylearn2-maxsom,fishcorn/pylearn2,KennethPierce/pylearnk,fyffyt/pylearn2,kose-y/pylearn2,jamessergeant/pylearn2,lancezlin/pylearn2,caidongyun/pylearn2,lamblin/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,fishcorn/pylearn2,fulmicoton/pylearn2,w1kke/pylearn2,caidongyun/pylearn2,CIFASIS/pylearn2,msingh172/pylearn2,pkainz/pylearn2,Refefer/pylearn2,aalmah/pylearn2,chrish42/pylearn,pkainz/pylearn2,bartvm/pylearn2,woozzu/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,pombredanne/pylearn2,jeremyfix/pylearn2,Refefer/pylearn2,lunyang/pylearn2,lisa-lab/pylearn2,JesseLivezey/pylearn2,skearnes/pylearn2,lunyang/pylearn2,TNick/pylearn2,goodfeli/pylearn2,kose-y/pylearn2,woozzu/pylearn2,lancezlin/pylearn2,fishcorn/pylearn2,aalmah/pylearn2,lamblin/pylearn2,daemonmaker/pylearn2,kastnerkyle/pylearn2,JesseLivezey/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,lunyang/pylearn2,woozzu/pylearn2,abergeron/pylearn2,w1kke/pylearn2,cosmoharrigan/pylearn2,alexjc/pylearn2,TNick/pylearn2,mkraemer67/pylearn2,w1kke/pylearn2
import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file + def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) - train.algorithm.termination_criterion = EpochCounter(max_epochs=1) + train.algorithm._set_monitoring_dataset(train.dataset) train.main_loop()
Allow papers/maxout to be tested without MNIST data
## Code Before: import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.main_loop() ## Instruction: Allow papers/maxout to be tested without MNIST data ## Code After: import os import numpy as np import pylearn2 from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.termination_criteria import EpochCounter from pylearn2.utils.serial import load_train_file def test_mnist(): """ Test the mnist.yaml file from the dropout paper on random input """ train = load_train_file(os.path.join(pylearn2.__path__[0], "scripts/papers/maxout/mnist.yaml")) random_X = np.random.rand(10, 784) random_y = np.random.randint(0, 10, (10, 1)) train.dataset = DenseDesignMatrix(X=random_X, y=random_y, y_labels=10) train.algorithm.termination_criterion = EpochCounter(max_epochs=1) train.algorithm._set_monitoring_dataset(train.dataset) train.main_loop()
a79a3f7c42c858ae42c618479654cd7589de05b9
zeeko/utils/tests/test_hmap.py
zeeko/utils/tests/test_hmap.py
import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)] @pytest.mark.skip def test_hmap(items): """docstring for test""" h = HashMap(10) if len(items): with pytest.raises(KeyError): h[items[0]] for item in items: h.add(item) assert len(h) == len(items) for i, item in enumerate(items): assert h[item] == i assert repr(h) == "HashMap({0!r})".format(items) if len(items): item = items[0] del h[item] assert len(h) == len(items) - 1 assert item not in h
import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)]
Remove unused tests for hash map
Remove unused tests for hash map
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)] - @pytest.mark.skip - def test_hmap(items): - """docstring for test""" - h = HashMap(10) - if len(items): - with pytest.raises(KeyError): - h[items[0]] - - for item in items: - h.add(item) - assert len(h) == len(items) - for i, item in enumerate(items): - assert h[item] == i - - assert repr(h) == "HashMap({0!r})".format(items) - - if len(items): - item = items[0] - - del h[item] - assert len(h) == len(items) - 1 - assert item not in h - +
Remove unused tests for hash map
## Code Before: import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)] @pytest.mark.skip def test_hmap(items): """docstring for test""" h = HashMap(10) if len(items): with pytest.raises(KeyError): h[items[0]] for item in items: h.add(item) assert len(h) == len(items) for i, item in enumerate(items): assert h[item] == i assert repr(h) == "HashMap({0!r})".format(items) if len(items): item = items[0] del h[item] assert len(h) == len(items) - 1 assert item not in h ## Instruction: Remove unused tests for hash map ## Code After: import pytest from ..hmap import HashMap @pytest.fixture(params=[0,1,5,9]) def n(request): """Number of items""" return request.param @pytest.fixture def items(n): """A list of strings.""" return ["item{0:d}".format(i) for i in range(n)]
311a858ecbe7d34f9f68a18a3735db9da8b0e692
tests/utils.py
tests/utils.py
import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') chrome = webdriver.Chrome(chrome_options=options) atexit.register(chrome.quit) chrome.delete_all_cookies() chrome.switch_to.default_content() return chrome def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') test_driver = webdriver.Chrome(chrome_options=options) atexit.register(test_driver.quit) test_driver.delete_all_cookies() test_driver.switch_to.default_content() return test_driver def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
Fix global test driver initialization
Fix global test driver initialization
Python
mit
alisaifee/holmium.core,alisaifee/holmium.core,alisaifee/holmium.core,alisaifee/holmium.core
import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') - chrome = webdriver.Chrome(chrome_options=options) + test_driver = webdriver.Chrome(chrome_options=options) - atexit.register(chrome.quit) + atexit.register(test_driver.quit) - chrome.delete_all_cookies() + test_driver.delete_all_cookies() - chrome.switch_to.default_content() + test_driver.switch_to.default_content() - return chrome + return test_driver def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
Fix global test driver initialization
## Code Before: import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') chrome = webdriver.Chrome(chrome_options=options) atexit.register(chrome.quit) chrome.delete_all_cookies() chrome.switch_to.default_content() return chrome def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open") ## Instruction: Fix global test driver initialization ## Code After: import atexit import tempfile import sys import mock from selenium import webdriver import os def build_mock_mapping(name): mock_driver = mock.Mock() browser_mapping = {name: mock_driver} mock_driver.return_value.name = name return browser_mapping test_driver = None def get_driver(): global test_driver if not test_driver: options = webdriver.ChromeOptions() options.add_argument('headless') test_driver = webdriver.Chrome(chrome_options=options) atexit.register(test_driver.quit) test_driver.delete_all_cookies() test_driver.switch_to.default_content() return test_driver def make_temp_page(src): f = tempfile.mktemp(".html") fh = open(f, "w") fh.write(src.replace("\n", "")) fh.close() atexit.register(lambda: os.remove(f)) return "file://%s" % f def mock_open(): if sys.version_info >= (3, 0, 0): return mock.patch("builtins.open") return mock.patch("__builtin__.open")
17015ecf48ec37909de6de2c299454fc89b592e9
tests/test_gmaps.py
tests/test_gmaps.py
from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42)) def test_url_dict_no_zoom(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78)))
Add failing test for URL without zoom
Add failing test for URL without zoom
Python
mit
bfontaine/jinja2_maps
from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42)) + def test_url_dict_no_zoom(self): + url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z" + self.assertEquals(url, + gmaps_url(dict(latitude=12.34, longitude=56.78))) +
Add failing test for URL without zoom
## Code Before: from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42)) ## Instruction: Add failing test for URL without zoom ## Code After: from base import TestCase from jinja2_maps.gmaps import gmaps_url class TestGmaps(TestCase): def test_url_dict(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42)) def test_url_dict_no_zoom(self): url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z" self.assertEquals(url, gmaps_url(dict(latitude=12.34, longitude=56.78)))
3c735d18bdcff28bbdd765b131649ba57fb612b0
hy/models/string.py
hy/models/string.py
from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ def __new__(cls, value): obj = str_type.__new__(cls, value) return obj
from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ pass
Revert "Revert "Remove useless code""
Revert "Revert "Remove useless code"" This reverts commit 262da59c7790cdadd60ea9612bc9e3c1616863fd. Conflicts: hy/models/string.py
Python
mit
ALSchwalm/hy,aisk/hy,paultag/hy,tianon/hy,hcarvalhoalves/hy,Foxboron/hy,Tritlo/hy,mtmiller/hy,michel-slm/hy,farhaven/hy,freezas/hy,zackmdavis/hy,tianon/hy,gilch/hy,aisk/hy,larme/hy,tuturto/hy,timmartin/hy,farhaven/hy,kirbyfan64/hy,farhaven/hy,algernon/hy,Foxboron/hy,hcarvalhoalves/hy,kirbyfan64/hy,adamfeuer/hy,jakirkham/hy,tianon/hy,larme/hy,larme/hy,kartikm/hy,aisk/hy
from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ + pass - def __new__(cls, value): - obj = str_type.__new__(cls, value) - return obj -
Revert "Revert "Remove useless code""
## Code Before: from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ def __new__(cls, value): obj = str_type.__new__(cls, value) return obj ## Instruction: Revert "Revert "Remove useless code"" ## Code After: from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ pass
60870a3e471637d44da32f3aac74064e4ca60208
pyplot.py
pyplot.py
import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts' ) module_subparser = {} for module_str in plotter.__all__: module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() from plotter.plotn import main main(args)
import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts', dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() args.run(args)
Use `set_defaults` of subparser to launch scripts
Use `set_defaults` of subparser to launch scripts
Python
mit
DerWeh/pyplot
import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', - description = 'available plotting scripts' + description = 'available plotting scripts', + dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: - module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) + module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) + module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() - from plotter.plotn import main - main(args) + args.run(args)
Use `set_defaults` of subparser to launch scripts
## Code Before: import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts' ) module_subparser = {} for module_str in plotter.__all__: module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() from plotter.plotn import main main(args) ## Instruction: Use `set_defaults` of subparser to launch scripts ## Code After: import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts', dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() args.run(args)
aac598d64fc0fa50cc068fc50173068e5d89b3fd
segpy/ext/numpyext.py
segpy/ext/numpyext.py
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'l': numpy.dtype('i4'), 'h': numpy.dtype('i2'), 'f': numpy.dtype('f4'), 'b': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'int32': numpy.dtype('i4'), 'int16': numpy.dtype('i2'), 'float32': numpy.dtype('f4'), 'int8': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
Update numpy dtypes extension for correct type codes.
Update numpy dtypes extension for correct type codes.
Python
agpl-3.0
hohogpb/segpy,stevejpurves/segpy,abingham/segpy,asbjorn/segpy,kjellkongsvik/segpy,Kramer477/segpy,kwinkunks/segpy
"""Optional interoperability with Numpy.""" import numpy - NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), + NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), - 'l': numpy.dtype('i4'), + 'int32': numpy.dtype('i4'), - 'h': numpy.dtype('i2'), + 'int16': numpy.dtype('i2'), - 'f': numpy.dtype('f4'), + 'float32': numpy.dtype('f4'), - 'b': numpy.dtype('i1')} + 'int8': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
Update numpy dtypes extension for correct type codes.
## Code Before: """Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'l': numpy.dtype('i4'), 'h': numpy.dtype('i2'), 'f': numpy.dtype('f4'), 'b': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format)) ## Instruction: Update numpy dtypes extension for correct type codes. ## Code After: """Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'int32': numpy.dtype('i4'), 'int16': numpy.dtype('i2'), 'float32': numpy.dtype('f4'), 'int8': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
2ba28c83de33ebc75f386d127d0c55e17248a94b
mapclientplugins/meshgeneratorstep/__init__.py
mapclientplugins/meshgeneratorstep/__init__.py
__version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = '' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
__version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = 'https://github.com/ABI-Software/mapclientplugins.meshgeneratorstep' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
Add location to step metadata.
Add location to step metadata.
Python
apache-2.0
rchristie/mapclientplugins.meshgeneratorstep
__version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' - __location__ = '' + __location__ = 'https://github.com/ABI-Software/mapclientplugins.meshgeneratorstep' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc +
Add location to step metadata.
## Code Before: __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = '' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc ## Instruction: Add location to step metadata. ## Code After: __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = 'https://github.com/ABI-Software/mapclientplugins.meshgeneratorstep' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
0f49230309ac115ff78eddd36bcd153d7f3b75ea
data_aggregator/threads.py
data_aggregator/threads.py
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run next job job = next(values_iter) thread.run(func, job, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run thread with the next value value = next(values_iter) thread.run(func, value, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
Remove reference to "job" from ThreadPool
Remove reference to "job" from ThreadPool
Python
apache-2.0
uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: - # run next job + # run thread with the next value - job = next(values_iter) + value = next(values_iter) - thread.run(func, job, self.mp_queue) + thread.run(func, value, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
Remove reference to "job" from ThreadPool
## Code Before: import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run next job job = next(values_iter) thread.run(func, job, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False ## Instruction: Remove reference to "job" from ThreadPool ## Code After: import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run thread with the next value value = next(values_iter) thread.run(func, value, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
de962f504db139500573457264a3dd1e257e8cc0
wagtail_mvc/decorators.py
wagtail_mvc/decorators.py
from __future__ import unicode_literals def wagtail_mvc_url(func): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def outer(self, *args, **kwargs): parts = self.get_parent().url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer
from __future__ import unicode_literals def wagtail_mvc_url(*decorator_args, **decorator_kwargs): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def decorator(func): def outer(self, *args, **kwargs): parent_attr = decorator_kwargs.get('parent_attr') if parent_attr: parent = getattr(self, parent_attr, None) else: parent = self.get_parent() parts = parent.url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer if len(decorator_args) == 1 and callable(decorator_args[0]): # We assume the decorator function has not been called # or passed any arguments and return the result of calling # the decorator function return decorator(decorator_args[0]) return decorator
Allow decorator to be called with optional args
Allow decorator to be called with optional args
Python
mit
fatboystring/Wagtail-MVC,fatboystring/Wagtail-MVC
from __future__ import unicode_literals - def wagtail_mvc_url(func): + def wagtail_mvc_url(*decorator_args, **decorator_kwargs): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ + def decorator(func): - def outer(self, *args, **kwargs): + def outer(self, *args, **kwargs): + parent_attr = decorator_kwargs.get('parent_attr') - parts = self.get_parent().url.split('/') - parts += func(self, *args, **kwargs).split('/') - return '/{0}/'.format('/'.join([part for part in parts if part])) - return outer + if parent_attr: + parent = getattr(self, parent_attr, None) + else: + parent = self.get_parent() + + parts = parent.url.split('/') + parts += func(self, *args, **kwargs).split('/') + return '/{0}/'.format('/'.join([part for part in parts if part])) + return outer + + if len(decorator_args) == 1 and callable(decorator_args[0]): + # We assume the decorator function has not been called + # or passed any arguments and return the result of calling + # the decorator function + return decorator(decorator_args[0]) + return decorator +
Allow decorator to be called with optional args
## Code Before: from __future__ import unicode_literals def wagtail_mvc_url(func): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def outer(self, *args, **kwargs): parts = self.get_parent().url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer ## Instruction: Allow decorator to be called with optional args ## Code After: from __future__ import unicode_literals def wagtail_mvc_url(*decorator_args, **decorator_kwargs): """ Decorates an existing method responsible for generating a url prepends the parent url to the generated url to account for :param func: The method to decorate :return: Full url """ def decorator(func): def outer(self, *args, **kwargs): parent_attr = decorator_kwargs.get('parent_attr') if parent_attr: parent = getattr(self, parent_attr, None) else: parent = self.get_parent() parts = parent.url.split('/') parts += func(self, *args, **kwargs).split('/') return '/{0}/'.format('/'.join([part for part in parts if part])) return outer if len(decorator_args) == 1 and callable(decorator_args[0]): # We assume the decorator function has not been called # or passed any arguments and return the result of calling # the decorator function return decorator(decorator_args[0]) return decorator
fe676a041b793f55d33bfd27eb2b4fdfe7d93bb6
twilio/rest/resources/pricing/__init__.py
twilio/rest/resources/pricing/__init__.py
from .voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from .phone_numbers import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumbers, )
from twilio.rest.pricing.voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from twilio.rest.pricing.phone_number import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumber, )
Change import path for pricing
Change import path for pricing
Python
mit
tysonholub/twilio-python,twilio/twilio-python
- from .voice import ( + from twilio.rest.pricing.voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) - from .phone_numbers import ( + from twilio.rest.pricing.phone_number import ( PhoneNumberCountries, PhoneNumberCountry, - PhoneNumbers, + PhoneNumber, )
Change import path for pricing
## Code Before: from .voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from .phone_numbers import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumbers, ) ## Instruction: Change import path for pricing ## Code After: from twilio.rest.pricing.voice import ( Voice, VoiceCountry, VoiceCountries, VoiceNumber, VoiceNumbers, ) from twilio.rest.pricing.phone_number import ( PhoneNumberCountries, PhoneNumberCountry, PhoneNumber, )
0e779581be648ca80eea6b97f9963606d85659b9
opensfm/commands/__init__.py
opensfm/commands/__init__.py
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, ]
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, export_visualsfm, ]
Add exporter to VisualSfM format
Add exporter to VisualSfM format
Python
bsd-2-clause
BrookRoberts/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,BrookRoberts/OpenSfM,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM,BrookRoberts/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,BrookRoberts/OpenSfM,BrookRoberts/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs + import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, + export_visualsfm, ]
Add exporter to VisualSfM format
## Code Before: import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, ] ## Instruction: Add exporter to VisualSfM format ## Code After: import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, export_visualsfm, ]
a0ac251bec891a6c511ea1c0b11faa6525b81545
bfg9000/languages.py
bfg9000/languages.py
ext2lang = { '.cpp': 'c++', '.c': 'c', }
ext2lang = { '.c' : 'c', '.cpp': 'c++', '.cc' : 'c++', '.cp' : 'c++', '.cxx': 'c++', '.CPP': 'c++', '.c++': 'c++', '.C' : 'c++', }
Support more C++ extensions by default
Support more C++ extensions by default
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
ext2lang = { + '.c' : 'c', '.cpp': 'c++', - '.c': 'c', + '.cc' : 'c++', + '.cp' : 'c++', + '.cxx': 'c++', + '.CPP': 'c++', + '.c++': 'c++', + '.C' : 'c++', }
Support more C++ extensions by default
## Code Before: ext2lang = { '.cpp': 'c++', '.c': 'c', } ## Instruction: Support more C++ extensions by default ## Code After: ext2lang = { '.c' : 'c', '.cpp': 'c++', '.cc' : 'c++', '.cp' : 'c++', '.cxx': 'c++', '.CPP': 'c++', '.c++': 'c++', '.C' : 'c++', }
7f1542bc52438e6c9796e776603553d7f5a9df7f
pySpatialTools/utils/util_classes/__init__.py
pySpatialTools/utils/util_classes/__init__.py
from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from general_mapper import General1_1Mapper from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
Debug in importing deleted module.
Debug in importing deleted module.
Python
mit
tgquintela/pySpatialTools,tgquintela/pySpatialTools
from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership - from general_mapper import General1_1Mapper from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
Debug in importing deleted module.
## Code Before: from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from general_mapper import General1_1Mapper from mapper_vals_i import Map_Vals_i, create_mapper_vals_i ## Instruction: Debug in importing deleted module. ## Code After: from spdesc_mapper import Sp_DescriptorMapper from spatialelements import SpatialElementsCollection, Locations from Membership import Membership from mapper_vals_i import Map_Vals_i, create_mapper_vals_i
62a76827ecf7c148101b62925dea04f63709012a
sublime/User/update_user_settings.py
sublime/User/update_user_settings.py
import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Update command to work with sublime 3
Update command to work with sublime 3
Python
apache-2.0
RomuloOliveira/dot-files,RomuloOliveira/unix-files,RomuloOliveira/dot-files
import json - import urllib2 + import urllib import sublime import sublime_plugin - GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa + GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): - + def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: - response = urllib2.urlopen(url) + response = urllib.request.urlopen(url) - settings = json.loads(response.read()) + settings = json.loads(response.read().decode('utf-8')) - except (urllib2.URLError, ValueError) as e: + except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Update command to work with sublime 3
## Code Before: import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated') ## Instruction: Update command to work with sublime 3 ## Code After: import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
0ba9fa847a8b605363b298ecad40cb2fc5870cbb
build_modules.py
build_modules.py
import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") if __name__ == "__main__": build_modules()
import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) from voxel_native.scripts.common import is_macos, is_windows, is_linux if is_windows(): shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") elif is_macos() or is_linux(): shutil.move("voxel_native/voxel_native.so", "voxel/voxel_native.so") if __name__ == "__main__": build_modules()
Update build script to work correctly on macOS and linux.
Update build script to work correctly on macOS and linux.
Python
mit
treamology/panda3d-voxels,treamology/panda3d-voxels,treamology/panda3d-voxels
import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) + from voxel_native.scripts.common import is_macos, is_windows, is_linux + if is_windows(): - shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") + shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") - + elif is_macos() or is_linux(): + shutil.move("voxel_native/voxel_native.so", "voxel/voxel_native.so") if __name__ == "__main__": build_modules()
Update build script to work correctly on macOS and linux.
## Code Before: import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") if __name__ == "__main__": build_modules() ## Instruction: Update build script to work correctly on macOS and linux. ## Code After: import os, sys, subprocess, shutil def check_for_module_builder(): if os.path.exists("voxel_native/scripts/"): return print("Downloading P3DModuleBuilder...") cmd = [sys.executable, "-B", "voxel_native/download_P3DModuleBuilder.py"] try: output = subprocess.check_output(cmd, stderr=sys.stderr) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Couldn't download P3DModuleBuilder.") sys.exit(-1) def build_modules(): print("Building native modules...") check_for_module_builder() cmd = [sys.executable, "-B", "-m", "voxel_native.build"] try: output = subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, check=True) except subprocess.CalledProcessError as errorMsg: print(errorMsg) print("Error building the native modules.") sys.exit(-1) from voxel_native.scripts.common import is_macos, is_windows, is_linux if is_windows(): shutil.move("voxel_native/voxel_native.pyd", "voxel/voxel_native.pyd") elif is_macos() or is_linux(): shutil.move("voxel_native/voxel_native.so", "voxel/voxel_native.so") if __name__ == "__main__": build_modules()
115a71995f2ceae667c05114da8e8ba21c25c402
syncplay/__init__.py
syncplay/__init__.py
version = '1.6.5' revision = ' release' milestone = 'Yoitsu' release_number = '86' projectURL = 'https://syncplay.pl/'
version = '1.6.6' revision = ' development' milestone = 'Yoitsu' release_number = '87' projectURL = 'https://syncplay.pl/'
Move to 1.6.6 dev for further development
Move to 1.6.6 dev for further development
Python
apache-2.0
alby128/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay
- version = '1.6.5' + version = '1.6.6' - revision = ' release' + revision = ' development' milestone = 'Yoitsu' - release_number = '86' + release_number = '87' projectURL = 'https://syncplay.pl/'
Move to 1.6.6 dev for further development
## Code Before: version = '1.6.5' revision = ' release' milestone = 'Yoitsu' release_number = '86' projectURL = 'https://syncplay.pl/' ## Instruction: Move to 1.6.6 dev for further development ## Code After: version = '1.6.6' revision = ' development' milestone = 'Yoitsu' release_number = '87' projectURL = 'https://syncplay.pl/'
d6b1f7c03ec2b32823fe2c4214e6521e8074cd9f
commands/join.py
commands/join.py
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0] if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0].encode('utf8') #Make sure it's a str and not unicode, otherwise Twisted chokes on it if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
[Join] Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
Python
mit
Didero/DideRobot
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') - channel = message.messageParts[0] + channel = message.messageParts[0].encode('utf8') #Make sure it's a str and not unicode, otherwise Twisted chokes on it if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
## Code Before: from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0] if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext) ## Instruction: Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that ## Code After: from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = u"" if message.messagePartsLength < 1: replytext = u"Please provide a channel for me to join" else: allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',') channel = message.messageParts[0].encode('utf8') #Make sure it's a str and not unicode, otherwise Twisted chokes on it if channel.startswith('#'): channel = channel[1:] if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user): replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: channel = '#' + channel replytext = u"All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.bot.say(message.source, replytext)
521e24fa115e69bca39d7cca89ce42e8efa3b077
tools/perf_expectations/PRESUBMIT.py
tools/perf_expectations/PRESUBMIT.py
UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
Use full pathname to perf_expectations in test.
Use full pathname to perf_expectations in test. BUG=none TEST=none Review URL: http://codereview.chromium.org/266055 git-svn-id: http://src.chromium.org/svn/trunk/src@28770 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: f9d8e0a8dae19e482d3c435a76b4e38403e646b5
Python
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] - PERF_EXPECTATIONS = 'perf_expectations.json' + PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): - if PERF_EXPECTATIONS == input_api.os_path.basename(path): + if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): - if PERF_EXPECTATIONS == input_api.os_path.basename(path): + if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
Use full pathname to perf_expectations in test.
## Code Before: UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output ## Instruction: Use full pathname to perf_expectations in test. ## Code After: UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
4378aef47a7e2b80a4a22af2bbe69ce4b780ab6d
pokr/views/login.py
pokr/views/login.py
from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and not user.is_anonymous() } app.context_processor(backends)
from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and user.is_authenticated } app.context_processor(backends)
Fix due to Flask-Login version up
Fix due to Flask-Login version up
Python
apache-2.0
teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr
from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, - 'is_logged': user and not user.is_anonymous() + 'is_logged': user and user.is_authenticated } app.context_processor(backends)
Fix due to Flask-Login version up
## Code Before: from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and not user.is_anonymous() } app.context_processor(backends) ## Instruction: Fix due to Flask-Login version up ## Code After: from flask import g, render_template, redirect, request, url_for from flask.ext.login import current_user, login_required, logout_user from social.apps.flask_app.template_filters import backends def register(app): @login_required @app.route('/done/') def done(): return redirect(request.referrer or url_for('main')) @app.route('/logout') def logout(): logout_user() return redirect(request.referrer or url_for('main')) @app.before_request def global_user(): g.user = current_user @app.context_processor def inject_user(): user = getattr(g, 'user') return { 'user': user, 'is_logged': user and user.is_authenticated } app.context_processor(backends)
f935eb48517627df679605aaee834165380d74db
django_db_geventpool/backends/postgresql_psycopg2/creation.py
django_db_geventpool/backends/postgresql_psycopg2/creation.py
import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber, keepdb) def _destroy_test_db(self, test_database_name, verbosity, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity, keepdb) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
Fix DatabaseCreation from django 1.7
Fix DatabaseCreation from django 1.7
Python
apache-2.0
jneight/django-db-geventpool,PreppyLLC-opensource/django-db-geventpool
import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): - def _create_test_db(self, verbosity, autoclobber, keepdb=False): + def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() - return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber, keepdb) + return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber) - def _destroy_test_db(self, test_database_name, verbosity, keepdb=False): + def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() - return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity, keepdb) + return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
Fix DatabaseCreation from django 1.7
## Code Before: import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber, keepdb) def _destroy_test_db(self, test_database_name, verbosity, keepdb=False): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity, keepdb) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass ## Instruction: Fix DatabaseCreation from django 1.7 ## Code After: import django from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreationMixin16(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin16, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin16, self)._destroy_test_db(test_database_name, verbosity) class DatabaseCreationMixin17(object): def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreationMixin17, self)._create_test_db(verbosity, autoclobber) def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreationMixin17, self)._destroy_test_db(test_database_name, verbosity) if django.VERSION >= (1, 7): class DatabaseCreationMixin(DatabaseCreationMixin17): pass else: class DatabaseCreationMixin(DatabaseCreationMixin16): pass class DatabaseCreation(DatabaseCreationMixin, OriginalDatabaseCreation): pass
c1d889f637d6d2a931f81332a9eef3974dfa18e0
code/marv/marv/__init__.py
code/marv/marv/__init__.py
import sys from pkg_resources import iter_entry_points from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ] MODULE = sys.modules[__name__] for ep in iter_entry_points(group='marv_deco'): assert not hasattr(MODULE, ep.name) setattr(MODULE, ep.name, ep.load()) del MODULE
from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ]
Drop unused support to add decorators via entry points
Drop unused support to add decorators via entry points
Python
agpl-3.0
ternaris/marv-robotics,ternaris/marv-robotics
- - import sys - - from pkg_resources import iter_entry_points from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ] - MODULE = sys.modules[__name__] - for ep in iter_entry_points(group='marv_deco'): - assert not hasattr(MODULE, ep.name) - setattr(MODULE, ep.name, ep.load()) - del MODULE -
Drop unused support to add decorators via entry points
## Code Before: import sys from pkg_resources import iter_entry_points from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ] MODULE = sys.modules[__name__] for ep in iter_entry_points(group='marv_deco'): assert not hasattr(MODULE, ep.name) setattr(MODULE, ep.name, ep.load()) del MODULE ## Instruction: Drop unused support to add decorators via entry points ## Code After: from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ]
7785d3129d089ce99aee340b3a72fd78d7e8f556
send.py
send.py
import os sender = str(raw_input("Your Username: ")) target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
import os if os.path.exists("account.conf") is False: sender = str(raw_input("Your Username: ")) accountFile = open('account.conf', 'w+') accountFile.write(sender) accountFile.close() else: accountFile = open('account.conf', 'r') sender = accountFile.read() accountFile.close() target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
Store your username in a file
Store your username in a file
Python
mit
NickGeek/WiN,NickGeek/WiN,NickGeek/WiN
import os + if os.path.exists("account.conf") is False: - sender = str(raw_input("Your Username: ")) + sender = str(raw_input("Your Username: ")) + accountFile = open('account.conf', 'w+') + accountFile.write(sender) + accountFile.close() + else: + accountFile = open('account.conf', 'r') + sender = accountFile.read() + accountFile.close() + target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
Store your username in a file
## Code Before: import os sender = str(raw_input("Your Username: ")) target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py") ## Instruction: Store your username in a file ## Code After: import os if os.path.exists("account.conf") is False: sender = str(raw_input("Your Username: ")) accountFile = open('account.conf', 'w+') accountFile.write(sender) accountFile.close() else: accountFile = open('account.conf', 'r') sender = accountFile.read() accountFile.close() target = str(raw_input("Target's Username: ")) message = str(raw_input("Message: ")) #Messages are encoded like so "senderProgramVx.x##target##sender##message" #Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?" formattedMessage = "linuxVpre.release##"+target+"##"+sender+"##"+message #Write to file messageFile = open('msg.txt', 'w+') messageFile.write(formattedMessage) messageFile.close() os.system("python server.py")
42e4f42901872433f90dd84d5acf04fec76ab7f3
curious/commands/exc.py
curious/commands/exc.py
class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for {.name} failed.".format(self.ctx) return "The check {.__name__} for {.name} failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument {} in {.name}.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error {}".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert {} to type {.__name__}".format(self.arg, self.to_type) __str__ = __repr__
class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for `{.name}` failed.".format(self.ctx) return "The check `{.__name__}` for `{.name}` failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument `{}` in `{.name}`.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error `{}`.".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert `{}` to type `{.__name__}`.".format(self.arg, self.to_type) __str__ = __repr__
Add better __repr__s for commands errors.
Add better __repr__s for commands errors.
Python
mit
SunDwarf/curious
class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): - return "The checks for {.name} failed.".format(self.ctx) + return "The checks for `{.name}` failed.".format(self.ctx) - return "The check {.__name__} for {.name} failed.".format(self.check, self.ctx) + return "The check `{.__name__}` for `{.name}` failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): - return "Missing required argument {} in {.name}.".format(self.arg, self.ctx) + return "Missing required argument `{}` in `{.name}`.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): - return "Command {.name} failed to invoke with error {}".format(self.ctx, self.__cause__) + return "Command {.name} failed to invoke with error `{}`.".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): - return "Cannot convert {} to type {.__name__}".format(self.arg, self.to_type) + return "Cannot convert `{}` to type `{.__name__}`.".format(self.arg, self.to_type) __str__ = __repr__
Add better __repr__s for commands errors.
## Code Before: class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for {.name} failed.".format(self.ctx) return "The check {.__name__} for {.name} failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument {} in {.name}.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error {}".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert {} to type {.__name__}".format(self.arg, self.to_type) __str__ = __repr__ ## Instruction: Add better __repr__s for commands errors. ## Code After: class CommandsError(Exception): pass class CheckFailureError(Exception): def __init__(self, ctx, check): self.ctx = ctx self.check = check def __repr__(self): if isinstance(self.check, list): return "The checks for `{.name}` failed.".format(self.ctx) return "The check `{.__name__}` for `{.name}` failed.".format(self.check, self.ctx) __str__ = __repr__ class MissingArgumentError(Exception): def __init__(self, ctx, arg): self.ctx = ctx self.arg = arg def __repr__(self): return "Missing required argument `{}` in `{.name}`.".format(self.arg, self.ctx) __str__ = __repr__ class CommandInvokeError(Exception): def __init__(self, ctx): self.ctx = ctx def __repr__(self): return "Command {.name} failed to invoke with error `{}`.".format(self.ctx, self.__cause__) __str__ = __repr__ class ConversionFailedError(Exception): def __init__(self, ctx, arg: str, to_type: type): self.ctx = ctx self.arg = arg self.to_type = to_type def __repr__(self): return "Cannot convert `{}` to type `{.__name__}`.".format(self.arg, self.to_type) __str__ = __repr__
e853e0137e59314f5101c178c74fd626984c34ac
pygraphc/similarity/LogTextSimilarity.py
pygraphc/similarity/LogTextSimilarity.py
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logfile): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logfile : str Log filename. """ self.logtype = logtype self.logfile = logfile def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype, self.logfile) preprocess.preprocess_text() events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(preprocess.loglength, 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logs): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logs : list List of every line of original logs. """ self.logtype = logtype self.logs = logs def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype) preprocess.preprocess_text(self.logs) events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(range(preprocess.loglength), 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
Change input from previous processing not from a file
Change input from previous processing not from a file
Python
mit
studiawan/pygraphc
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ - def __init__(self, logtype, logfile): + def __init__(self, logtype, logs): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. - logfile : str - Log filename. + logs : list + List of every line of original logs. """ self.logtype = logtype - self.logfile = logfile + self.logs = logs def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ - preprocess = PreprocessLog(self.logtype, self.logfile) + preprocess = PreprocessLog(self.logtype) - preprocess.preprocess_text() + preprocess.preprocess_text(self.logs) events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} - for log_pair in combinations(preprocess.loglength, 2): + for log_pair in combinations(range(preprocess.loglength), 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
Change input from previous processing not from a file
## Code Before: from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logfile): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logfile : str Log filename. """ self.logtype = logtype self.logfile = logfile def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype, self.logfile) preprocess.preprocess_text() events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(preprocess.loglength, 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity ## Instruction: Change input from previous processing not from a file ## Code After: from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logs): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logs : list List of every line of original logs. """ self.logtype = logtype self.logs = logs def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype) preprocess.preprocess_text(self.logs) events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(range(preprocess.loglength), 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
bf96bf9d71f432f2db75b0c62b49098235d75661
cryptography/bindings/openssl/pkcs12.py
cryptography/bindings/openssl/pkcs12.py
TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ """
TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); """
Move these to macros, the exact type of these functions changes by deifne
Move these to macros, the exact type of these functions changes by deifne
Python
bsd-3-clause
Lukasa/cryptography,kimvais/cryptography,skeuomorf/cryptography,sholsapp/cryptography,dstufft/cryptography,bwhmather/cryptography,glyph/cryptography,dstufft/cryptography,bwhmather/cryptography,kimvais/cryptography,dstufft/cryptography,Ayrx/cryptography,Lukasa/cryptography,skeuomorf/cryptography,sholsapp/cryptography,Hasimir/cryptography,kimvais/cryptography,skeuomorf/cryptography,Ayrx/cryptography,skeuomorf/cryptography,bwhmather/cryptography,Hasimir/cryptography,bwhmather/cryptography,sholsapp/cryptography,Hasimir/cryptography,Lukasa/cryptography,dstufft/cryptography,Ayrx/cryptography,Ayrx/cryptography,sholsapp/cryptography,Hasimir/cryptography,glyph/cryptography,kimvais/cryptography,dstufft/cryptography
TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ - int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, - struct stack_st_X509 **); - PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, - struct stack_st_X509 *, int, int, int, int, int); void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ + int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, + struct stack_st_X509 **); + PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, + struct stack_st_X509 *, int, int, int, int, int); """
Move these to macros, the exact type of these functions changes by deifne
## Code Before: TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ """ ## Instruction: Move these to macros, the exact type of these functions changes by deifne ## Code After: TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); """
bcaf887ccad40adf2cb09627c12f2a3e1b4b006d
redis_cache/client/__init__.py
redis_cache/client/__init__.py
from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient from .sentinel import SentinelClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient', 'SentinelClient']
import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient',] try: from .sentinel import SentinelClient __all__.append("SentinelClient") except ImportError: warnings.warn("sentinel client is unsuported with redis-py<2.9", RuntimeWarning)
Disable Sentinel client with redis-py < 2.9
Disable Sentinel client with redis-py < 2.9
Python
bsd-3-clause
zl352773277/django-redis,smahs/django-redis,yanheng/django-redis,lucius-feng/django-redis,GetAmbassador/django-redis
+ + import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient - from .sentinel import SentinelClient + __all__ = ['DefaultClient', 'ShardClient', - 'HerdClient', 'SimpleFailoverClient', + 'HerdClient', 'SimpleFailoverClient',] - 'SentinelClient'] + try: + from .sentinel import SentinelClient + __all__.append("SentinelClient") + except ImportError: + warnings.warn("sentinel client is unsuported with redis-py<2.9", + RuntimeWarning) + +
Disable Sentinel client with redis-py < 2.9
## Code Before: from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient from .sentinel import SentinelClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient', 'SentinelClient'] ## Instruction: Disable Sentinel client with redis-py < 2.9 ## Code After: import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient',] try: from .sentinel import SentinelClient __all__.append("SentinelClient") except ImportError: warnings.warn("sentinel client is unsuported with redis-py<2.9", RuntimeWarning)
684ac5e6e6011581d5abcb42a7c0e54742f20606
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py
import socket, traceback import time import json host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() while time.time()-t0 < 200: try: message, address = s.recvfrom(4096) print(message) json.loads(message.decode("utf-8")) filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # -------------------------------------------------------
import socket, traceback import time import json import numpy as np from scipy.spatial.transform import Rotation as R host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() # Place IMU x-axis into wind going direction when launching script is_init_done = False wind_yaw = 0 while time.time()-t0 < 200: try: message, address = s.recvfrom(4096) #print(message) msg = json.loads(message.decode("utf-8")) if is_init_done==False: wind_yaw = msg["Yaw"] is_init_done = True msg['Yaw'] = msg['Yaw']-wind_yaw print(msg) ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']] seq = 'ZYX' # small letters from intrinsic rotations r = R.from_euler(seq, ypr, degrees=True) # Compute coordinates in NED (could be useful to compare position with GPS position for example) line_length = 10 base_to_kite = [0, 0, line_length] base_to_kite_in_NED = r.apply(base_to_kite) # Express kite coordinates as great roll, great pitch and small yaw angles grpy=r.as_euler(seq="XYZ") print(grpy*180/np.pi) filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # -------------------------------------------------------
Add computations of great roll, pitch and small yaw angle (kite angles)
Add computations of great roll, pitch and small yaw angle (kite angles)
Python
mit
baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite
import socket, traceback import time import json + + import numpy as np + from scipy.spatial.transform import Rotation as R host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() + + # Place IMU x-axis into wind going direction when launching script + is_init_done = False + wind_yaw = 0 while time.time()-t0 < 200: try: message, address = s.recvfrom(4096) - print(message) + #print(message) - json.loads(message.decode("utf-8")) + msg = json.loads(message.decode("utf-8")) + if is_init_done==False: + wind_yaw = msg["Yaw"] + is_init_done = True + msg['Yaw'] = msg['Yaw']-wind_yaw + print(msg) + + ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']] + seq = 'ZYX' # small letters from intrinsic rotations + + r = R.from_euler(seq, ypr, degrees=True) + + # Compute coordinates in NED (could be useful to compare position with GPS position for example) + line_length = 10 + base_to_kite = [0, 0, line_length] + base_to_kite_in_NED = r.apply(base_to_kite) + + # Express kite coordinates as great roll, great pitch and small yaw angles + grpy=r.as_euler(seq="XYZ") + print(grpy*180/np.pi) + filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # -------------------------------------------------------
Add computations of great roll, pitch and small yaw angle (kite angles)
## Code Before: import socket, traceback import time import json host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() while time.time()-t0 < 200: try: message, address = s.recvfrom(4096) print(message) json.loads(message.decode("utf-8")) filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # ------------------------------------------------------- ## Instruction: Add computations of great roll, pitch and small yaw angle (kite angles) ## Code After: import socket, traceback import time import json import numpy as np from scipy.spatial.transform import Rotation as R host = '' port = 2390 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() # Place IMU x-axis into wind going direction when launching script is_init_done = False wind_yaw = 0 while time.time()-t0 < 200: try: message, address = s.recvfrom(4096) #print(message) msg = json.loads(message.decode("utf-8")) if is_init_done==False: wind_yaw = msg["Yaw"] is_init_done = True msg['Yaw'] = msg['Yaw']-wind_yaw print(msg) ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']] seq = 'ZYX' # small letters from intrinsic rotations r = R.from_euler(seq, ypr, degrees=True) # Compute coordinates in NED (could be useful to compare position with GPS position for example) line_length = 10 base_to_kite = [0, 0, line_length] base_to_kite_in_NED = r.apply(base_to_kite) # Express kite coordinates as great roll, great pitch and small yaw angles grpy=r.as_euler(seq="XYZ") print(grpy*180/np.pi) filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # -------------------------------------------------------
6d18ff715a5fa3059ddb609c1abdbbb06b15ad63
fuel/downloaders/celeba.py
fuel/downloaders/celeba.py
from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
Update download links for CelebA files
Update download links for CelebA files
Python
mit
mila-udem/fuel,dmitriy-serdyuk/fuel,dmitriy-serdyuk/fuel,mila-udem/fuel,vdumoulin/fuel,vdumoulin/fuel
from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' - 'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1', + 'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' - 'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1'] + 'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
Update download links for CelebA files
## Code Before: from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader ## Instruction: Update download links for CelebA files ## Code After: from fuel.downloaders.base import default_downloader def fill_subparser(subparser): """Sets up a subparser to download the CelebA dataset file. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `celeba` command. """ urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1', 'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/' 'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1'] filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip'] subparser.set_defaults(urls=urls, filenames=filenames) return default_downloader
e818860af87cad796699e27f8dfb4ff6fc9354e8
h2o-py/h2o/model/autoencoder.py
h2o-py/h2o/model/autoencoder.py
from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data,per_feature=False): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :param per_feature: Whether to return the square reconstruction error per feature. Otherwise, return the mean square error. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True, reconstruction_error_per_feature=per_feature) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
Add extra argument to get per-feature reconstruction error for anomaly detection from Python.
PUBDEV-2078: Add extra argument to get per-feature reconstruction error for anomaly detection from Python.
Python
apache-2.0
kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,brightchen/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,datachand/h2o-3,kyoren/https-github.com-h2oai-h2o-3,printedheart/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,pchmieli/h2o-3,datachand/h2o-3,junwucs/h2o-3,mathemage/h2o-3,h2oai/h2o-3,printedheart/h2o-3,junwucs/h2o-3,kyoren/https-github.com-h2oai-h2o-3,YzPaul3/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,junwucs/h2o-3,printedheart/h2o-3,datachand/h2o-3,pchmieli/h2o-3,michalkurka/h2o-3,printedheart/h2o-3,brightchen/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,madmax983/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,brightchen/h2o-3,pchmieli/h2o-3,brightchen/h2o-3,spennihana/h2o-3,junwucs/h2o-3,mathemage/h2o-3,printedheart/h2o-3,madmax983/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,kyoren/https-github.com-h2oai-h2o-3,madmax983/h2o-3,datachand/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,junwucs/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,pchmieli/h2o-3,junwucs/h2o-3,mathemage/h2o-3,datachand/h2o-3,kyoren/https-github.com-h2oai-h2o-3,jangorecki/h2o-3,spennihana/h2o-3,spennihana/h2o-3,spennihana/h2o-3,madmax983/h2o-3,spennihana/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,brightchen/h2o-3,pchmieli/h2o-3,h2oai/h2o-dev,brightchen/h2o-3,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,printedheart/h2o-3
from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) - def anomaly(self,test_data): + def anomaly(self,test_data,per_feature=False): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. + :param per_feature: Whether to return the square reconstruction error per feature. Otherwise, return the mean square error. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") - j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True) + j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True, reconstruction_error_per_feature=per_feature) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
Add extra argument to get per-feature reconstruction error for anomaly detection from Python.
## Code Before: from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"]) ## Instruction: Add extra argument to get per-feature reconstruction error for anomaly detection from Python. ## Code After: from model_base import * from metrics_base import * class H2OAutoEncoderModel(ModelBase): """ Class for AutoEncoder models. """ def __init__(self, dest_key, model_json): super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics) def anomaly(self,test_data,per_feature=False): """ Obtain the reconstruction error for the input test_data. :param test_data: The dataset upon which the reconstruction error is computed. :param per_feature: Whether to return the square reconstruction error per feature. Otherwise, return the mean square error. :return: Return the reconstruction error. """ if not test_data: raise ValueError("Must specify test data") j = H2OConnection.post_json("Predictions/models/" + self._id + "/frames/" + test_data._id, reconstruction_error=True, reconstruction_error_per_feature=per_feature) return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
ea1c095fb12c4062616ee0d38818ab1baaabd1eb
ipywidgets/widgets/tests/test_widget_upload.py
ipywidgets/widgets/tests/test_widget_upload.py
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == []
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] def test_receive_single_file(self): uploader = FileUpload() content = memoryview(b"file content") message = { "value": [ { "name": "file-name.txt", "type": "text/plain", "size": 20760, "lastModified": 1578578296434, "error": "", "content": content, } ] } uploader.set_state(message) assert len(uploader.value) == 1 [uploaded_file] = uploader.value assert uploaded_file.name == "file-name.txt" assert uploaded_file.type == "text/plain" assert uploaded_file.size == 20760 assert uploaded_file.content.tobytes() == b"file content"
Test deserialization of comm message following upload
Test deserialization of comm message following upload
Python
bsd-3-clause
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] + def test_receive_single_file(self): + uploader = FileUpload() + content = memoryview(b"file content") + message = { + "value": [ + { + "name": "file-name.txt", + "type": "text/plain", + "size": 20760, + "lastModified": 1578578296434, + "error": "", + "content": content, + } + ] + } + uploader.set_state(message) + assert len(uploader.value) == 1 + [uploaded_file] = uploader.value + assert uploaded_file.name == "file-name.txt" + assert uploaded_file.type == "text/plain" + assert uploaded_file.size == 20760 + assert uploaded_file.content.tobytes() == b"file content" +
Test deserialization of comm message following upload
## Code Before: from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] ## Instruction: Test deserialization of comm message following upload ## Code After: from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] def test_receive_single_file(self): uploader = FileUpload() content = memoryview(b"file content") message = { "value": [ { "name": "file-name.txt", "type": "text/plain", "size": 20760, "lastModified": 1578578296434, "error": "", "content": content, } ] } uploader.set_state(message) assert len(uploader.value) == 1 [uploaded_file] = uploader.value assert uploaded_file.name == "file-name.txt" assert uploaded_file.type == "text/plain" assert uploaded_file.size == 20760 assert uploaded_file.content.tobytes() == b"file content"
c5730d19d41f7221c4108f340d0ff8be26c24c74
auxiliary/tag_suggestions/__init__.py
auxiliary/tag_suggestions/__init__.py
from tagging.models import Tag, TaggedItem from django.contrib.contenttypes.models import ContentType from auxiliary.models import TagSuggestion from django.db import IntegrityError def approve(admin, request, tag_suggestions): for tag_suggestion in tag_suggestions: object = tag_suggestion.object try: tag = Tag.objects.create(name=tag_suggestion.name) TaggedItem.objects.create(tag=tag, object=object) except IntegrityError as e: if str(e) != 'column name is not unique': raise tag_suggestion.delete()
from tagging.models import Tag, TaggedItem from django.contrib.contenttypes.models import ContentType def approve(admin, request, tag_suggestions): for tag_suggestion in tag_suggestions: obj = tag_suggestion.object ct = ContentType.objects.get_for_model(obj) tag, t_created = Tag.objects.get_or_create(name=tag_suggestion.name) ti, ti_created = TaggedItem.objects.get_or_create( tag=tag, object_id=obj.pk, content_type=ct) tag_suggestion.delete()
Make tag_suggestions test less flaky
Make tag_suggestions test less flaky Failed on Python 2.7.6 as it was dependant on an error string returned
Python
bsd-3-clause
noamelf/Open-Knesset,otadmor/Open-Knesset,habeanf/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,navotsil/Open-Knesset,noamelf/Open-Knesset,navotsil/Open-Knesset,navotsil/Open-Knesset,otadmor/Open-Knesset,noamelf/Open-Knesset,otadmor/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,jspan/Open-Knesset,MeirKriheli/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,ofri/Open-Knesset,OriHoch/Open-Knesset,DanaOshri/Open-Knesset,ofri/Open-Knesset,MeirKriheli/Open-Knesset,alonisser/Open-Knesset,DanaOshri/Open-Knesset,alonisser/Open-Knesset,DanaOshri/Open-Knesset,OriHoch/Open-Knesset,MeirKriheli/Open-Knesset,jspan/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,OriHoch/Open-Knesset,Shrulik/Open-Knesset,habeanf/Open-Knesset,ofri/Open-Knesset,OriHoch/Open-Knesset,DanaOshri/Open-Knesset,noamelf/Open-Knesset,Shrulik/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,MeirKriheli/Open-Knesset,daonb/Open-Knesset,navotsil/Open-Knesset
from tagging.models import Tag, TaggedItem from django.contrib.contenttypes.models import ContentType + - from auxiliary.models import TagSuggestion - from django.db import IntegrityError def approve(admin, request, tag_suggestions): for tag_suggestion in tag_suggestions: - object = tag_suggestion.object + obj = tag_suggestion.object - try: + + ct = ContentType.objects.get_for_model(obj) + - tag = Tag.objects.create(name=tag_suggestion.name) + tag, t_created = Tag.objects.get_or_create(name=tag_suggestion.name) + ti, ti_created = TaggedItem.objects.get_or_create( + tag=tag, object_id=obj.pk, content_type=ct) + - TaggedItem.objects.create(tag=tag, object=object) - except IntegrityError as e: - if str(e) != 'column name is not unique': - raise tag_suggestion.delete()
Make tag_suggestions test less flaky
## Code Before: from tagging.models import Tag, TaggedItem from django.contrib.contenttypes.models import ContentType from auxiliary.models import TagSuggestion from django.db import IntegrityError def approve(admin, request, tag_suggestions): for tag_suggestion in tag_suggestions: object = tag_suggestion.object try: tag = Tag.objects.create(name=tag_suggestion.name) TaggedItem.objects.create(tag=tag, object=object) except IntegrityError as e: if str(e) != 'column name is not unique': raise tag_suggestion.delete() ## Instruction: Make tag_suggestions test less flaky ## Code After: from tagging.models import Tag, TaggedItem from django.contrib.contenttypes.models import ContentType def approve(admin, request, tag_suggestions): for tag_suggestion in tag_suggestions: obj = tag_suggestion.object ct = ContentType.objects.get_for_model(obj) tag, t_created = Tag.objects.get_or_create(name=tag_suggestion.name) ti, ti_created = TaggedItem.objects.get_or_create( tag=tag, object_id=obj.pk, content_type=ct) tag_suggestion.delete()
85b269bde76af2b8d15dc3b1e9f7cf882fc18dc2
labcalc/tests/test_functions.py
labcalc/tests/test_functions.py
from labcalc.run import * from labcalc import gibson # labcalc.gibson def test_gibson_one_insert(): d = {'insert1': [300, 50], 'vector': [5000, 50]} assert gibson.gibson_calc(d) == {'insert1': 0.24, 'vector': 2.0}
from labcalc.run import * from labcalc import gibson # labcalc.gibson def test_gibson_one_insert(): d = {'vector': [5000, 50], 'insert1': [300, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24} def test_gibson_two_inserts(): d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24, 'insert2': 0.48} def test_gibson_four_inserts(): d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50], 'insert3': [300, 50], 'insert4': [600, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.12, 'insert2': 0.24, 'insert3': 0.12, 'insert4': 0.24}
Add tests for multiple gibson inserts
Add tests for multiple gibson inserts
Python
bsd-3-clause
dtarnowski16/labcalc,mandel01/labcalc,mjmlab/labcalc
from labcalc.run import * from labcalc import gibson # labcalc.gibson def test_gibson_one_insert(): - d = {'insert1': [300, 50], 'vector': [5000, 50]} + d = {'vector': [5000, 50], 'insert1': [300, 50]} - assert gibson.gibson_calc(d) == {'insert1': 0.24, 'vector': 2.0} + assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24} + def test_gibson_two_inserts(): + d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50]} + assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24, 'insert2': 0.48} + + def test_gibson_four_inserts(): + d = {'vector': [5000, 50], + 'insert1': [300, 50], 'insert2': [600, 50], 'insert3': [300, 50], 'insert4': [600, 50]} + assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.12, 'insert2': 0.24, 'insert3': 0.12, 'insert4': 0.24} +
Add tests for multiple gibson inserts
## Code Before: from labcalc.run import * from labcalc import gibson # labcalc.gibson def test_gibson_one_insert(): d = {'insert1': [300, 50], 'vector': [5000, 50]} assert gibson.gibson_calc(d) == {'insert1': 0.24, 'vector': 2.0} ## Instruction: Add tests for multiple gibson inserts ## Code After: from labcalc.run import * from labcalc import gibson # labcalc.gibson def test_gibson_one_insert(): d = {'vector': [5000, 50], 'insert1': [300, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24} def test_gibson_two_inserts(): d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.24, 'insert2': 0.48} def test_gibson_four_inserts(): d = {'vector': [5000, 50], 'insert1': [300, 50], 'insert2': [600, 50], 'insert3': [300, 50], 'insert4': [600, 50]} assert gibson.gibson_calc(d) == {'vector': 2.0, 'insert1': 0.12, 'insert2': 0.24, 'insert3': 0.12, 'insert4': 0.24}
caaa807a4226bfdeb18681f8ccb6119bd2caa609
pombola/core/context_processors.py
pombola/core/context_processors.py
from django.conf import settings import logging def add_settings( request ): """Add some selected settings values to the context""" return { 'settings': { 'STAGING': settings.STAGING, 'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER, 'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT, 'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID, 'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME, 'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS, 'TWITTER_USERNAME': settings.TWITTER_USERNAME, 'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID, 'BLOG_RSS_FEED': settings.BLOG_RSS_FEED, 'ENABLED_FEATURES': settings.ENABLED_FEATURES, 'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH, 'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST, 'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH, 'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST, } }
from django.conf import settings import logging def add_settings( request ): """Add some selected settings values to the context""" return { 'settings': { 'STAGING': settings.STAGING, 'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER, 'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT, 'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID, 'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME, 'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS, 'TWITTER_USERNAME': settings.TWITTER_USERNAME, 'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID, 'BLOG_RSS_FEED': settings.BLOG_RSS_FEED, 'ENABLED_FEATURES': settings.ENABLED_FEATURES, 'COUNTRY_APP': settings.COUNTRY_APP, 'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH, 'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST, 'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH, 'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST, } }
Add COUNTRY_APP to settings exposed to the templates
Add COUNTRY_APP to settings exposed to the templates
Python
agpl-3.0
hzj123/56th,mysociety/pombola,hzj123/56th,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola
from django.conf import settings import logging def add_settings( request ): """Add some selected settings values to the context""" return { 'settings': { 'STAGING': settings.STAGING, 'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER, 'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT, 'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID, 'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME, 'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS, 'TWITTER_USERNAME': settings.TWITTER_USERNAME, 'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID, 'BLOG_RSS_FEED': settings.BLOG_RSS_FEED, 'ENABLED_FEATURES': settings.ENABLED_FEATURES, + 'COUNTRY_APP': settings.COUNTRY_APP, 'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH, 'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST, 'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH, 'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST, } }
Add COUNTRY_APP to settings exposed to the templates
## Code Before: from django.conf import settings import logging def add_settings( request ): """Add some selected settings values to the context""" return { 'settings': { 'STAGING': settings.STAGING, 'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER, 'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT, 'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID, 'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME, 'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS, 'TWITTER_USERNAME': settings.TWITTER_USERNAME, 'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID, 'BLOG_RSS_FEED': settings.BLOG_RSS_FEED, 'ENABLED_FEATURES': settings.ENABLED_FEATURES, 'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH, 'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST, 'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH, 'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST, } } ## Instruction: Add COUNTRY_APP to settings exposed to the templates ## Code After: from django.conf import settings import logging def add_settings( request ): """Add some selected settings values to the context""" return { 'settings': { 'STAGING': settings.STAGING, 'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER, 'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT, 'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID, 'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME, 'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS, 'TWITTER_USERNAME': settings.TWITTER_USERNAME, 'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID, 'BLOG_RSS_FEED': settings.BLOG_RSS_FEED, 'ENABLED_FEATURES': settings.ENABLED_FEATURES, 'COUNTRY_APP': settings.COUNTRY_APP, 'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH, 'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST, 'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH, 'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST, } }
47d9a8df136e235f49921d4782c5e392b0101107
migrations/versions/147_add_cleaned_subject.py
migrations/versions/147_add_cleaned_subject.py
# revision identifiers, used by Alembic. revision = '486c7fa5b533' down_revision = 'c77a90d524' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.add_column('thread', sa.Column('_cleaned_subject', sa.String(length=255), nullable=True)) op.create_index('ix_cleaned_subject', 'thread', ['namespace_id', '_cleaned_subject'], unique=False) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.drop_index('ix_cleaned_subject', table_name='thread') op.drop_column('thread', '_cleaned_subject')
# revision identifiers, used by Alembic. revision = '486c7fa5b533' down_revision = 'c77a90d524' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.add_column('thread', sa.Column('_cleaned_subject', sa.String(length=255), nullable=True)) op.create_index('ix_cleaned_subject', 'thread', ['_cleaned_subject'], unique=False) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.drop_index('ix_cleaned_subject', table_name='thread') op.drop_column('thread', '_cleaned_subject')
Make _cleaned_subject migration match declared schema.
Make _cleaned_subject migration match declared schema. Test Plan: Upgrade old database to head. Reviewers: kav-ya Reviewed By: kav-ya Differential Revision: https://review.inboxapp.com/D1394
Python
agpl-3.0
Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,closeio/nylas,nylas/sync-engine,gale320/sync-engine,gale320/sync-engine,gale320/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,closeio/nylas,jobscore/sync-engine,gale320/sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,closeio/nylas,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine
# revision identifiers, used by Alembic. revision = '486c7fa5b533' down_revision = 'c77a90d524' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.add_column('thread', sa.Column('_cleaned_subject', sa.String(length=255), nullable=True)) - op.create_index('ix_cleaned_subject', 'thread', + op.create_index('ix_cleaned_subject', 'thread', ['_cleaned_subject'], - ['namespace_id', '_cleaned_subject'], unique=False) + unique=False) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.drop_index('ix_cleaned_subject', table_name='thread') op.drop_column('thread', '_cleaned_subject')
Make _cleaned_subject migration match declared schema.
## Code Before: # revision identifiers, used by Alembic. revision = '486c7fa5b533' down_revision = 'c77a90d524' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.add_column('thread', sa.Column('_cleaned_subject', sa.String(length=255), nullable=True)) op.create_index('ix_cleaned_subject', 'thread', ['namespace_id', '_cleaned_subject'], unique=False) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.drop_index('ix_cleaned_subject', table_name='thread') op.drop_column('thread', '_cleaned_subject') ## Instruction: Make _cleaned_subject migration match declared schema. ## Code After: # revision identifiers, used by Alembic. revision = '486c7fa5b533' down_revision = 'c77a90d524' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.add_column('thread', sa.Column('_cleaned_subject', sa.String(length=255), nullable=True)) op.create_index('ix_cleaned_subject', 'thread', ['_cleaned_subject'], unique=False) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) op.drop_index('ix_cleaned_subject', table_name='thread') op.drop_column('thread', '_cleaned_subject')
cdaeb29474df423e66cbc79fffa74d937fe2193c
justitie/just/pipelines.py
justitie/just/pipelines.py
import requests import json from just.items import JustPublication import logging API_KEY = 'justitie-very-secret-key' API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/' class JustPublicationsToApiPipeline(object): def process_item(self, item, spider): if type(item) != JustPublication: return item r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } ) return item
import requests import json import logging from just.items import JustPublication import logging API_KEY = 'justitie-very-secret-key' API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/' class JustPublicationsToApiPipeline(object): def process_item(self, item, spider): if type(item) != JustPublication: return item r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } ) api_log = logging.getLogger('api-log.txt') if r.status_code == 200 or r.status_code == '200': api_log.log(r.status_code, level=logging.INFO) else: api_log.log(r.status_code, level=logging.ERROR) api_log.log(r.content, level=logging.INFO) return item
Add logging for api calls.
Add logging for api calls.
Python
mpl-2.0
mgax/czl-scrape,margelatu/czl-scrape,costibleotu/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,lbogdan/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,code4romania/czl-scrape,lbogdan/czl-scrape,margelatu/czl-scrape,margelatu/czl-scrape,lbogdan/czl-scrape,mgax/czl-scrape,costibleotu/czl-scrape,margelatu/czl-scrape,costibleotu/czl-scrape,costibleotu/czl-scrape
import requests import json + import logging from just.items import JustPublication import logging API_KEY = 'justitie-very-secret-key' API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/' class JustPublicationsToApiPipeline(object): def process_item(self, item, spider): if type(item) != JustPublication: return item r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } ) + api_log = logging.getLogger('api-log.txt') + if r.status_code == 200 or r.status_code == '200': + api_log.log(r.status_code, level=logging.INFO) + else: + api_log.log(r.status_code, level=logging.ERROR) + api_log.log(r.content, level=logging.INFO) + return item
Add logging for api calls.
## Code Before: import requests import json from just.items import JustPublication import logging API_KEY = 'justitie-very-secret-key' API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/' class JustPublicationsToApiPipeline(object): def process_item(self, item, spider): if type(item) != JustPublication: return item r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } ) return item ## Instruction: Add logging for api calls. ## Code After: import requests import json import logging from just.items import JustPublication import logging API_KEY = 'justitie-very-secret-key' API_PUBLICATIONS = 'http://czl-api.code4.ro/api/publications/' class JustPublicationsToApiPipeline(object): def process_item(self, item, spider): if type(item) != JustPublication: return item r = requests.post(API_PUBLICATIONS, json=dict(item), headers={'Authorization': 'Token %s' % (API_KEY,) } ) api_log = logging.getLogger('api-log.txt') if r.status_code == 200 or r.status_code == '200': api_log.log(r.status_code, level=logging.INFO) else: api_log.log(r.status_code, level=logging.ERROR) api_log.log(r.content, level=logging.INFO) return item
a91a04af6b95fa600a0b3ce74b5fffc07ecf590e
polymorphic/__init__.py
polymorphic/__init__.py
# See PEP 440 (https://www.python.org/dev/peps/pep-0440/) __version__ = "1.3"
import pkg_resources __version__ = pkg_resources.require("django-polymorphic")[0].version
Set polymorphic.__version__ from setuptools metadata
Set polymorphic.__version__ from setuptools metadata
Python
bsd-3-clause
skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,skirsdeda/django_polymorphic,chrisglass/django_polymorphic,chrisglass/django_polymorphic
+ import pkg_resources - # See PEP 440 (https://www.python.org/dev/peps/pep-0440/) - __version__ = "1.3" + + __version__ = pkg_resources.require("django-polymorphic")[0].version +
Set polymorphic.__version__ from setuptools metadata
## Code Before: # See PEP 440 (https://www.python.org/dev/peps/pep-0440/) __version__ = "1.3" ## Instruction: Set polymorphic.__version__ from setuptools metadata ## Code After: import pkg_resources __version__ = pkg_resources.require("django-polymorphic")[0].version
8cb680c7fbadfe6cfc245fe1eb1261a00c5ffd6d
djmoney/forms/fields.py
djmoney/forms/fields.py
from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return Money(*data_list[:2])
from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): try: if data_list[0] is None: return None except IndexError: return None return Money(*data_list[:2])
Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None.
Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None.
Python
bsd-3-clause
recklessromeo/django-money,rescale/django-money,iXioN/django-money,AlexRiina/django-money,tsouvarev/django-money,iXioN/django-money,tsouvarev/django-money,recklessromeo/django-money
from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): + try: + if data_list[0] is None: + return None + except IndexError: + return None return Money(*data_list[:2]) +
Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None.
## Code Before: from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return Money(*data_list[:2]) ## Instruction: Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None. ## Code After: from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): try: if data_list[0] is None: return None except IndexError: return None return Money(*data_list[:2])
98ca37ed174e281542df2f1026a298387845b524
rmgpy/tools/data/generate/input.py
rmgpy/tools/data/generate/input.py
database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='ethane', reactive=True, structure=SMILES("CC"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) species( label='butane', reactive=True, structure=SMILES("CCCC"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "ethane": 1, }, terminationConversion={ 'butane': .99, }, terminationTime=(40,'s'), )
database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['R_Recombination'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='Propyl', reactive=True, structure=SMILES("CC[CH3]"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "Propyl": 1, }, terminationConversion={ 'Propyl': .99, }, terminationTime=(40,'s'), )
Cut down on the loading of families in the normal GenerateReactionsTest
Cut down on the loading of families in the normal GenerateReactionsTest Change generateReactions input reactant to propyl
Python
mit
nickvandewiele/RMG-Py,nyee/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,nickvandewiele/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py
database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with - kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], + kineticsFamilies = ['R_Recombination'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( - label='ethane', + label='Propyl', reactive=True, - structure=SMILES("CC"), + structure=SMILES("CC[CH3]"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) - species( - label='butane', - reactive=True, - structure=SMILES("CCCC"), - ) - # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ - "ethane": 1, + "Propyl": 1, }, terminationConversion={ - 'butane': .99, + 'Propyl': .99, }, terminationTime=(40,'s'), ) +
Cut down on the loading of families in the normal GenerateReactionsTest
## Code Before: database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='ethane', reactive=True, structure=SMILES("CC"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) species( label='butane', reactive=True, structure=SMILES("CCCC"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "ethane": 1, }, terminationConversion={ 'butane': .99, }, terminationTime=(40,'s'), ) ## Instruction: Cut down on the loading of families in the normal GenerateReactionsTest ## Code After: database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['R_Recombination'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='Propyl', reactive=True, structure=SMILES("CC[CH3]"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "Propyl": 1, }, terminationConversion={ 'Propyl': .99, }, terminationTime=(40,'s'), )
75c48ecbac476fd751e55745cc2935c1dac1f138
longest_duplicated_substring.py
longest_duplicated_substring.py
import sys # O(n^4) approach: generate all possible substrings and # compare each for equality. def longest_duplicated_substring(string): """Return the longest duplicated substring. Keyword Arguments: string -- the string to examine for duplicated substrings This approach examines each possible pair of starting points for duplicated substrings. If the characters at those points are the same, the match is extended up to the maximum length for those points. Each new longest duplicated substring is recorded as the best found so far. This solution is optimal for the naive brute-force approach and runs in O(n^3). """ lds = "" string_length = len(string) for i in range(string_length): for j in range(i+1,string_length): # Alternate approach with while loop here and max update outside. # Can also break length check into function. for substring_length in range(string_length-j): if string[i+substring_length] != string[j+substring_length]: break elif substring_length + 1 > len(lds): lds = string[i:i+substring_length+1] return lds if __name__ == "__main__": print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
import sys def longest_duplicated_substring(string): """Return the longest duplicated substring. Keyword Arguments: string -- the string to examine for duplicated substrings This approach examines each possible pair of starting points for duplicated substrings. If the characters at those points are the same, the match is extended up to the maximum length for those points. Each new longest duplicated substring is recorded as the best found so far. This solution is optimal for the naive brute-force approach and runs in O(n^3). """ lds = "" string_length = len(string) for i in range(string_length): for j in range(i+1,string_length): for substring_length in range(string_length-j): if string[i+substring_length] != string[j+substring_length]: break elif substring_length + 1 > len(lds): lds = string[i:i+substring_length+1] return lds if __name__ == "__main__": print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
Move todos into issues tracking on GitHub
Move todos into issues tracking on GitHub
Python
mit
taylor-peterson/longest-duplicated-substring
import sys - - # O(n^4) approach: generate all possible substrings and - # compare each for equality. def longest_duplicated_substring(string): """Return the longest duplicated substring. Keyword Arguments: string -- the string to examine for duplicated substrings This approach examines each possible pair of starting points for duplicated substrings. If the characters at those points are the same, the match is extended up to the maximum length for those points. Each new longest duplicated substring is recorded as the best found so far. This solution is optimal for the naive brute-force approach and runs in O(n^3). """ lds = "" string_length = len(string) for i in range(string_length): for j in range(i+1,string_length): - # Alternate approach with while loop here and max update outside. - # Can also break length check into function. for substring_length in range(string_length-j): if string[i+substring_length] != string[j+substring_length]: break elif substring_length + 1 > len(lds): lds = string[i:i+substring_length+1] return lds if __name__ == "__main__": print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
Move todos into issues tracking on GitHub
## Code Before: import sys # O(n^4) approach: generate all possible substrings and # compare each for equality. def longest_duplicated_substring(string): """Return the longest duplicated substring. Keyword Arguments: string -- the string to examine for duplicated substrings This approach examines each possible pair of starting points for duplicated substrings. If the characters at those points are the same, the match is extended up to the maximum length for those points. Each new longest duplicated substring is recorded as the best found so far. This solution is optimal for the naive brute-force approach and runs in O(n^3). """ lds = "" string_length = len(string) for i in range(string_length): for j in range(i+1,string_length): # Alternate approach with while loop here and max update outside. # Can also break length check into function. for substring_length in range(string_length-j): if string[i+substring_length] != string[j+substring_length]: break elif substring_length + 1 > len(lds): lds = string[i:i+substring_length+1] return lds if __name__ == "__main__": print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:])))) ## Instruction: Move todos into issues tracking on GitHub ## Code After: import sys def longest_duplicated_substring(string): """Return the longest duplicated substring. Keyword Arguments: string -- the string to examine for duplicated substrings This approach examines each possible pair of starting points for duplicated substrings. If the characters at those points are the same, the match is extended up to the maximum length for those points. Each new longest duplicated substring is recorded as the best found so far. This solution is optimal for the naive brute-force approach and runs in O(n^3). """ lds = "" string_length = len(string) for i in range(string_length): for j in range(i+1,string_length): for substring_length in range(string_length-j): if string[i+substring_length] != string[j+substring_length]: break elif substring_length + 1 > len(lds): lds = string[i:i+substring_length+1] return lds if __name__ == "__main__": print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
847a88c579118f8a0d528284ab3ea029ccca7215
git_pre_commit_hook/builtin_plugins/rst_check.py
git_pre_commit_hook/builtin_plugins/rst_check.py
import os import fnmatch import restructuredtext_lint DEFAULTS = { 'files': '*.rst', } def make_message(error): return '%s %s:%s %s\n' % ( error.type, error.source, error.line, error.message, ) def check(file_staged_for_commit, options): basename = os.path.basename(file_staged_for_commit.path) if not fnmatch.fnmatch(basename, options.rst_files): return True errors = restructuredtext_lint.lint( file_staged_for_commit.contents, file_staged_for_commit.path, ) if errors: print('\n'.join(make_message(e) for e in errors)) return False else: return True
"""Check that files contains valid ReStructuredText.""" import os import fnmatch import restructuredtext_lint DEFAULTS = { 'files': '*.rst', } def make_message(error): return '%s %s:%s %s\n' % ( error.type, error.source, error.line, error.message, ) def check(file_staged_for_commit, options): basename = os.path.basename(file_staged_for_commit.path) if not fnmatch.fnmatch(basename, options.rst_files): return True errors = restructuredtext_lint.lint( file_staged_for_commit.contents, file_staged_for_commit.path, ) if errors: print('\n'.join(make_message(e) for e in errors)) return False else: return True
Add description to rst plugin
Add description to rst plugin
Python
mit
evvers/git-pre-commit-hook
+ """Check that files contains valid ReStructuredText.""" import os import fnmatch import restructuredtext_lint DEFAULTS = { 'files': '*.rst', } def make_message(error): return '%s %s:%s %s\n' % ( error.type, error.source, error.line, error.message, ) def check(file_staged_for_commit, options): basename = os.path.basename(file_staged_for_commit.path) if not fnmatch.fnmatch(basename, options.rst_files): return True errors = restructuredtext_lint.lint( file_staged_for_commit.contents, file_staged_for_commit.path, ) if errors: print('\n'.join(make_message(e) for e in errors)) return False else: return True
Add description to rst plugin
## Code Before: import os import fnmatch import restructuredtext_lint DEFAULTS = { 'files': '*.rst', } def make_message(error): return '%s %s:%s %s\n' % ( error.type, error.source, error.line, error.message, ) def check(file_staged_for_commit, options): basename = os.path.basename(file_staged_for_commit.path) if not fnmatch.fnmatch(basename, options.rst_files): return True errors = restructuredtext_lint.lint( file_staged_for_commit.contents, file_staged_for_commit.path, ) if errors: print('\n'.join(make_message(e) for e in errors)) return False else: return True ## Instruction: Add description to rst plugin ## Code After: """Check that files contains valid ReStructuredText.""" import os import fnmatch import restructuredtext_lint DEFAULTS = { 'files': '*.rst', } def make_message(error): return '%s %s:%s %s\n' % ( error.type, error.source, error.line, error.message, ) def check(file_staged_for_commit, options): basename = os.path.basename(file_staged_for_commit.path) if not fnmatch.fnmatch(basename, options.rst_files): return True errors = restructuredtext_lint.lint( file_staged_for_commit.contents, file_staged_for_commit.path, ) if errors: print('\n'.join(make_message(e) for e in errors)) return False else: return True
bc7b1fc053150728095ec5d0a41611aa4d4ede45
kerrokantasi/settings/__init__.py
kerrokantasi/settings/__init__.py
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
Remove JWT_AUTH check from settings
Remove JWT_AUTH check from settings JWT settings has been removed in OpenID change and currently there isn't use for this.
Python
mit
City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) - - if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": - raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
Remove JWT_AUTH check from settings
## Code Before: from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use. ## Instruction: Remove JWT_AUTH check from settings ## Code After: from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
c0fc60aa5fd51ac9a5795017fdc57d5b89b300e7
tests/check_locale_format_consistency.py
tests/check_locale_format_consistency.py
import re import json import glob locale_folder = "../locales/" locale_files = glob.glob(locale_folder + "*.json") locale_files = [filename.split("/")[-1] for filename in locale_files] locale_files.remove("en.json") reference = json.loads(open(locale_folder + "en.json").read()) for locale_file in locale_files: this_locale = json.loads(open(locale_folder + locale_file).read()) for key, string in reference.items(): if key in this_locale: subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string)) subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])) if any(key not in subkeys_in_ref for key in subkeys_in_this_locale): print("\n") print("==========================") print("Format inconsistency for string %s in %s:" % (key, locale_file)) print("%s -> %s " % ("en.json", string)) print("%s -> %s " % (locale_file, this_locale[key]))
import re import json import glob # List all locale files (except en.json being the ref) locale_folder = "../locales/" locale_files = glob.glob(locale_folder + "*.json") locale_files = [filename.split("/")[-1] for filename in locale_files] locale_files.remove("en.json") reference = json.loads(open(locale_folder + "en.json").read()) found_inconsistencies = False # Let's iterate over each locale file for locale_file in locale_files: this_locale = json.loads(open(locale_folder + locale_file).read()) # We iterate over all keys/string in en.json for key, string in reference.items(): # If there is a translation available for this key/string if key in this_locale: # Then we check that every "{stuff}" (for python's .format()) # should also be in the translated string, otherwise the .format # will trigger an exception! subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string)) subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])) if any(key not in subkeys_in_ref for key in subkeys_in_this_locale): found_inconsistencies = True print("\n") print("==========================") print("Format inconsistency for string %s in %s:" % (key, locale_file)) print("%s -> %s " % ("en.json", string)) print("%s -> %s " % (locale_file, this_locale[key])) if found_inconsistencies: sys.exit(1)
Add comments + return 1 if inconsistencies found
Add comments + return 1 if inconsistencies found
Python
agpl-3.0
YunoHost/yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost
import re import json import glob + # List all locale files (except en.json being the ref) locale_folder = "../locales/" locale_files = glob.glob(locale_folder + "*.json") locale_files = [filename.split("/")[-1] for filename in locale_files] locale_files.remove("en.json") reference = json.loads(open(locale_folder + "en.json").read()) + found_inconsistencies = False + + # Let's iterate over each locale file for locale_file in locale_files: this_locale = json.loads(open(locale_folder + locale_file).read()) + # We iterate over all keys/string in en.json for key, string in reference.items(): + # If there is a translation available for this key/string if key in this_locale: + # Then we check that every "{stuff}" (for python's .format()) + # should also be in the translated string, otherwise the .format + # will trigger an exception! subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string)) subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])) if any(key not in subkeys_in_ref for key in subkeys_in_this_locale): + found_inconsistencies = True print("\n") print("==========================") print("Format inconsistency for string %s in %s:" % (key, locale_file)) print("%s -> %s " % ("en.json", string)) print("%s -> %s " % (locale_file, this_locale[key])) + if found_inconsistencies: + sys.exit(1)
Add comments + return 1 if inconsistencies found
## Code Before: import re import json import glob locale_folder = "../locales/" locale_files = glob.glob(locale_folder + "*.json") locale_files = [filename.split("/")[-1] for filename in locale_files] locale_files.remove("en.json") reference = json.loads(open(locale_folder + "en.json").read()) for locale_file in locale_files: this_locale = json.loads(open(locale_folder + locale_file).read()) for key, string in reference.items(): if key in this_locale: subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string)) subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])) if any(key not in subkeys_in_ref for key in subkeys_in_this_locale): print("\n") print("==========================") print("Format inconsistency for string %s in %s:" % (key, locale_file)) print("%s -> %s " % ("en.json", string)) print("%s -> %s " % (locale_file, this_locale[key])) ## Instruction: Add comments + return 1 if inconsistencies found ## Code After: import re import json import glob # List all locale files (except en.json being the ref) locale_folder = "../locales/" locale_files = glob.glob(locale_folder + "*.json") locale_files = [filename.split("/")[-1] for filename in locale_files] locale_files.remove("en.json") reference = json.loads(open(locale_folder + "en.json").read()) found_inconsistencies = False # Let's iterate over each locale file for locale_file in locale_files: this_locale = json.loads(open(locale_folder + locale_file).read()) # We iterate over all keys/string in en.json for key, string in reference.items(): # If there is a translation available for this key/string if key in this_locale: # Then we check that every "{stuff}" (for python's .format()) # should also be in the translated string, otherwise the .format # will trigger an exception! subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string)) subkeys_in_this_locale = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])) if any(key not in subkeys_in_ref for key in subkeys_in_this_locale): found_inconsistencies = True print("\n") print("==========================") print("Format inconsistency for string %s in %s:" % (key, locale_file)) print("%s -> %s " % ("en.json", string)) print("%s -> %s " % (locale_file, this_locale[key])) if found_inconsistencies: sys.exit(1)
423dcb102fc2b7a1108a0b0fe1e116e8a5d451c9
netsecus/korrekturtools.py
netsecus/korrekturtools.py
from __future__ import unicode_literals import os def readStatus(student): student = student.lower() if not os.path.exists("attachments"): return if not os.path.exists(os.path.join("attachments", student)): return "Student ohne Abgabe" if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")): return "Unbearbeitet" statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r") status = statusfile.read() statusfile.close() return status def writeStatus(student, status): student = student.lower() status = status.lower() if not os.path.exists(os.path.join("attachments", student)): return statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w") statusfile.write(status) statusfile.close()
from __future__ import unicode_literals import os from . import helper def readStatus(student): student = student.lower() if not os.path.exists("attachments"): return if not os.path.exists(os.path.join("attachments", student)): return "Student ohne Abgabe" if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")): return "Unbearbeitet" statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r") status = statusfile.read() statusfile.close() return status def writeStatus(student, status): student = student.lower() status = status.lower() if not os.path.exists(os.path.join("attachments", student)): logging.error("Requested student '%s' hasn't submitted anything yet.") return statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w") statusfile.write(status) statusfile.close()
Add error message for malformed request
Add error message for malformed request
Python
mit
hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem
from __future__ import unicode_literals import os + + from . import helper + def readStatus(student): student = student.lower() if not os.path.exists("attachments"): return if not os.path.exists(os.path.join("attachments", student)): return "Student ohne Abgabe" if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")): return "Unbearbeitet" statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r") status = statusfile.read() statusfile.close() return status def writeStatus(student, status): student = student.lower() status = status.lower() if not os.path.exists(os.path.join("attachments", student)): + logging.error("Requested student '%s' hasn't submitted anything yet.") return statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w") statusfile.write(status) statusfile.close()
Add error message for malformed request
## Code Before: from __future__ import unicode_literals import os def readStatus(student): student = student.lower() if not os.path.exists("attachments"): return if not os.path.exists(os.path.join("attachments", student)): return "Student ohne Abgabe" if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")): return "Unbearbeitet" statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r") status = statusfile.read() statusfile.close() return status def writeStatus(student, status): student = student.lower() status = status.lower() if not os.path.exists(os.path.join("attachments", student)): return statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w") statusfile.write(status) statusfile.close() ## Instruction: Add error message for malformed request ## Code After: from __future__ import unicode_literals import os from . import helper def readStatus(student): student = student.lower() if not os.path.exists("attachments"): return if not os.path.exists(os.path.join("attachments", student)): return "Student ohne Abgabe" if not os.path.exists(os.path.join("attachments", student, "korrekturstatus.txt")): return "Unbearbeitet" statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "r") status = statusfile.read() statusfile.close() return status def writeStatus(student, status): student = student.lower() status = status.lower() if not os.path.exists(os.path.join("attachments", student)): logging.error("Requested student '%s' hasn't submitted anything yet.") return statusfile = open(os.path.join("attachments", student, "korrekturstatus.txt"), "w") statusfile.write(status) statusfile.close()
3cbc3b96d3f91c940c5d762ce08da9814c29b04d
utils/gyb_syntax_support/protocolsMap.py
utils/gyb_syntax_support/protocolsMap.py
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { 'ExpressibleByConditionElement': [ 'ExpressibleByConditionElementList' ], 'ExpressibleByDeclBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleByMemberDeclListItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByStmtBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByExprList': [ 'ExpressibleByConditionElement', 'ExpressibleBySyntaxBuildable' ] }
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'ExpressibleAsConditionElement': [ 'ExpressibleAsConditionElementList' ], 'ExpressibleAsDeclBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsMemberDeclListItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsStmtBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsExprList': [ 'ExpressibleAsConditionElement', 'ExpressibleAsSyntaxBuildable' ] }
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
Python
apache-2.0
roambotics/swift,glessard/swift,ahoppen/swift,roambotics/swift,apple/swift,roambotics/swift,gregomni/swift,ahoppen/swift,JGiola/swift,JGiola/swift,apple/swift,gregomni/swift,benlangmuir/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,ahoppen/swift,atrick/swift,benlangmuir/swift,gregomni/swift,atrick/swift,glessard/swift,rudkx/swift,benlangmuir/swift,glessard/swift,apple/swift,benlangmuir/swift,ahoppen/swift,rudkx/swift,roambotics/swift,roambotics/swift,glessard/swift,glessard/swift,ahoppen/swift,atrick/swift,apple/swift,JGiola/swift,JGiola/swift,rudkx/swift,atrick/swift,rudkx/swift,gregomni/swift,rudkx/swift,rudkx/swift,roambotics/swift,atrick/swift,gregomni/swift,apple/swift,JGiola/swift,ahoppen/swift,JGiola/swift,apple/swift,benlangmuir/swift
- SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { + SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { - 'ExpressibleByConditionElement': [ + 'ExpressibleAsConditionElement': [ - 'ExpressibleByConditionElementList' + 'ExpressibleAsConditionElementList' ], - 'ExpressibleByDeclBuildable': [ + 'ExpressibleAsDeclBuildable': [ - 'ExpressibleByCodeBlockItem', + 'ExpressibleAsCodeBlockItem', - 'ExpressibleByMemberDeclListItem', + 'ExpressibleAsMemberDeclListItem', - 'ExpressibleBySyntaxBuildable' + 'ExpressibleAsSyntaxBuildable' ], - 'ExpressibleByStmtBuildable': [ + 'ExpressibleAsStmtBuildable': [ - 'ExpressibleByCodeBlockItem', + 'ExpressibleAsCodeBlockItem', - 'ExpressibleBySyntaxBuildable' + 'ExpressibleAsSyntaxBuildable' ], - 'ExpressibleByExprList': [ + 'ExpressibleAsExprList': [ - 'ExpressibleByConditionElement', + 'ExpressibleAsConditionElement', - 'ExpressibleBySyntaxBuildable' + 'ExpressibleAsSyntaxBuildable' ] }
Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols"
## Code Before: SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { 'ExpressibleByConditionElement': [ 'ExpressibleByConditionElementList' ], 'ExpressibleByDeclBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleByMemberDeclListItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByStmtBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByExprList': [ 'ExpressibleByConditionElement', 'ExpressibleBySyntaxBuildable' ] } ## Instruction: Revert "[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols" ## Code After: SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'ExpressibleAsConditionElement': [ 'ExpressibleAsConditionElementList' ], 'ExpressibleAsDeclBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsMemberDeclListItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsStmtBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsExprList': [ 'ExpressibleAsConditionElement', 'ExpressibleAsSyntaxBuildable' ] }
1b3f97ff7bc219588b94a2346ac91f10203e44b9
matador/commands/deployment/__init__.py
matador/commands/deployment/__init__.py
from .deploy_sql_script import DeploySqlScript, DeployOraclePackage from .deploy_report import DeployExceleratorReport
from .deploy_sql_script import DeploySqlScript, DeployOraclePackage from .deploy_report import DeployExceleratorReport, DeployReportFile
Add report file deployment to init
Add report file deployment to init
Python
mit
Empiria/matador
from .deploy_sql_script import DeploySqlScript, DeployOraclePackage - from .deploy_report import DeployExceleratorReport + from .deploy_report import DeployExceleratorReport, DeployReportFile
Add report file deployment to init
## Code Before: from .deploy_sql_script import DeploySqlScript, DeployOraclePackage from .deploy_report import DeployExceleratorReport ## Instruction: Add report file deployment to init ## Code After: from .deploy_sql_script import DeploySqlScript, DeployOraclePackage from .deploy_report import DeployExceleratorReport, DeployReportFile
f55d590004874f9ec64c041b5630321e686bf6f9
mindbender/plugins/validate_id.py
mindbender/plugins/validate_id.py
import pyblish.api class ValidateMindbenderID(pyblish.api.InstancePlugin): """All models must have an ID attribute""" label = "Mindbender ID" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model"] def process(self, instance): from maya import cmds nodes = list(instance) nodes += cmds.listRelatives(instance, allDescendents=True) or list() missing = list() for node in nodes: # Only check transforms with a shape if not cmds.listRelatives(node, shapes=True): continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing))
import pyblish.api class ValidateMindbenderID(pyblish.api.InstancePlugin): """All models must have an ID attribute""" label = "Mindbender ID" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.lookdev"] def process(self, instance): from maya import cmds nodes = list(instance) nodes += cmds.listRelatives(instance, allDescendents=True) or list() missing = list() for node in nodes: # Only check transforms with a shape if not cmds.listRelatives(node, shapes=True): continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing))
Extend ID validator to lookdev
Extend ID validator to lookdev
Python
mit
mindbender-studio/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core,MoonShineVFX/core,getavalon/core,pyblish/pyblish-mindbender
import pyblish.api class ValidateMindbenderID(pyblish.api.InstancePlugin): """All models must have an ID attribute""" label = "Mindbender ID" order = pyblish.api.ValidatorOrder hosts = ["maya"] - families = ["mindbender.model"] + families = ["mindbender.model", "mindbender.lookdev"] def process(self, instance): from maya import cmds nodes = list(instance) nodes += cmds.listRelatives(instance, allDescendents=True) or list() missing = list() for node in nodes: # Only check transforms with a shape if not cmds.listRelatives(node, shapes=True): continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing))
Extend ID validator to lookdev
## Code Before: import pyblish.api class ValidateMindbenderID(pyblish.api.InstancePlugin): """All models must have an ID attribute""" label = "Mindbender ID" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model"] def process(self, instance): from maya import cmds nodes = list(instance) nodes += cmds.listRelatives(instance, allDescendents=True) or list() missing = list() for node in nodes: # Only check transforms with a shape if not cmds.listRelatives(node, shapes=True): continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing)) ## Instruction: Extend ID validator to lookdev ## Code After: import pyblish.api class ValidateMindbenderID(pyblish.api.InstancePlugin): """All models must have an ID attribute""" label = "Mindbender ID" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.model", "mindbender.lookdev"] def process(self, instance): from maya import cmds nodes = list(instance) nodes += cmds.listRelatives(instance, allDescendents=True) or list() missing = list() for node in nodes: # Only check transforms with a shape if not cmds.listRelatives(node, shapes=True): continue try: self.log.info("Checking '%s'" % node) cmds.getAttr(node + ".mbID") except ValueError: missing.append(node) assert not missing, ("Missing ID attribute on: %s" % ", ".join(missing))
09be419960d208967771d93025c4f86b80ebe4e9
python/qibuild/__init__.py
python/qibuild/__init__.py
""" This module contains a few functions for running CMake and building projects. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os import sys reload(sys) sys.setdefaultencoding('utf-8') QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items()))
""" This module contains a few functions for running CMake and building projects. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items()))
Revert "use utf-8 by default"
Revert "use utf-8 by default" This reverts commit a986aac5e3b4f065d6c2ab70129bde105651d2ca.
Python
bsd-3-clause
aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild
""" This module contains a few functions for running CMake and building projects. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os - import sys - reload(sys) - sys.setdefaultencoding('utf-8') QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items()))
Revert "use utf-8 by default"
## Code Before: """ This module contains a few functions for running CMake and building projects. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os import sys reload(sys) sys.setdefaultencoding('utf-8') QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items())) ## Instruction: Revert "use utf-8 by default" ## Code After: """ This module contains a few functions for running CMake and building projects. """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os QIBUILD_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def stringify_env(env): """ convert each key value pairs to strings in env list""" return dict(((str(key), str(val)) for key, val in env.items()))
c7cb6c1441bcfe359a9179858492044591e80007
osgtest/tests/test_10_condor.py
osgtest/tests/test_10_condor.py
from os.path import join import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.condor as condor import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service personal_condor_config = ''' DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD CONDOR_HOST = $(FULL_HOSTNAME) ''' class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG') if service.is_running('condor'): core.state['condor.running-service'] = True return core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf') files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor') core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog']) service.check_start('condor') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
from os.path import join import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.condor as condor import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service personal_condor_config = ''' DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD CONDOR_HOST = $(FULL_HOSTNAME) ''' class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG') if service.is_running('condor'): core.state['condor.running-service'] = True return core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf') files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor', chmod=0o644) core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog']) service.check_start('condor') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
Make the personal condor config world readable
Make the personal condor config world readable
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
from os.path import join import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.condor as condor import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service personal_condor_config = ''' DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD CONDOR_HOST = $(FULL_HOSTNAME) ''' class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG') if service.is_running('condor'): core.state['condor.running-service'] = True return core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf') - files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor') + files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor', chmod=0o644) core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog']) service.check_start('condor') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
Make the personal condor config world readable
## Code Before: from os.path import join import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.condor as condor import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service personal_condor_config = ''' DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD CONDOR_HOST = $(FULL_HOSTNAME) ''' class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG') if service.is_running('condor'): core.state['condor.running-service'] = True return core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf') files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor') core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog']) service.check_start('condor') core.state['condor.started-service'] = True core.state['condor.running-service'] = True ## Instruction: Make the personal condor config world readable ## Code After: from os.path import join import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.condor as condor import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service personal_condor_config = ''' DAEMON_LIST = COLLECTOR, MASTER, NEGOTIATOR, SCHEDD, STARTD CONDOR_HOST = $(FULL_HOSTNAME) ''' class TestStartCondor(osgunittest.OSGTestCase): def test_01_start_condor(self): core.state['condor.running-service'] = False core.skip_ok_unless_installed('condor') core.config['condor.collectorlog'] = condor.config_val('COLLECTOR_LOG') if service.is_running('condor'): core.state['condor.running-service'] = True return core.config['condor.personal_condor'] = join(condor.config_val('LOCAL_CONFIG_DIR'), '99-personal-condor.conf') files.write(core.config['condor.personal_condor'], personal_condor_config, owner='condor', chmod=0o644) core.config['condor.collectorlog_stat'] = core.get_stat(core.config['condor.collectorlog']) service.check_start('condor') core.state['condor.started-service'] = True core.state['condor.running-service'] = True
d8b477083866a105947281ca34cb6e215417f44d
packs/salt/actions/lib/utils.py
packs/salt/actions/lib/utils.py
import yaml action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Runner functions through Salt API", "enabled": True, "entry_point": "runner.py"} def generate_action(module_type, action): manifest = action_meta manifest['name'] = "{0}_{1}".format(module_type, action) manifest['parameters']['action']['default'] = action fh = open('{0}_{1}.yaml'.format(module_type, action), 'w') fh.write('---\n') fh.write(yaml.dump(manifest, default_flow_style=False)) fh.close() def sanitize_payload(keys_to_sanitize, payload): data = payload.copy() map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize) return data
import yaml from .meta import actions runner_action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Runner functions through Salt API", "enabled": True, "entry_point": "runner.py"} local_action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "args": { "type": "array", "required": False }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Execution modules through Salt API", "enabled": True, "entry_point": "local.py"} def generate_actions(): def create_file(mt, m, a): manifest = local_action_meta manifest['name'] = "{0}_{1}.{2}".format(mt, m, a) manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a) fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w') fh.write('---\n') fh.write(yaml.dump(manifest, default_flow_style=False)) fh.close() for key in actions: map(lambda l: create_file('local', key, l), actions[key]) def sanitize_payload(keys_to_sanitize, payload): ''' Removes sensitive data from payloads before publishing to the logs ''' data = payload.copy() map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize) return data
Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging.
Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging.
Python
apache-2.0
pidah/st2contrib,StackStorm/st2contrib,psychopenguin/st2contrib,lmEshoo/st2contrib,armab/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,psychopenguin/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,pidah/st2contrib
+ import yaml + from .meta import actions - action_meta = { + runner_action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Runner functions through Salt API", "enabled": True, "entry_point": "runner.py"} + local_action_meta = { + "name": "", + "parameters": { + "action": { + "type": "string", + "immutable": True, + "default": "" + }, + "args": { + "type": "array", + "required": False + }, + "kwargs": { + "type": "object", + "required": False + } + }, + "runner_type": "run-python", + "description": "Run Salt Execution modules through Salt API", + "enabled": True, + "entry_point": "local.py"} - def generate_action(module_type, action): - manifest = action_meta - manifest['name'] = "{0}_{1}".format(module_type, action) - manifest['parameters']['action']['default'] = action + def generate_actions(): + def create_file(mt, m, a): + manifest = local_action_meta + manifest['name'] = "{0}_{1}.{2}".format(mt, m, a) + manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a) + - fh = open('{0}_{1}.yaml'.format(module_type, action), 'w') + fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w') - fh.write('---\n') + fh.write('---\n') - fh.write(yaml.dump(manifest, default_flow_style=False)) + fh.write(yaml.dump(manifest, default_flow_style=False)) - fh.close() + fh.close() + for key in actions: + map(lambda l: create_file('local', key, l), actions[key]) def sanitize_payload(keys_to_sanitize, payload): + ''' + Removes sensitive data from payloads before + publishing to the logs + ''' data = payload.copy() map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize) return data
Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging.
## Code Before: import yaml action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Runner functions through Salt API", "enabled": True, "entry_point": "runner.py"} def generate_action(module_type, action): manifest = action_meta manifest['name'] = "{0}_{1}".format(module_type, action) manifest['parameters']['action']['default'] = action fh = open('{0}_{1}.yaml'.format(module_type, action), 'w') fh.write('---\n') fh.write(yaml.dump(manifest, default_flow_style=False)) fh.close() def sanitize_payload(keys_to_sanitize, payload): data = payload.copy() map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize) return data ## Instruction: Make distinction between local and runner action payload templates. Added small description for sanitizing the NetAPI payload for logging. ## Code After: import yaml from .meta import actions runner_action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Runner functions through Salt API", "enabled": True, "entry_point": "runner.py"} local_action_meta = { "name": "", "parameters": { "action": { "type": "string", "immutable": True, "default": "" }, "args": { "type": "array", "required": False }, "kwargs": { "type": "object", "required": False } }, "runner_type": "run-python", "description": "Run Salt Execution modules through Salt API", "enabled": True, "entry_point": "local.py"} def generate_actions(): def create_file(mt, m, a): manifest = local_action_meta manifest['name'] = "{0}_{1}.{2}".format(mt, m, a) manifest['parameters']['action']['default'] = "{0}.{1}".format(m, a) fh = open('{0}_{1}.{2}.yaml'.format(mt, m, a), 'w') fh.write('---\n') fh.write(yaml.dump(manifest, default_flow_style=False)) fh.close() for key in actions: map(lambda l: create_file('local', key, l), actions[key]) def sanitize_payload(keys_to_sanitize, payload): ''' Removes sensitive data from payloads before publishing to the logs ''' data = payload.copy() map(lambda k: data.update({k: "*" * len(payload[k])}), keys_to_sanitize) return data
60625877a23e26e66c2c97cbeb4f139ede717eda
B.py
B.py
from collections import namedtuple import matplotlib.pyplot as plt BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p']) bs = [] with open('B.txt') as f: for line in f.readlines()[1:]: bs.append(BCand(*[float(v) for v in line.strip().split(',')])) masses = [b.m for b in bs] plt.hist(masses, 60, histtype='stepfilled') plt.xlabel(r'$m_B / \mathrm{GeV}$') plt.savefig('mass.pdf')
from collections import namedtuple import matplotlib.pyplot as plt import numpy as np BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p']) bs = [BCand(*b) for b in np.genfromtxt('B.txt', skip_header=1, delimiter=',')] masses = [b.m for b in bs] ns, bins, _ = plt.hist(masses, 60, histtype='stepfilled', facecolor='r', edgecolor='none') centers = bins[:-1] + (bins[1:] - bins[:-1]) / 2 merr = np.sqrt(ns) plt.errorbar(centers, ns, yerr=merr, fmt='b+') plt.xlabel(r'$m_B / \mathrm{GeV}$') plt.savefig('mass.pdf')
Use numpy for readin and add errorbars.
Use numpy for readin and add errorbars.
Python
mit
bixel/python-introduction
from collections import namedtuple import matplotlib.pyplot as plt + import numpy as np BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p']) + bs = [BCand(*b) for b in np.genfromtxt('B.txt', skip_header=1, delimiter=',')] - bs = [] - - with open('B.txt') as f: - for line in f.readlines()[1:]: - bs.append(BCand(*[float(v) for v in line.strip().split(',')])) masses = [b.m for b in bs] - plt.hist(masses, 60, histtype='stepfilled') + ns, bins, _ = plt.hist(masses, 60, histtype='stepfilled', facecolor='r', + edgecolor='none') + centers = bins[:-1] + (bins[1:] - bins[:-1]) / 2 + merr = np.sqrt(ns) + plt.errorbar(centers, ns, yerr=merr, fmt='b+') plt.xlabel(r'$m_B / \mathrm{GeV}$') plt.savefig('mass.pdf')
Use numpy for readin and add errorbars.
## Code Before: from collections import namedtuple import matplotlib.pyplot as plt BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p']) bs = [] with open('B.txt') as f: for line in f.readlines()[1:]: bs.append(BCand(*[float(v) for v in line.strip().split(',')])) masses = [b.m for b in bs] plt.hist(masses, 60, histtype='stepfilled') plt.xlabel(r'$m_B / \mathrm{GeV}$') plt.savefig('mass.pdf') ## Instruction: Use numpy for readin and add errorbars. ## Code After: from collections import namedtuple import matplotlib.pyplot as plt import numpy as np BCand = namedtuple('BCand', ['m', 'merr', 'pt', 'p']) bs = [BCand(*b) for b in np.genfromtxt('B.txt', skip_header=1, delimiter=',')] masses = [b.m for b in bs] ns, bins, _ = plt.hist(masses, 60, histtype='stepfilled', facecolor='r', edgecolor='none') centers = bins[:-1] + (bins[1:] - bins[:-1]) / 2 merr = np.sqrt(ns) plt.errorbar(centers, ns, yerr=merr, fmt='b+') plt.xlabel(r'$m_B / \mathrm{GeV}$') plt.savefig('mass.pdf')
8a544ac2db71d4041c77fdb0ddfe27b84b565bb5
salt/utils/saltminionservice.py
salt/utils/saltminionservice.py
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def console_event_handler(event): if event == 5: # Do nothing on CTRL_LOGOFF_EVENT return True return False def _main(): win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service" This reverts commit a7ddf81b37b578b1448f83b0efb4f7116de0c3fb.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror - import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") - def console_event_handler(event): - if event == 5: - # Do nothing on CTRL_LOGOFF_EVENT - return True - return False def _main(): - win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
## Code Before: from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def console_event_handler(event): if event == 5: # Do nothing on CTRL_LOGOFF_EVENT return True return False def _main(): win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main() ## Instruction: Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service" ## Code After: from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
2f8c3ab7ecd0606069d524192c551e7be77ca461
zhihudaily/views/with_image.py
zhihudaily/views/with_image.py
from __future__ import absolute_import, unicode_literals import datetime from flask import render_template, Blueprint from zhihudaily.utils import make_request from zhihudaily.cache import cache image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') (display_date, date, news_list) = get_news_info(r) news_list = handle_image(news_list) day_before = ( datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) ).strftime('%Y%m%d') return render_template('with_image.html', lists=news_list, display_date=display_date, day_before=day_before, is_today=True)
from __future__ import absolute_import, unicode_literals from flask import render_template, Blueprint, json from zhihudaily.cache import cache from zhihudaily.models import Zhihudaily from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" day = Date() news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() return render_template('with_image.html', lists=json.loads(news.json_news), display_date=news.display_date, day_before=day.day_before, is_today=True)
Switch to use database for image ui
Switch to use database for image ui
Python
mit
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
from __future__ import absolute_import, unicode_literals - import datetime - from flask import render_template, Blueprint + from flask import render_template, Blueprint, json - from zhihudaily.utils import make_request from zhihudaily.cache import cache + from zhihudaily.models import Zhihudaily + from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" + day = Date() + news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() + - r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') - (display_date, date, news_list) = get_news_info(r) - news_list = handle_image(news_list) - day_before = ( - datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) - ).strftime('%Y%m%d') - return render_template('with_image.html', lists=news_list, + return render_template('with_image.html', + lists=json.loads(news.json_news), - display_date=display_date, + display_date=news.display_date, - day_before=day_before, + day_before=day.day_before, is_today=True)
Switch to use database for image ui
## Code Before: from __future__ import absolute_import, unicode_literals import datetime from flask import render_template, Blueprint from zhihudaily.utils import make_request from zhihudaily.cache import cache image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') (display_date, date, news_list) = get_news_info(r) news_list = handle_image(news_list) day_before = ( datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) ).strftime('%Y%m%d') return render_template('with_image.html', lists=news_list, display_date=display_date, day_before=day_before, is_today=True) ## Instruction: Switch to use database for image ui ## Code After: from __future__ import absolute_import, unicode_literals from flask import render_template, Blueprint, json from zhihudaily.cache import cache from zhihudaily.models import Zhihudaily from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" day = Date() news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() return render_template('with_image.html', lists=json.loads(news.json_news), display_date=news.display_date, day_before=day.day_before, is_today=True)
5c405745c954c2aa6121ddd82fb13ffef11b3150
pyp2rpm/utils.py
pyp2rpm/utils.py
import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSES: license.append(settings.TROVE_LICENSES[stripped]) else: license.append("Unknown License") return ' and '.join(license)
import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSES: license.append(settings.TROVE_LICENSES[stripped]) return ' and '.join(license)
Revert the commit "bc85b4e" to keep the current solution
Revert the commit "bc85b4e" to keep the current solution
Python
mit
henrysher/spec4pypi
import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSES: license.append(settings.TROVE_LICENSES[stripped]) - else: - license.append("Unknown License") return ' and '.join(license)
Revert the commit "bc85b4e" to keep the current solution
## Code Before: import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSES: license.append(settings.TROVE_LICENSES[stripped]) else: license.append("Unknown License") return ' and '.join(license) ## Instruction: Revert the commit "bc85b4e" to keep the current solution ## Code After: import functools from pyp2rpm import settings def memoize_by_args(func): """Memoizes return value of a func based on args.""" memory = {} @functools.wraps(func) def memoized(*args): if not args in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifier in trove: if classifier is None: continue if 'License' in classifier != -1: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TROVE_LICENSES: license.append(settings.TROVE_LICENSES[stripped]) return ' and '.join(license)
58eb4b2b034d90f45b3daa12900f24a390bb4782
setuptools/command/bdist_rpm.py
setuptools/command/bdist_rpm.py
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm class bdist_rpm(_bdist_rpm): def run(self): # ensure distro name is up-to-date self.run_command('egg_info') _bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-','_') spec = _bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm class bdist_rpm(_bdist_rpm): """ Override the default bdist_rpm behavior to do the following: 1. Run egg_info to ensure the name and version are properly calculated. 2. Always run 'install' using --single-version-externally-managed to disable eggs in RPM distributions. 3. Replace dash with underscore in the version numbers for better RPM compatibility. """ def run(self): # ensure distro name is up-to-date self.run_command('egg_info') _bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-','_') spec = _bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec
Replace outdated deprecating comments with a proper doc string.
Replace outdated deprecating comments with a proper doc string.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
- from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm class bdist_rpm(_bdist_rpm): + """ + Override the default bdist_rpm behavior to do the following: + + 1. Run egg_info to ensure the name and version are properly calculated. + 2. Always run 'install' using --single-version-externally-managed to + disable eggs in RPM distributions. + 3. Replace dash with underscore in the version numbers for better RPM + compatibility. + """ def run(self): # ensure distro name is up-to-date self.run_command('egg_info') _bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-','_') spec = _bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec
Replace outdated deprecating comments with a proper doc string.
## Code Before: from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm class bdist_rpm(_bdist_rpm): def run(self): # ensure distro name is up-to-date self.run_command('egg_info') _bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-','_') spec = _bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec ## Instruction: Replace outdated deprecating comments with a proper doc string. ## Code After: from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm class bdist_rpm(_bdist_rpm): """ Override the default bdist_rpm behavior to do the following: 1. Run egg_info to ensure the name and version are properly calculated. 2. Always run 'install' using --single-version-externally-managed to disable eggs in RPM distributions. 3. Replace dash with underscore in the version numbers for better RPM compatibility. """ def run(self): # ensure distro name is up-to-date self.run_command('egg_info') _bdist_rpm.run(self) def _make_spec_file(self): version = self.distribution.get_version() rpmversion = version.replace('-','_') spec = _bdist_rpm._make_spec_file(self) line23 = '%define version ' + version line24 = '%define version ' + rpmversion spec = [ line.replace( "Source0: %{name}-%{version}.tar", "Source0: %{name}-%{unmangled_version}.tar" ).replace( "setup.py install ", "setup.py install --single-version-externally-managed " ).replace( "%setup", "%setup -n %{name}-%{unmangled_version}" ).replace(line23, line24) for line in spec ] insert_loc = spec.index(line24) + 1 unmangled_version = "%define unmangled_version " + version spec.insert(insert_loc, unmangled_version) return spec
678532961cbc676fb3b82fa58185b281a8a4a7b3
rex/preconstrained_file_stream.py
rex/preconstrained_file_stream.py
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def __getstate__(self): d = super().__getstate__() d['preconstraining_handler'] = None return d
Fix a bug that leads to failures in pickling.
SimPreconstrainedFileStream: Fix a bug that leads to failures in pickling.
Python
bsd-2-clause
shellphish/rex,shellphish/rex
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + def __getstate__(self): + d = super().__getstate__() + d['preconstraining_handler'] = None + return d +
Fix a bug that leads to failures in pickling.
## Code Before: from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied ## Instruction: Fix a bug that leads to failures in pickling. ## Code After: from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def __getstate__(self): d = super().__getstate__() d['preconstraining_handler'] = None return d
91f503cd99dfa6fc6562afc1b627b6f8b0f1d91b
addons/l10n_ar/models/res_partner_bank.py
addons/l10n_ar/models/res_partner_bank.py
from odoo import models, api, _ import stdnum.ar.cbu def validate_cbu(cbu): return stdnum.ar.cbu.validate(cbu) class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu'
from odoo import models, api, _ from odoo.exceptions import ValidationError import stdnum.ar import logging _logger = logging.getLogger(__name__) def validate_cbu(cbu): try: return stdnum.ar.cbu.validate(cbu) except Exception as error: msg = _("Argentinian CBU was not validated: %s" % repr(error)) _logger.log(25, msg) raise ValidationError(msg) class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu'
Fix ImportError: No module named 'stdnum.ar.cbu'
[FIX] l10n_ar: Fix ImportError: No module named 'stdnum.ar.cbu' Since stdnum.ar.cbu is not available in odoo saas enviroment because is using an old version of stdnum package, we add a try exept in order to catch this and manage the error properly which is raise an exception and leave a message in the log telling the user that the cbu was not able to validate. closes odoo/odoo#40383 X-original-commit: 25d483fc3fc05fd47c72c3d96c02fed12b998b0d Signed-off-by: Josse Colpaert <1f46e7f017caa89a77c9557ed26b800e8d5d7700@openerp.com>
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
from odoo import models, api, _ + from odoo.exceptions import ValidationError - import stdnum.ar.cbu + import stdnum.ar + import logging + _logger = logging.getLogger(__name__) def validate_cbu(cbu): + try: - return stdnum.ar.cbu.validate(cbu) + return stdnum.ar.cbu.validate(cbu) + except Exception as error: + msg = _("Argentinian CBU was not validated: %s" % repr(error)) + _logger.log(25, msg) + raise ValidationError(msg) class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu'
Fix ImportError: No module named 'stdnum.ar.cbu'
## Code Before: from odoo import models, api, _ import stdnum.ar.cbu def validate_cbu(cbu): return stdnum.ar.cbu.validate(cbu) class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu' ## Instruction: Fix ImportError: No module named 'stdnum.ar.cbu' ## Code After: from odoo import models, api, _ from odoo.exceptions import ValidationError import stdnum.ar import logging _logger = logging.getLogger(__name__) def validate_cbu(cbu): try: return stdnum.ar.cbu.validate(cbu) except Exception as error: msg = _("Argentinian CBU was not validated: %s" % repr(error)) _logger.log(25, msg) raise ValidationError(msg) class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' @api.model def _get_supported_account_types(self): """ Add new account type named cbu used in Argentina """ res = super()._get_supported_account_types() res.append(('cbu', _('CBU'))) return res @api.model def retrieve_acc_type(self, acc_number): try: validate_cbu(acc_number) except Exception: return super().retrieve_acc_type(acc_number) return 'cbu'
5cd0507e99d8f78597d225266ec09f6588308396
tests/app/public_contracts/test_POST_notification.py
tests/app/public_contracts/test_POST_notification.py
from flask import json from . import return_json_from_response, validate_v0 from tests import create_authorization_header def _post_notification(client, template, url, to): data = { 'to': to, 'template': str(template.id) } auth_header = create_authorization_header(service_id=template.service_id) return client.post( path=url, data=json.dumps(data), headers=[('Content-Type', 'application/json'), auth_header] ) def test_post_sms_contract(client, mocker, sample_template): mocker.patch('app.celery.tasks.send_sms.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_template, url='/notifications/sms', to='07700 900 855' )) validate_v0(response_json, 'POST_notification_return_sms.json') def test_post_email_contract(client, mocker, sample_email_template): mocker.patch('app.celery.tasks.send_email.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_email_template, url='/notifications/email', to='foo@bar.com' )) validate_v0(response_json, 'POST_notification_return_email.json')
from flask import json from . import return_json_from_response, validate_v0 from tests import create_authorization_header def _post_notification(client, template, url, to): data = { 'to': to, 'template': str(template.id) } auth_header = create_authorization_header(service_id=template.service_id) return client.post( path=url, data=json.dumps(data), headers=[('Content-Type', 'application/json'), auth_header] ) def test_post_sms_contract(client, mocker, sample_template): mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_template, url='/notifications/sms', to='07700 900 855' )) validate_v0(response_json, 'POST_notification_return_sms.json') def test_post_email_contract(client, mocker, sample_email_template): mocker.patch('app.celery.provider_tasks.deliver_email.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_email_template, url='/notifications/email', to='foo@bar.com' )) validate_v0(response_json, 'POST_notification_return_email.json')
Revert "Fixed faoiling jenkins tests. Mocked the required functions"
Revert "Fixed faoiling jenkins tests. Mocked the required functions" This reverts commit 4b60c8dadaa413581cd373c9059ff95ecf751159.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
from flask import json from . import return_json_from_response, validate_v0 from tests import create_authorization_header def _post_notification(client, template, url, to): data = { 'to': to, 'template': str(template.id) } auth_header = create_authorization_header(service_id=template.service_id) return client.post( path=url, data=json.dumps(data), headers=[('Content-Type', 'application/json'), auth_header] ) def test_post_sms_contract(client, mocker, sample_template): - mocker.patch('app.celery.tasks.send_sms.apply_async') + mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_template, url='/notifications/sms', to='07700 900 855' )) validate_v0(response_json, 'POST_notification_return_sms.json') def test_post_email_contract(client, mocker, sample_email_template): - mocker.patch('app.celery.tasks.send_email.apply_async') + mocker.patch('app.celery.provider_tasks.deliver_email.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_email_template, url='/notifications/email', to='foo@bar.com' )) validate_v0(response_json, 'POST_notification_return_email.json')
Revert "Fixed faoiling jenkins tests. Mocked the required functions"
## Code Before: from flask import json from . import return_json_from_response, validate_v0 from tests import create_authorization_header def _post_notification(client, template, url, to): data = { 'to': to, 'template': str(template.id) } auth_header = create_authorization_header(service_id=template.service_id) return client.post( path=url, data=json.dumps(data), headers=[('Content-Type', 'application/json'), auth_header] ) def test_post_sms_contract(client, mocker, sample_template): mocker.patch('app.celery.tasks.send_sms.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_template, url='/notifications/sms', to='07700 900 855' )) validate_v0(response_json, 'POST_notification_return_sms.json') def test_post_email_contract(client, mocker, sample_email_template): mocker.patch('app.celery.tasks.send_email.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_email_template, url='/notifications/email', to='foo@bar.com' )) validate_v0(response_json, 'POST_notification_return_email.json') ## Instruction: Revert "Fixed faoiling jenkins tests. Mocked the required functions" ## Code After: from flask import json from . import return_json_from_response, validate_v0 from tests import create_authorization_header def _post_notification(client, template, url, to): data = { 'to': to, 'template': str(template.id) } auth_header = create_authorization_header(service_id=template.service_id) return client.post( path=url, data=json.dumps(data), headers=[('Content-Type', 'application/json'), auth_header] ) def test_post_sms_contract(client, mocker, sample_template): mocker.patch('app.celery.provider_tasks.deliver_sms.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_template, url='/notifications/sms', to='07700 900 855' )) validate_v0(response_json, 'POST_notification_return_sms.json') def test_post_email_contract(client, mocker, sample_email_template): mocker.patch('app.celery.provider_tasks.deliver_email.apply_async') mocker.patch('app.encryption.encrypt', return_value="something_encrypted") response_json = return_json_from_response(_post_notification( client, sample_email_template, url='/notifications/email', to='foo@bar.com' )) validate_v0(response_json, 'POST_notification_return_email.json')
4467ffe669eec09bab16f4e5a3256ed333c5d3d5
rcamp/lib/ldap_utils.py
rcamp/lib/ldap_utils.py
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
Set bytes_mode=False for future compatability with Python3
Set bytes_mode=False for future compatability with Python3
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) - conn = ldap.initialize(server) + conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
Set bytes_mode=False for future compatability with Python3
## Code Before: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org ## Instruction: Set bytes_mode=False for future compatability with Python3 ## Code After: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
c872b9991ec1a80d03906cebfb43e71335ba9c26
tests/run/generator_frame_cycle.py
tests/run/generator_frame_cycle.py
import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) assert sys.exc_info()[1] is exc, sys.exc_info() del g assert sys.exc_info()[1] is exc, sys.exc_info() if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit)
import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) # CPython 3.3 handles this incorrectly itself :) if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() del g if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() return tuple(testit)
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
Python
apache-2.0
cython/cython,cython/cython,da-woods/cython,scoder/cython,cython/cython,scoder/cython,scoder/cython,cython/cython,da-woods/cython,da-woods/cython,scoder/cython,da-woods/cython
import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g - if cython.compiled: - # FIXME: this should not be necessary, but I can't see how to do it... - import gc; gc.collect() return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) + # CPython 3.3 handles this incorrectly itself :) + if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: - assert sys.exc_info()[1] is exc, sys.exc_info() + assert sys.exc_info()[1] is exc, sys.exc_info() del g + if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: - assert sys.exc_info()[1] is exc, sys.exc_info() + assert sys.exc_info()[1] is exc, sys.exc_info() - if cython.compiled: - # FIXME: this should not be necessary, but I can't see how to do it... - import gc; gc.collect() return tuple(testit)
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
## Code Before: import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) assert sys.exc_info()[1] is exc, sys.exc_info() del g assert sys.exc_info()[1] is exc, sys.exc_info() if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit) ## Instruction: Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later. ## Code After: import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) # CPython 3.3 handles this incorrectly itself :) if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() del g if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() return tuple(testit)
88f699690a48bc9e204c561443a53ca03dcf1ae6
test/python_api/default-constructor/sb_type.py
test/python_api/default-constructor/sb_type.py
import sys import lldb def fuzz_obj(obj): obj.GetName() obj.GetByteSize() #obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) obj.GetChildIndexForName(True, "_member_field") obj.IsAPointerType() obj.GetPointeeType() obj.GetDescription(lldb.SBStream())
import sys import lldb def fuzz_obj(obj): obj.GetName() obj.GetByteSize() #obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) obj.GetChildIndexForName(True, "_member_field") obj.IsAPointerType() obj.GetPointeeType() obj.GetDescription(lldb.SBStream()) obj.IsPointerType(None) lldb.SBType.IsPointerType(None)
Add fuzz calls for SBType::IsPointerType(void *opaque_type).
Add fuzz calls for SBType::IsPointerType(void *opaque_type). git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@134551 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
import sys import lldb def fuzz_obj(obj): obj.GetName() obj.GetByteSize() #obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) obj.GetChildIndexForName(True, "_member_field") obj.IsAPointerType() obj.GetPointeeType() obj.GetDescription(lldb.SBStream()) + obj.IsPointerType(None) + lldb.SBType.IsPointerType(None)
Add fuzz calls for SBType::IsPointerType(void *opaque_type).
## Code Before: import sys import lldb def fuzz_obj(obj): obj.GetName() obj.GetByteSize() #obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) obj.GetChildIndexForName(True, "_member_field") obj.IsAPointerType() obj.GetPointeeType() obj.GetDescription(lldb.SBStream()) ## Instruction: Add fuzz calls for SBType::IsPointerType(void *opaque_type). ## Code After: import sys import lldb def fuzz_obj(obj): obj.GetName() obj.GetByteSize() #obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) obj.GetChildIndexForName(True, "_member_field") obj.IsAPointerType() obj.GetPointeeType() obj.GetDescription(lldb.SBStream()) obj.IsPointerType(None) lldb.SBType.IsPointerType(None)
4636c9394138534fc39cc5bdac373b97919ffd01
server/info/services.py
server/info/services.py
"""info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter(column__uid=uid).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
"""info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter( column__uid=uid ).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().only('uid', 'name').order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
Modify django orm filter, add only
Modify django orm filter, add only
Python
mit
istommao/codingcatweb,istommao/codingcatweb,istommao/codingcatweb
"""info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" - queryset = Article.objects.filter(column__uid=uid).order_by('id') + queryset = Article.objects.filter( + column__uid=uid + ).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" - queryset = Column.objects.all().order_by('-id') + queryset = Column.objects.all().only('uid', 'name').order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
Modify django orm filter, add only
## Code Before: """info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter(column__uid=uid).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id') ## Instruction: Modify django orm filter, add only ## Code After: """info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter( column__uid=uid ).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().only('uid', 'name').order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
437ed5ee5e919186eabd1d71b0c1949adc1cf378
src/orca/gnome-terminal.py
src/orca/gnome-terminal.py
import a11y import speech def onTextInserted (e): if e.source.role != "terminal": return speech.say ("default", e.any_data) def onTextDeleted (event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ # Ignore text deletions from non-focused objects, unless the # currently focused object is the parent of the object from which # text was deleted # if (event.source != a11y.focusedObject) \ and (event.source.parent != a11y.focusedObject): pass else: brlUpdateText (event.source)
import a11y import speech import default def onTextInserted (e): if e.source.role != "terminal": return speech.say ("default", e.any_data) def onTextDeleted (event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ # Ignore text deletions from non-focused objects, unless the # currently focused object is the parent of the object from which # text was deleted # if (event.source != a11y.focusedObject) \ and (event.source.parent != a11y.focusedObject): pass else: default.brlUpdateText (event.source)
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
Python
lgpl-2.1
GNOME/orca,h4ck3rm1k3/orca-sonar,pvagner/orca,h4ck3rm1k3/orca-sonar,GNOME/orca,pvagner/orca,h4ck3rm1k3/orca-sonar,chrys87/orca-beep,chrys87/orca-beep,pvagner/orca,pvagner/orca,chrys87/orca-beep,GNOME/orca,chrys87/orca-beep,GNOME/orca
import a11y import speech + import default def onTextInserted (e): if e.source.role != "terminal": return speech.say ("default", e.any_data) def onTextDeleted (event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ # Ignore text deletions from non-focused objects, unless the # currently focused object is the parent of the object from which # text was deleted # if (event.source != a11y.focusedObject) \ and (event.source.parent != a11y.focusedObject): pass else: - brlUpdateText (event.source) + default.brlUpdateText (event.source)
Call default.brlUpdateText instead of brlUpdateText (which was undefined)
## Code Before: import a11y import speech def onTextInserted (e): if e.source.role != "terminal": return speech.say ("default", e.any_data) def onTextDeleted (event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ # Ignore text deletions from non-focused objects, unless the # currently focused object is the parent of the object from which # text was deleted # if (event.source != a11y.focusedObject) \ and (event.source.parent != a11y.focusedObject): pass else: brlUpdateText (event.source) ## Instruction: Call default.brlUpdateText instead of brlUpdateText (which was undefined) ## Code After: import a11y import speech import default def onTextInserted (e): if e.source.role != "terminal": return speech.say ("default", e.any_data) def onTextDeleted (event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ # Ignore text deletions from non-focused objects, unless the # currently focused object is the parent of the object from which # text was deleted # if (event.source != a11y.focusedObject) \ and (event.source.parent != a11y.focusedObject): pass else: default.brlUpdateText (event.source)
45b3fc7babfbd922bdb174e5156f54c567a66de4
plotly/tests/test_core/test_graph_objs/test_graph_objs_tools.py
plotly/tests/test_core/test_graph_objs/test_graph_objs_tools.py
from __future__ import absolute_import from unittest import TestCase
from __future__ import absolute_import from unittest import TestCase from plotly.graph_objs import graph_objs as go from plotly.graph_objs import graph_objs_tools as got class TestGetRole(TestCase): def test_get_role_no_value(self): # this is a bit fragile, but we pick a few stable values # the location in the figure matters for this test! fig = go.Figure(data=[{}]) fig.data[0].marker.color = 'red' fig.layout.title = 'some-title' parent_key_role_tuples = [ (fig.data[0], 'x', 'data'), (fig.data[0], 'marker', 'object'), (fig.data[0].marker, 'color', 'style'), (fig.layout, 'title', 'info'), (fig, 'data', 'object'), ] for parent, key, role in parent_key_role_tuples: self.assertEqual(got.get_role(parent, key), role, msg=key) def test_get_role_with_value(self): # some attributes are conditionally considered data if they're arrays # the location in the figure matters for this test! fig = go.Figure(data=[{}]) fig.data[0].marker.color = 'red' parent_key_value_role_tuples = [ (fig.data[0], 'x', 'wh0cares', 'data'), (fig.data[0], 'marker', 'wh0cares', 'object'), (fig.data[0].marker, 'color', 'red', 'style'), (fig.data[0].marker, 'color', ['red'], 'data') ] for parent, key, value, role in parent_key_value_role_tuples: self.assertEqual(got.get_role(parent, key, value), role, msg=(key, value))
Add some :tiger2:s for `graph_objs_tools.py`.
Add some :tiger2:s for `graph_objs_tools.py`.
Python
mit
plotly/plotly.py,plotly/python-api,plotly/plotly.py,plotly/python-api,plotly/plotly.py,plotly/python-api
from __future__ import absolute_import from unittest import TestCase + from plotly.graph_objs import graph_objs as go + from plotly.graph_objs import graph_objs_tools as got + + + class TestGetRole(TestCase): + + def test_get_role_no_value(self): + + # this is a bit fragile, but we pick a few stable values + + # the location in the figure matters for this test! + fig = go.Figure(data=[{}]) + fig.data[0].marker.color = 'red' + fig.layout.title = 'some-title' + + parent_key_role_tuples = [ + (fig.data[0], 'x', 'data'), + (fig.data[0], 'marker', 'object'), + (fig.data[0].marker, 'color', 'style'), + (fig.layout, 'title', 'info'), + (fig, 'data', 'object'), + ] + for parent, key, role in parent_key_role_tuples: + self.assertEqual(got.get_role(parent, key), role, msg=key) + + def test_get_role_with_value(self): + + # some attributes are conditionally considered data if they're arrays + + # the location in the figure matters for this test! + fig = go.Figure(data=[{}]) + fig.data[0].marker.color = 'red' + + parent_key_value_role_tuples = [ + (fig.data[0], 'x', 'wh0cares', 'data'), + (fig.data[0], 'marker', 'wh0cares', 'object'), + (fig.data[0].marker, 'color', 'red', 'style'), + (fig.data[0].marker, 'color', ['red'], 'data') + ] + for parent, key, value, role in parent_key_value_role_tuples: + self.assertEqual(got.get_role(parent, key, value), role, + msg=(key, value)) +
Add some :tiger2:s for `graph_objs_tools.py`.
## Code Before: from __future__ import absolute_import from unittest import TestCase ## Instruction: Add some :tiger2:s for `graph_objs_tools.py`. ## Code After: from __future__ import absolute_import from unittest import TestCase from plotly.graph_objs import graph_objs as go from plotly.graph_objs import graph_objs_tools as got class TestGetRole(TestCase): def test_get_role_no_value(self): # this is a bit fragile, but we pick a few stable values # the location in the figure matters for this test! fig = go.Figure(data=[{}]) fig.data[0].marker.color = 'red' fig.layout.title = 'some-title' parent_key_role_tuples = [ (fig.data[0], 'x', 'data'), (fig.data[0], 'marker', 'object'), (fig.data[0].marker, 'color', 'style'), (fig.layout, 'title', 'info'), (fig, 'data', 'object'), ] for parent, key, role in parent_key_role_tuples: self.assertEqual(got.get_role(parent, key), role, msg=key) def test_get_role_with_value(self): # some attributes are conditionally considered data if they're arrays # the location in the figure matters for this test! fig = go.Figure(data=[{}]) fig.data[0].marker.color = 'red' parent_key_value_role_tuples = [ (fig.data[0], 'x', 'wh0cares', 'data'), (fig.data[0], 'marker', 'wh0cares', 'object'), (fig.data[0].marker, 'color', 'red', 'style'), (fig.data[0].marker, 'color', ['red'], 'data') ] for parent, key, value, role in parent_key_value_role_tuples: self.assertEqual(got.get_role(parent, key, value), role, msg=(key, value))
668a5240c29047d86fe9451f3078bb163bea0db9
skan/__init__.py
skan/__init__.py
from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
Add version info to package init
Add version info to package init
Python
bsd-3-clause
jni/skan
from .csr import skeleton_to_csgraph, branch_statistics, summarise + + __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise'] +
Add version info to package init
## Code Before: from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise'] ## Instruction: Add version info to package init ## Code After: from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
2d9fce5715b2d7d5b920d2e77212f076e9ebd1be
staticgen_demo/staticgen_views.py
staticgen_demo/staticgen_views.py
from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews)
from __future__ import unicode_literals from django.conf import settings from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) class StaticgenCMSView(StaticgenView): def items(self): try: from cms.models import Title except ImportError: # pragma: no cover # django-cms is not installed. return super(StaticgenCMSView, self).items() items = Title.objects.public().filter( page__login_required=False, page__site_id=settings.SITE_ID, ).order_by('page__path') return items def url(self, obj): translation.activate(obj.language) url = obj.page.get_absolute_url(obj.language) translation.deactivate() return url staticgen_pool.register(StaticgenCMSView)
Add CMS Pages to staticgen registry.
Add CMS Pages to staticgen registry.
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
from __future__ import unicode_literals + + from django.conf import settings + from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) + + class StaticgenCMSView(StaticgenView): + + def items(self): + try: + from cms.models import Title + except ImportError: # pragma: no cover + # django-cms is not installed. + return super(StaticgenCMSView, self).items() + + items = Title.objects.public().filter( + page__login_required=False, + page__site_id=settings.SITE_ID, + ).order_by('page__path') + return items + + def url(self, obj): + translation.activate(obj.language) + url = obj.page.get_absolute_url(obj.language) + translation.deactivate() + return url + + staticgen_pool.register(StaticgenCMSView) +
Add CMS Pages to staticgen registry.
## Code Before: from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) ## Instruction: Add CMS Pages to staticgen registry. ## Code After: from __future__ import unicode_literals from django.conf import settings from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) class StaticgenCMSView(StaticgenView): def items(self): try: from cms.models import Title except ImportError: # pragma: no cover # django-cms is not installed. return super(StaticgenCMSView, self).items() items = Title.objects.public().filter( page__login_required=False, page__site_id=settings.SITE_ID, ).order_by('page__path') return items def url(self, obj): translation.activate(obj.language) url = obj.page.get_absolute_url(obj.language) translation.deactivate() return url staticgen_pool.register(StaticgenCMSView)
4d73eb2a7e06e1e2607a2abfae1063b9969e70a0
strichliste/strichliste/models.py
strichliste/strichliste/models.py
from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value} class Meta: ordering = ('create_date',)
from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value, 'user': self.user_id} class Meta: ordering = ('create_date',)
Add user_id to returned transactions
Add user_id to returned transactions
Python
mit
Don42/strichliste-django,hackerspace-bootstrap/strichliste-django
from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, - 'value': self.value} + 'value': self.value, + 'user': self.user_id} class Meta: ordering = ('create_date',)
Add user_id to returned transactions
## Code Before: from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value} class Meta: ordering = ('create_date',) ## Instruction: Add user_id to returned transactions ## Code After: from django.db import models from django.db.models import Sum class User(models.Model): name = models.CharField(max_length=254, unique=True) create_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) mail_address = models.EmailField(null=True) @property def last_transaction(self): try: return self.transactions.last().create_date except AttributeError: return None @property def balance(self): return self.transactions.aggregate(sum=Sum('value'))['sum'] or 0 def to_full_dict(self): return {'id': self.id, 'name': self.name, 'mail_address': self.mail_address, 'balance': self.balance, 'last_transaction': self.last_transaction} def to_dict(self): return {'id': self.id, 'name': self.name, 'balance': self.balance, 'last_transaction': self.last_transaction} def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey('User', related_name='transactions', on_delete=models.PROTECT, db_index=True) create_date = models.DateTimeField(auto_now_add=True) value = models.IntegerField() def to_dict(self): return {'id': self.id, 'create_date': self.create_date, 'value': self.value, 'user': self.user_id} class Meta: ordering = ('create_date',)
0f1cb413503034cbc1e2deddd8327ad1946201fe
numba2/compiler/optimizations/throwing.py
numba2/compiler/optimizations/throwing.py
from numba2.compiler import excmodel from pykit.optimizations import local_exceptions def rewrite_local_exceptions(func, env): local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env)) def rewrite_exceptions(func, env): for op in func.ops: if op.opcode == 'exc_throw': raise NotImplementedError("Exception throwing", op, func) if op.opcode in ('exc_catch', 'exc_setup'): op.delete()
from numba2.compiler import excmodel from pykit.analysis import cfa from pykit.optimizations import local_exceptions def rewrite_local_exceptions(func, env): local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env)) def rewrite_exceptions(func, env): blocks = set() for op in func.ops: if op.opcode == 'exc_throw': raise NotImplementedError("Exception throwing", op, func) if op.opcode in ('exc_catch', 'exc_setup'): blocks.add(op.block) op.delete() update_outdated_incoming_blocks(func, blocks) def update_outdated_incoming_blocks(func, candidates): """ Update phi nodes in blocks previously containing 'exc_catch'. 'exc_setup' may span many blocks, and none, or only a subset of those blocks may be actual predecessors. """ cfg = cfa.cfg(func) for block in candidates: preds = cfg.predecessors(block) for op in block.leaders: if op.opcode == 'phi': blocks, values = op.args newblocks = [block for block in blocks if block in preds] newvalues = [val for block, val in zip(blocks, values) if block in preds] op.set_args([newblocks, newvalues])
Rewrite phis from outdated incoming exception blocks
Rewrite phis from outdated incoming exception blocks
Python
bsd-2-clause
flypy/flypy,flypy/flypy
from numba2.compiler import excmodel + + from pykit.analysis import cfa from pykit.optimizations import local_exceptions def rewrite_local_exceptions(func, env): local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env)) def rewrite_exceptions(func, env): + blocks = set() for op in func.ops: if op.opcode == 'exc_throw': raise NotImplementedError("Exception throwing", op, func) if op.opcode in ('exc_catch', 'exc_setup'): + blocks.add(op.block) op.delete() + update_outdated_incoming_blocks(func, blocks) + + def update_outdated_incoming_blocks(func, candidates): + """ + Update phi nodes in blocks previously containing 'exc_catch'. 'exc_setup' + may span many blocks, and none, or only a subset of those blocks may be + actual predecessors. + """ + cfg = cfa.cfg(func) + for block in candidates: + preds = cfg.predecessors(block) + for op in block.leaders: + if op.opcode == 'phi': + blocks, values = op.args + newblocks = [block for block in blocks if block in preds] + newvalues = [val for block, val in zip(blocks, values) + if block in preds] + op.set_args([newblocks, newvalues])
Rewrite phis from outdated incoming exception blocks
## Code Before: from numba2.compiler import excmodel from pykit.optimizations import local_exceptions def rewrite_local_exceptions(func, env): local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env)) def rewrite_exceptions(func, env): for op in func.ops: if op.opcode == 'exc_throw': raise NotImplementedError("Exception throwing", op, func) if op.opcode in ('exc_catch', 'exc_setup'): op.delete() ## Instruction: Rewrite phis from outdated incoming exception blocks ## Code After: from numba2.compiler import excmodel from pykit.analysis import cfa from pykit.optimizations import local_exceptions def rewrite_local_exceptions(func, env): local_exceptions.run(func, env, exc_model=excmodel.ExcModel(env)) def rewrite_exceptions(func, env): blocks = set() for op in func.ops: if op.opcode == 'exc_throw': raise NotImplementedError("Exception throwing", op, func) if op.opcode in ('exc_catch', 'exc_setup'): blocks.add(op.block) op.delete() update_outdated_incoming_blocks(func, blocks) def update_outdated_incoming_blocks(func, candidates): """ Update phi nodes in blocks previously containing 'exc_catch'. 'exc_setup' may span many blocks, and none, or only a subset of those blocks may be actual predecessors. """ cfg = cfa.cfg(func) for block in candidates: preds = cfg.predecessors(block) for op in block.leaders: if op.opcode == 'phi': blocks, values = op.args newblocks = [block for block in blocks if block in preds] newvalues = [val for block, val in zip(blocks, values) if block in preds] op.set_args([newblocks, newvalues])