commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
90c2141ccdcb566149a0f11e8cc1e3f67b2dc113
|
mnp/commands.py
|
mnp/commands.py
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
Change to use --extra-index-url instead
|
Change to use --extra-index-url instead
|
Python
|
mit
|
heryandi/mnp
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
Change to use --extra-index-url instead
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
<commit_before>import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
<commit_msg>Change to use --extra-index-url instead<commit_after>
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
Change to use --extra-index-url insteadimport subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
<commit_before>import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
<commit_msg>Change to use --extra-index-url instead<commit_after>import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["python", "setup.py", "register", "-r", repository, "sdist", "upload", "-r", repository] + additional_args)
|
446d36cbbf79083b9d41ea5b152c5a845560eb4b
|
whats_fresh/whats_fresh_api/tests/views/test_stories.py
|
whats_fresh/whats_fresh_api/tests/views/test_stories.py
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
Add error field to expected JSON
|
Add error field to expected JSON
|
Python
|
apache-2.0
|
iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
Add error field to expected JSON
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
<commit_before>from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
<commit_msg>Add error field to expected JSON<commit_after>
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
Add error field to expected JSONfrom django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
<commit_before>from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
<commit_msg>Add error field to expected JSON<commit_after>from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
ab57bcc9f4219af63e99d82a844986213ade4c01
|
script/commit_message.py
|
script/commit_message.py
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
Fix script up to search branches
|
Fix script up to search branches
|
Python
|
mit
|
pact-foundation/pact-python,pact-foundation/pact-python
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
Fix script up to search branches
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
<commit_msg>Fix script up to search branches<commit_after>
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
Fix script up to search branches#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd = "git log --pretty=format:'%s' master..HEAD"
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
<commit_msg>Fix script up to search branches<commit_after>#!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
"""
def main():
cmd_tag = "git describe --abbrev=0"
tag = subprocess.check_output(cmd_tag,
shell=True).decode("utf-8").split('\n')[0]
cmd = "git log --pretty=format:'%s' {}..master".format(tag)
commits = subprocess.check_output(cmd, shell=True)
commits = commits.decode("utf-8").split('\n')
for commit in commits:
pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa
m = re.match(pattern, commit)
if m is None:
print("\nError with git message '{}' style".format(commit))
print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa
print("\n" + examples)
sys.exit(1)
print("Commit messages valid")
if __name__ == "__main__":
main()
|
03aae3ef6488168730d35e36f416e1b8eb058431
|
script/daytime_client.py
|
script/daytime_client.py
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
Use python script to send json
|
Use python script to send json
|
Python
|
bsd-3-clause
|
crapp/netfortune,crapp/netfortune
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
Use python script to send json
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
<commit_before># A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
<commit_msg>Use python script to send json<commit_after>
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
Use python script to send json# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
<commit_before># A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
<commit_msg>Use python script to send json<commit_after># A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
a63481c0198791b41cf377e4bc8247afaed90364
|
email_extras/__init__.py
|
email_extras/__init__.py
|
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
|
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
|
Fix to allow version number to be imported without dependencies being installed.
|
Fix to allow version number to be imported without dependencies being installed.
|
Python
|
bsd-2-clause
|
blag/django-email-extras,stephenmcd/django-email-extras,blag/django-email-extras,dreipol/django-email-extras,dreipol/django-email-extras,stephenmcd/django-email-extras
|
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
Fix to allow version number to be imported without dependencies being installed.
|
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
|
<commit_before>
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
<commit_msg>Fix to allow version number to be imported without dependencies being installed.<commit_after>
|
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
|
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
Fix to allow version number to be imported without dependencies being installed.
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
|
<commit_before>
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
<commit_msg>Fix to allow version number to be imported without dependencies being installed.<commit_after>
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
|
ca9f3c005b2412c1b9ff0247afc6708b0172d183
|
web/impact/impact/v1/views/base_history_view.py
|
web/impact/impact/v1/views/base_history_view.py
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
Improve history sorting and remove dead comments
|
[AC-4875] Improve history sorting and remove dead comments
|
Python
|
mit
|
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
[AC-4875] Improve history sorting and remove dead comments
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
<commit_before># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
<commit_msg>[AC-4875] Improve history sorting and remove dead comments<commit_after>
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
[AC-4875] Improve history sorting and remove dead comments# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
<commit_before># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
<commit_msg>[AC-4875] Improve history sorting and remove dead comments<commit_after># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
479e532769b201ee0213812b3071100eaf4dfef4
|
skele/cli.py
|
skele/cli.py
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k):
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k) and v:
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
Validate command not only exists but was used
|
Validate command not only exists but was used
Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)
|
Python
|
mit
|
snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k):
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
Validate command not only exists but was used
Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k) and v:
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
<commit_before>"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k):
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
<commit_msg>Validate command not only exists but was used
Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)<commit_after>
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k) and v:
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k):
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
Validate command not only exists but was used
Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k) and v:
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
<commit_before>"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k):
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
<commit_msg>Validate command not only exists but was used
Without this, it just uses the first command module that exists, even if that option is `False` (it wasn't passed by the user)<commit_after>"""
skele
Usage:
skele hello
skele -h | --help
skele --version
Options:
-h --help Show this screen.
--version Show version.
Examples:
skele hello
Help:
For help using this tool, please open an issue on the Github repository:
https://github.com/rdegges/skele-cli
"""
from inspect import getmembers, isclass
from docopt import docopt
from . import __version__ as VERSION
def main():
"""Main CLI entrypoint."""
import commands
options = docopt(__doc__, version=VERSION)
# Here we'll try to dynamically match the command the user is trying to run
# with a pre-defined command class we've already created.
for k, v in options.iteritems():
if hasattr(commands, k) and v:
module = getattr(commands, k)
commands = getmembers(module, isclass)
command = [command[1] for command in commands if command[0] != 'Base'][0]
command = command(options)
command.run()
|
112ce320f351399a28e4d85ed88e1b71df4e7aef
|
magpie/config/__init__.py
|
magpie/config/__init__.py
|
from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
|
from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exists(return_path): return return_path
return None
config_path = ConfigPath()
|
Enable configuration from home directory
|
Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem that magpie must be run as root if it was installed as root.
|
Python
|
mit
|
damoeb/magpie,akarca/magpie,charlesthomas/magpie,jcda/magpie,akarca/magpie,damoeb/magpie,damoeb/magpie,beni55/magpie,jcda/magpie,beni55/magpie,jcda/magpie,beni55/magpie,charlesthomas/magpie,akarca/magpie,charlesthomas/magpie
|
from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem that magpie must be run as root if it was installed as root.
|
from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exists(return_path): return return_path
return None
config_path = ConfigPath()
|
<commit_before>from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
<commit_msg>Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem that magpie must be run as root if it was installed as root.<commit_after>
|
from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exists(return_path): return return_path
return None
config_path = ConfigPath()
|
from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem that magpie must be run as root if it was installed as root.from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exists(return_path): return return_path
return None
config_path = ConfigPath()
|
<commit_before>from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
<commit_msg>Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem that magpie must be run as root if it was installed as root.<commit_after>from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exists(return_path): return return_path
return None
config_path = ConfigPath()
|
6f992bda1747d8dd23dd03f1ae3679c00f2fc977
|
marketpulse/geo/lookup.py
|
marketpulse/geo/lookup.py
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
Handle errors in case of a country mismatch.
|
Handle errors in case of a country mismatch.
|
Python
|
mpl-2.0
|
mozilla/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,mozilla/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
Handle errors in case of a country mismatch.
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
<commit_before>from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
<commit_msg>Handle errors in case of a country mismatch.<commit_after>
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
Handle errors in case of a country mismatch.from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
<commit_before>from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
results['country'] = COUNTRY_CODES[text]
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
<commit_msg>Handle errors in case of a country mismatch.<commit_after>from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
url = urljoin(settings.MAPBOX_GEOCODE_URL, query)
params = {'access_token': settings.MAPBOX_TOKEN}
response = requests.get(url, params=params)
results = {}
if response.status_code != 200:
return results
data = response.json()
for feature in data['features']:
text = feature['text']
if feature['id'].startswith('country.'):
try:
results['country'] = COUNTRY_CODES[text]
except KeyError:
results['country'] = text
if feature['id'].startswith('region.'):
results['region'] = text
if feature['id'].startswith('place.'):
results['city'] = text
if feature['id'].startswith('address.'):
results['address'] = text
return results
|
ef7910d259f3a7d025e95ad69345da457a777b90
|
myvoice/urls.py
|
myvoice/urls.py
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Use Django 1.7 syntax for URLs
|
Use Django 1.7 syntax for URLs
|
Python
|
bsd-2-clause
|
myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use Django 1.7 syntax for URLs
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
<commit_before>from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_msg>Use Django 1.7 syntax for URLs<commit_after>
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use Django 1.7 syntax for URLsfrom django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
<commit_before>from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_msg>Use Django 1.7 syntax for URLs<commit_after>from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
e252962f9a6cc1ed6cd2ccdd72c4151708be7233
|
tests/cases/resources/tests/preview.py
|
tests/cases/resources/tests/preview.py
|
import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
import json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
def test_get_with_user(self):
self.user = User.objects.create_user(username='test', password='test')
self.client.login(username='test', password='test')
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
Add test to recreate error in this bug
|
Add test to recreate error in this bug
|
Python
|
bsd-2-clause
|
rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano,chop-dbhi/serrano
|
import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
Add test to recreate error in this bug
|
import json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
def test_get_with_user(self):
self.user = User.objects.create_user(username='test', password='test')
self.client.login(username='test', password='test')
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
<commit_before>import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
<commit_msg>Add test to recreate error in this bug<commit_after>
|
import json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
def test_get_with_user(self):
self.user = User.objects.create_user(username='test', password='test')
self.client.login(username='test', password='test')
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
Add test to recreate error in this bugimport json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
def test_get_with_user(self):
self.user = User.objects.create_user(username='test', password='test')
self.client.login(username='test', password='test')
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
<commit_before>import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
<commit_msg>Add test to recreate error in this bug<commit_after>import json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
def test_get_with_user(self):
self.user = User.objects.create_user(username='test', password='test')
self.client.login(username='test', password='test')
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), {
'_links': {
'self': {
'href': 'http://testserver/api/data/preview/?limit=20&page=1',
},
'base': {
'href': 'http://testserver/api/data/preview/',
}
},
'keys': [],
'object_count': 0,
'object_name': 'employee',
'object_name_plural': 'employees',
'objects': [],
'page_num': 1,
'num_pages': 1,
'limit': 20,
})
|
64732e7dd32f23b9431bd69fecd757af1772053e
|
local_test_settings.py
|
local_test_settings.py
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
Remove UNICORE_DISTRIBUTE_API from test settings
|
Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c
|
Python
|
bsd-2-clause
|
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
<commit_before>from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
<commit_msg>Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c<commit_after>
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109cfrom testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
<commit_before>from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
<commit_msg>Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c<commit_after>from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
|
c460fd7d257b25723fc19557ad4404519904e0a9
|
simplecoin/tests/__init__.py
|
simplecoin/tests/__init__.py
|
import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
Fix tests to allow use of random, but not change each time
|
Fix tests to allow use of random, but not change each time
|
Python
|
mit
|
nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi
|
import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
Fix tests to allow use of random, but not change each time
|
import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
<commit_before>import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
<commit_msg>Fix tests to allow use of random, but not change each time<commit_after>
|
import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
Fix tests to allow use of random, but not change each timeimport simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
<commit_before>import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
<commit_msg>Fix tests to allow use of random, but not change each time<commit_after>import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
66eadda6a2a26cfef2f38449736183b8b5175022
|
pytest_django/__init__.py
|
pytest_django/__init__.py
|
from .plugin import *
from .funcargs import *
from .marks import *
|
from pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
|
Make module imports 2.5 compatible
|
Make module imports 2.5 compatible
|
Python
|
bsd-3-clause
|
bforchhammer/pytest-django,thedrow/pytest-django,reincubate/pytest-django,aptivate/pytest-django,felixonmars/pytest-django,pelme/pytest-django,ojake/pytest-django,hoh/pytest-django,RonnyPfannschmidt/pytest_django,ktosiek/pytest-django,davidszotten/pytest-django,pombredanne/pytest_django,tomviner/pytest-django
|
from .plugin import *
from .funcargs import *
from .marks import *
Make module imports 2.5 compatible
|
from pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
|
<commit_before>from .plugin import *
from .funcargs import *
from .marks import *
<commit_msg>Make module imports 2.5 compatible<commit_after>
|
from pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
|
from .plugin import *
from .funcargs import *
from .marks import *
Make module imports 2.5 compatiblefrom pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
|
<commit_before>from .plugin import *
from .funcargs import *
from .marks import *
<commit_msg>Make module imports 2.5 compatible<commit_after>from pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
|
d4f63bb099db886f50b6e54838ec9200dbc3ca1f
|
echo_client.py
|
echo_client.py
|
#!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
print main()
|
#!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
t = Thread(target=echo_server.main)
t.start()
print main()
|
Add threading to allow for client and server to be run from a single script
|
Add threading to allow for client and server to be run from a single script
|
Python
|
mit
|
charlieRode/network_tools
|
#!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
print main()
Add threading to allow for client and server to be run from a single script
|
#!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
t = Thread(target=echo_server.main)
t.start()
print main()
|
<commit_before>#!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
print main()
<commit_msg>Add threading to allow for client and server to be run from a single script<commit_after>
|
#!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
t = Thread(target=echo_server.main)
t.start()
print main()
|
#!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
print main()
Add threading to allow for client and server to be run from a single script#!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
t = Thread(target=echo_server.main)
t.start()
print main()
|
<commit_before>#!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
print main()
<commit_msg>Add threading to allow for client and server to be run from a single script<commit_after>#!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
if __name__ == '__main__':
t = Thread(target=echo_server.main)
t.start()
print main()
|
fddd632e73a7540bc6be4f02022dcc663b35b3d4
|
echo_server.py
|
echo_server.py
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server_socket.accept()
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
connection.shutdown(socket.SHUT_WR)
except KeyboardInterrupt:
return "Connection closing..."
connection.close()
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# receive message from client, and immediately return
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
# shutdown socket to writing after sending echo message
connection.shutdown(socket.SHUT_WR)
connection.close()
except KeyboardInterrupt:
server_socket.close()
|
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
|
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
|
Python
|
mit
|
jwarren116/network-tools,jwarren116/network-tools
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server_socket.accept()
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
connection.shutdown(socket.SHUT_WR)
except KeyboardInterrupt:
return "Connection closing..."
connection.close()
Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# receive message from client, and immediately return
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
# shutdown socket to writing after sending echo message
connection.shutdown(socket.SHUT_WR)
connection.close()
except KeyboardInterrupt:
server_socket.close()
|
<commit_before>import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server_socket.accept()
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
connection.shutdown(socket.SHUT_WR)
except KeyboardInterrupt:
return "Connection closing..."
connection.close()
<commit_msg>Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt<commit_after>
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# receive message from client, and immediately return
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
# shutdown socket to writing after sending echo message
connection.shutdown(socket.SHUT_WR)
connection.close()
except KeyboardInterrupt:
server_socket.close()
|
import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server_socket.accept()
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
connection.shutdown(socket.SHUT_WR)
except KeyboardInterrupt:
return "Connection closing..."
connection.close()
Fix bug in server, connection closes after returning message, socket closes on KeyboardInteruptimport socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# receive message from client, and immediately return
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
# shutdown socket to writing after sending echo message
connection.shutdown(socket.SHUT_WR)
connection.close()
except KeyboardInterrupt:
server_socket.close()
|
<commit_before>import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server_socket.accept()
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
connection.shutdown(socket.SHUT_WR)
except KeyboardInterrupt:
return "Connection closing..."
connection.close()
<commit_msg>Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt<commit_after>import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# receive message from client, and immediately return
echo_msg = connection.recv(16)
connection.sendall(echo_msg)
# shutdown socket to writing after sending echo message
connection.shutdown(socket.SHUT_WR)
connection.close()
except KeyboardInterrupt:
server_socket.close()
|
0611f0ca617c3463a69e5bd627e821ae55c822ec
|
logintokens/tests/util.py
|
logintokens/tests/util.py
|
from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
|
"""utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + self.time_passed
def sleep(self, seconds):
"""Increase the offset to make it seem as though time has passed.
"""
self.time_passed += seconds
mock_time = MockTime()
|
Add docstrings to mocked time methods
|
Add docstrings to mocked time methods
|
Python
|
mit
|
randomic/aniauth-tdd,randomic/aniauth-tdd
|
from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
Add docstrings to mocked time methods
|
"""utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + self.time_passed
def sleep(self, seconds):
"""Increase the offset to make it seem as though time has passed.
"""
self.time_passed += seconds
mock_time = MockTime()
|
<commit_before>from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
<commit_msg>Add docstrings to mocked time methods<commit_after>
|
"""utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + self.time_passed
def sleep(self, seconds):
"""Increase the offset to make it seem as though time has passed.
"""
self.time_passed += seconds
mock_time = MockTime()
|
from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
Add docstrings to mocked time methods"""utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + self.time_passed
def sleep(self, seconds):
"""Increase the offset to make it seem as though time has passed.
"""
self.time_passed += seconds
mock_time = MockTime()
|
<commit_before>from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
<commit_msg>Add docstrings to mocked time methods<commit_after>"""utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + self.time_passed
def sleep(self, seconds):
"""Increase the offset to make it seem as though time has passed.
"""
self.time_passed += seconds
mock_time = MockTime()
|
07617ec8b1cb57c795d9875691d7f3c67e633b6a
|
repour/auth/oauth2_jwt.py
|
repour/auth/oauth2_jwt.py
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token: ' + str(token))
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token!')
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
Remove user token from logs
|
[NCL-3741] Remove user token from logs
|
Python
|
apache-2.0
|
project-ncl/repour,project-ncl/repour
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token: ' + str(token))
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
[NCL-3741] Remove user token from logs
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token!')
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
<commit_before>import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token: ' + str(token))
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
<commit_msg>[NCL-3741] Remove user token from logs<commit_after>
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token!')
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token: ' + str(token))
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
[NCL-3741] Remove user token from logsimport asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token!')
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
<commit_before>import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token: ' + str(token))
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
<commit_msg>[NCL-3741] Remove user token from logs<commit_after>import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'verify_aud': False,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': False,
'verify_jti': True,
'verify_at_hash': True,
'leeway': 0,
}
try:
token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS,
issuer=c['auth']['oauth2_jwt']['token_issuer'])
logger.info('Got valid token!')
return True
except JWTError as e:
logger.info('Got invalid token: ' + str(e))
return False
|
9f557a7632a1cd3b16dd6db79c7bb6a61ff79791
|
v0/tig.py
|
v0/tig.py
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
print args
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
Print parsed args, useful for demo.
|
Print parsed args, useful for demo.
|
Python
|
mit
|
bravegnu/tiny-git,jamesmortensen/tiny-git,jamesmortensen/tiny-git,bravegnu/tiny-git
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
Print parsed args, useful for demo.
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
print args
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
<commit_msg>Print parsed args, useful for demo.<commit_after>
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
print args
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
Print parsed args, useful for demo.#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
print args
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
<commit_msg>Print parsed args, useful for demo.<commit_after>#!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
def checkout(start_point, new_branch):
pass
def diff():
pass
def log():
pass
def merge(branch):
pass
def main():
args = docopt.docopt(__doc__)
print args
if args["commit"]:
commit(args["<msg>"])
elif args["checkout"]:
checkout(args["<start-point>"], args["-b"])
elif args["init"]:
init()
elif args["diff"]:
diff()
elif args["log"]:
log()
elif args["branch"]:
branch()
elif args["merge"]:
merge(args["<branch>"])
else:
# Not reached
pass
if __name__ == "__main__":
main()
|
fd09e0ef4ea9a0dede74e5a87ad108a75d5e5ce7
|
comrade/core/decorators.py
|
comrade/core/decorators.py
|
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
Add decorator for loading instance of a model in a view.
|
Add decorator for loading instance of a model in a view.
|
Python
|
mit
|
bueda/django-comrade
|
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
Add decorator for loading instance of a model in a view.
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
<commit_before>from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
<commit_msg>Add decorator for loading instance of a model in a view.<commit_after>
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
Add decorator for loading instance of a model in a view.from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
<commit_before>from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
<commit_msg>Add decorator for loading instance of a model in a view.<commit_after>from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
5a2c794bebc4b6594eacdaef4409825c135b62d7
|
test/test_integ_rules.py
|
test/test_integ_rules.py
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_4(self):
""" IsACaptureP calls direction with a move that doesn't exist """
direction = 4
rules_obj = rules.Rules()
board = gamenode.GameNode()
foxCoordinate = coordinate.Coordinate(3, 4)
goose_location = coordinate.Coordinate(4, 3)
board.setState(foxCoordinate, types.FOX)
board.setState(goose_location, types.GOOSE)
actual_result = rules_obj.isACaptureP(board, foxCoordinate, direction)
expected_result = False
self.assertEqual(actual_result, expected_result)
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
Add integration test for isACaptureP()
|
Add integration test for isACaptureP()
|
Python
|
mit
|
blairck/jaeger
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
Add integration test for isACaptureP()
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_4(self):
""" IsACaptureP calls direction with a move that doesn't exist """
direction = 4
rules_obj = rules.Rules()
board = gamenode.GameNode()
foxCoordinate = coordinate.Coordinate(3, 4)
goose_location = coordinate.Coordinate(4, 3)
board.setState(foxCoordinate, types.FOX)
board.setState(goose_location, types.GOOSE)
actual_result = rules_obj.isACaptureP(board, foxCoordinate, direction)
expected_result = False
self.assertEqual(actual_result, expected_result)
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
<commit_before>""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
<commit_msg>Add integration test for isACaptureP()<commit_after>
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_4(self):
""" IsACaptureP calls direction with a move that doesn't exist """
direction = 4
rules_obj = rules.Rules()
board = gamenode.GameNode()
foxCoordinate = coordinate.Coordinate(3, 4)
goose_location = coordinate.Coordinate(4, 3)
board.setState(foxCoordinate, types.FOX)
board.setState(goose_location, types.GOOSE)
actual_result = rules_obj.isACaptureP(board, foxCoordinate, direction)
expected_result = False
self.assertEqual(actual_result, expected_result)
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
Add integration test for isACaptureP()""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_4(self):
""" IsACaptureP calls direction with a move that doesn't exist """
direction = 4
rules_obj = rules.Rules()
board = gamenode.GameNode()
foxCoordinate = coordinate.Coordinate(3, 4)
goose_location = coordinate.Coordinate(4, 3)
board.setState(foxCoordinate, types.FOX)
board.setState(goose_location, types.GOOSE)
actual_result = rules_obj.isACaptureP(board, foxCoordinate, direction)
expected_result = False
self.assertEqual(actual_result, expected_result)
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
<commit_before>""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
<commit_msg>Add integration test for isACaptureP()<commit_after>""" Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_4(self):
""" IsACaptureP calls direction with a move that doesn't exist """
direction = 4
rules_obj = rules.Rules()
board = gamenode.GameNode()
foxCoordinate = coordinate.Coordinate(3, 4)
goose_location = coordinate.Coordinate(4, 3)
board.setState(foxCoordinate, types.FOX)
board.setState(goose_location, types.GOOSE)
actual_result = rules_obj.isACaptureP(board, foxCoordinate, direction)
expected_result = False
self.assertEqual(actual_result, expected_result)
def test_existsCaptureP_capture(self):
""" End to end test for finding a real goose capture """
rules_obj = rules.Rules()
foxOne = coordinate.Coordinate(5, 5)
foxTwo = coordinate.Coordinate(3, 7)
goose = coordinate.Coordinate(4, 5)
board = gamenode.GameNode()
board.setState(foxOne, types.FOX)
board.setState(foxTwo, types.FOX)
board.setState(goose, types.GOOSE)
actual_result = rules_obj.existsCaptureP(board)
expected_result = True
self.assertEqual(actual_result, expected_result)
def test_readSavedFile_real(self):
""" Read in a real saved game file and verify result """
rules_obj = rules.Rules()
expected_result = 6
actual_result = len(rules_obj.readSavedFile("test/savedGame.txt"))
self.assertEqual(actual_result, expected_result)
|
cc0a971bad5f4b2eb81881b8c570eddb2bd144f3
|
django_vend/stores/forms.py
|
django_vend/stores/forms.py
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
Make form update existing instance if uid matches
|
Make form update existing instance if uid matches
|
Python
|
bsd-3-clause
|
remarkablerocket/django-vend,remarkablerocket/django-vend
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
Make form update existing instance if uid matches
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
<commit_before>from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
<commit_msg>Make form update existing instance if uid matches<commit_after>
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
Make form update existing instance if uid matchesfrom django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
<commit_before>from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
<commit_msg>Make form update existing instance if uid matches<commit_after>from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
5d5a4e6fb6a646ddf189100d87160d36f09862bf
|
games/admin.py
|
games/admin.py
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'game', 'version']
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
Add more fields to the release display
|
Add more fields to the release display
|
Python
|
mit
|
stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
Add more fields to the release display
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'game', 'version']
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
<commit_before>from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
<commit_msg>Add more fields to the release display<commit_after>
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'game', 'version']
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
Add more fields to the release displayfrom django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'game', 'version']
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
<commit_before>from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
<commit_msg>Add more fields to the release display<commit_after>from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'game', 'version']
class AssetAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'release']
admin.site.register(Game, GameAdmin)
admin.site.register(Release, ReleaseAdmin)
admin.site.register(Framework, FrameworkAdmin)
admin.site.register(Asset, AssetAdmin)
|
fde47133da8c5157f2cae04abb77eccbace6c831
|
netbox/netbox/forms.py
|
netbox/netbox/forms.py
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
Fix global search placeholder text
|
Fix global search placeholder text
|
Python
|
apache-2.0
|
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,lampwins/netbox,lampwins/netbox,lampwins/netbox,digitalocean/netbox,lampwins/netbox
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
Fix global search placeholder text
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
<commit_before>from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
<commit_msg>Fix global search placeholder text<commit_after>
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
Fix global search placeholder textfrom __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
<commit_before>from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
<commit_msg>Fix global search placeholder text<commit_after>from __future__ import unicode_literals
from django import forms
from utilities.forms import BootstrapMixin
OBJ_TYPE_CHOICES = (
('', 'All Objects'),
('Circuits', (
('provider', 'Providers'),
('circuit', 'Circuits'),
)),
('DCIM', (
('site', 'Sites'),
('rack', 'Racks'),
('devicetype', 'Device types'),
('device', 'Devices'),
)),
('IPAM', (
('vrf', 'VRFs'),
('aggregate', 'Aggregates'),
('prefix', 'Prefixes'),
('ipaddress', 'IP addresses'),
('vlan', 'VLANs'),
)),
('Secrets', (
('secret', 'Secrets'),
)),
('Tenancy', (
('tenant', 'Tenants'),
)),
)
class SearchForm(BootstrapMixin, forms.Form):
q = forms.CharField(
label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'})
)
obj_type = forms.ChoiceField(
choices=OBJ_TYPE_CHOICES, required=False, label='Type'
)
|
89ae5637fe57afbd777f0a491a6ab0d674a5e351
|
agsadmin/sharing_admin/content/users/UserItem.py
|
agsadmin/sharing_admin/content/users/UserItem.py
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json()
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json()
|
Add move operation to user item
|
Add move operation to user item
|
Python
|
bsd-3-clause
|
DavidWhittingham/agsadmin
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json()Add move operation to user item
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json()
|
<commit_before>from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json()<commit_msg>Add move operation to user item<commit_after>
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json()
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json()Add move operation to user itemfrom __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json()
|
<commit_before>from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def delete(self):
r = self._create_operation_request(self, "delete", method = "POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method = "POST", data = updated_item_info)
return send_session_request(self._session, r).json()<commit_msg>Add move operation to user item<commit_after>from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_request
from ..Item import Item
class UserItem(Item):
@property
def username(self):
return self._pdata["username"]
@property
def _url_full(self):
return "{0}/items/{1}".format(self._url_base, self.id)
def __init__(self, requests_session, content_url, username, item_id):
super().__init__(requests_session, content_url, item_id)
self._pdata["username"] = username
def move(self, folder_id):
r = self._create_operation_request(self, "move", method="POST", data={"folder": folder_id})
return send_session_request(self._session, r).json()
def delete(self):
r = self._create_operation_request(self, "delete", method="POST")
return send_session_request(self._session, r).json()
def get_properties(self):
"""
Gets the properties of the item.
"""
return self._get()["item"]
def get_sharing(self):
"""
Gets the sharing details of the item.
"""
return self._get()["sharing"]
def update(self, updated_item_info):
r = self._create_operation_request(self, "update", method="POST", data=updated_item_info)
return send_session_request(self._session, r).json()
|
afbe8ddff1791084aa1bcad775f1b01481b72c2b
|
larvae/person.py
|
larvae/person.py
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
for k, v in kwargs.items():
setattr(self, k, v)
self.links = []
self.other_names = []
self.extras = {}
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
self.links = []
self.other_names = []
self.extras = {}
for k, v in kwargs.items():
setattr(self, k, v)
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
Move default value assignments before kwargs
|
Move default value assignments before kwargs
|
Python
|
bsd-3-clause
|
AGarrow/larvae
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
for k, v in kwargs.items():
setattr(self, k, v)
self.links = []
self.other_names = []
self.extras = {}
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
Move default value assignments before kwargs
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
self.links = []
self.other_names = []
self.extras = {}
for k, v in kwargs.items():
setattr(self, k, v)
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
<commit_before>from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
for k, v in kwargs.items():
setattr(self, k, v)
self.links = []
self.other_names = []
self.extras = {}
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
<commit_msg>Move default value assignments before kwargs<commit_after>
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
self.links = []
self.other_names = []
self.extras = {}
for k, v in kwargs.items():
setattr(self, k, v)
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
for k, v in kwargs.items():
setattr(self, k, v)
self.links = []
self.other_names = []
self.extras = {}
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
Move default value assignments before kwargsfrom larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
self.links = []
self.other_names = []
self.extras = {}
for k, v in kwargs.items():
setattr(self, k, v)
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
<commit_before>from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
for k, v in kwargs.items():
setattr(self, k, v)
self.links = []
self.other_names = []
self.extras = {}
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
<commit_msg>Move default value assignments before kwargs<commit_after>from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras', 'contact_details', 'openstates_id',
'chamber', 'district')
_other_name_slots = ('name', 'start_date', 'end_date', 'note')
def __init__(self, name, **kwargs):
super(Person, self).__init__()
self.name = name
self.links = []
self.other_names = []
self.extras = {}
for k, v in kwargs.items():
setattr(self, k, v)
def add_name(self, name, **kwargs):
other_name = {'name': name}
for k, v in kwargs.items():
if k not in self._other_name_slots:
raise AttributeError('{0} not a valid kwarg for add_name'
.format(k))
other_name[k] = v
self.other_names.append(other_name)
def add_link(self, url, note):
self.links.append({"note": note, "url": url})
def __unicode__(self):
return self.name
__str__ = __unicode__
|
2d4382ae1cec44875e7bec2f16b8406879a0bac9
|
opentreemap/api/models.py
|
opentreemap/api/models.py
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.access_key
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
Print debug-friendly repr of APIAccessCredential
|
Print debug-friendly repr of APIAccessCredential
|
Python
|
agpl-3.0
|
maurizi/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
Print debug-friendly repr of APIAccessCredential
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.access_key
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
<commit_msg>Print debug-friendly repr of APIAccessCredential<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.access_key
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
Print debug-friendly repr of APIAccessCredential# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.access_key
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
<commit_msg>Print debug-friendly repr of APIAccessCredential<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharField(max_length=100, null=False, blank=False)
secret_key = models.CharField(max_length=256, null=False, blank=False)
# If a user is specified then this credential
# is always authorized as the given user
#
# If user is None this credential can access
# any user's data if that user's username
# and password are also provided
user = models.ForeignKey(User, null=True)
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.access_key
@classmethod
def create(clz, user=None):
secret_key = base64.urlsafe_b64encode(os.urandom(64))
access_key = base64.urlsafe_b64encode(uuid.uuid4().bytes)\
.replace('=', '')
return APIAccessCredential.objects.create(
user=user, access_key=access_key, secret_key=secret_key)
|
25a37ea86e26a731608e4c2a810610c842d37d19
|
grano/service/indexer.py
|
grano/service/indexer.py
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None).yield_per(1000)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
#log.info('Indexing: %s', body.get('name'))
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
Remove use of yield_per which clashes with 'joined' load.
|
Remove use of yield_per which clashes with 'joined' load.
|
Python
|
mit
|
4bic/grano,granoproject/grano,4bic-attic/grano,CodeForAfrica/grano
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None).yield_per(1000)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
#log.info('Indexing: %s', body.get('name'))
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
Remove use of yield_per which clashes with 'joined' load.
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
<commit_before>import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None).yield_per(1000)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
#log.info('Indexing: %s', body.get('name'))
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
<commit_msg>Remove use of yield_per which clashes with 'joined' load. <commit_after>
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None).yield_per(1000)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
#log.info('Indexing: %s', body.get('name'))
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
Remove use of yield_per which clashes with 'joined' load. import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
<commit_before>import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None).yield_per(1000)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
#log.info('Indexing: %s', body.get('name'))
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
<commit_msg>Remove use of yield_per which clashes with 'joined' load. <commit_after>import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Entity.all().filter_by(same_as=None)):
body = entities.to_index(entity)
if not 'name' in body:
log.warn('No name: %s, skipping!', entity.id)
continue
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
if i > 0 and i % 1000 == 0:
log.info("Indexed: %s entities", i)
es.indices.refresh(index=es_index)
es.indices.refresh(index=es_index)
def index_single(entity_id):
""" Index a single entity. """
entity = Entity.by_id(entity_id)
body = entities.to_index(entity)
es.index(index=es_index, doc_type='entity', id=body.pop('id'), body=body)
es.indices.refresh(index=es_index)
def flush_entities():
""" Delete the entire index. """
query = {'query': {"match_all": {}}}
es.delete_by_query(index=es_index, doc_type='entity', q='*:*')
|
62d93afd3f59f4096ef22a056881faf725d09531
|
oweb/tests/__init__.py
|
oweb/tests/__init__.py
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# use a namespace, which is required by the app
self.urls = patterns('',
url(r'', include('oweb.urls', namespace='oweb')),
)
|
Add test specific url configuration
|
Add test specific url configuration
|
Python
|
mit
|
Mischback/django-oweb,Mischback/django-oweb
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
Add test specific url configuration
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# use a namespace, which is required by the app
self.urls = patterns('',
url(r'', include('oweb.urls', namespace='oweb')),
)
|
<commit_before># Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
<commit_msg>Add test specific url configuration<commit_after>
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# use a namespace, which is required by the app
self.urls = patterns('',
url(r'', include('oweb.urls', namespace='oweb')),
)
|
# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
Add test specific url configuration# Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# use a namespace, which is required by the app
self.urls = patterns('',
url(r'', include('oweb.urls', namespace='oweb')),
)
|
<commit_before># Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
<commit_msg>Add test specific url configuration<commit_after># Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# use a namespace, which is required by the app
self.urls = patterns('',
url(r'', include('oweb.urls', namespace='oweb')),
)
|
7f23dfe16904fdf73b353338a8881928c5211989
|
hoomd/filter/__init__.py
|
hoomd/filter/__init__.py
|
"""Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
"""Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a **group**,
an internally maintained list of the selected particles. Subsequent uses of the
same particle filter specification will resolve to the same group *and the
originally selected particles*, **even if the state of the system has changed.**
Groups are not completely static. HOOMD-blue re-evaluates the filter
specifications and updates the group membership whenever the number of particles
in the simulation changes. A future release will include an operation that you
can schedule to periodically update groups on demand.
For molecular dynamics simulations, each group maintains a count of the number
of degrees of freedom given to the group by integration methods. This count is
used by `hoomd.md.compute.ThermodynamicQuantities` and the integration methods
themselves to compute the kinetic temperature. See
`hoomd.State.update_group_dof` for details on when HOOMD-blue updates this
count.
"""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
Add particle filter overview information.
|
Add particle filter overview information.
|
Python
|
bsd-3-clause
|
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
|
"""Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
Add particle filter overview information.
|
"""Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a **group**,
an internally maintained list of the selected particles. Subsequent uses of the
same particle filter specification will resolve to the same group *and the
originally selected particles*, **even if the state of the system has changed.**
Groups are not completely static. HOOMD-blue re-evaluates the filter
specifications and updates the group membership whenever the number of particles
in the simulation changes. A future release will include an operation that you
can schedule to periodically update groups on demand.
For molecular dynamics simulations, each group maintains a count of the number
of degrees of freedom given to the group by integration methods. This count is
used by `hoomd.md.compute.ThermodynamicQuantities` and the integration methods
themselves to compute the kinetic temperature. See
`hoomd.State.update_group_dof` for details on when HOOMD-blue updates this
count.
"""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
<commit_before>"""Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
<commit_msg>Add particle filter overview information.<commit_after>
|
"""Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a **group**,
an internally maintained list of the selected particles. Subsequent uses of the
same particle filter specification will resolve to the same group *and the
originally selected particles*, **even if the state of the system has changed.**
Groups are not completely static. HOOMD-blue re-evaluates the filter
specifications and updates the group membership whenever the number of particles
in the simulation changes. A future release will include an operation that you
can schedule to periodically update groups on demand.
For molecular dynamics simulations, each group maintains a count of the number
of degrees of freedom given to the group by integration methods. This count is
used by `hoomd.md.compute.ThermodynamicQuantities` and the integration methods
themselves to compute the kinetic temperature. See
`hoomd.State.update_group_dof` for details on when HOOMD-blue updates this
count.
"""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
"""Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
Add particle filter overview information."""Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a **group**,
an internally maintained list of the selected particles. Subsequent uses of the
same particle filter specification will resolve to the same group *and the
originally selected particles*, **even if the state of the system has changed.**
Groups are not completely static. HOOMD-blue re-evaluates the filter
specifications and updates the group membership whenever the number of particles
in the simulation changes. A future release will include an operation that you
can schedule to periodically update groups on demand.
For molecular dynamics simulations, each group maintains a count of the number
of degrees of freedom given to the group by integration methods. This count is
used by `hoomd.md.compute.ThermodynamicQuantities` and the integration methods
themselves to compute the kinetic temperature. See
`hoomd.State.update_group_dof` for details on when HOOMD-blue updates this
count.
"""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
<commit_before>"""Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
<commit_msg>Add particle filter overview information.<commit_after>"""Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a **group**,
an internally maintained list of the selected particles. Subsequent uses of the
same particle filter specification will resolve to the same group *and the
originally selected particles*, **even if the state of the system has changed.**
Groups are not completely static. HOOMD-blue re-evaluates the filter
specifications and updates the group membership whenever the number of particles
in the simulation changes. A future release will include an operation that you
can schedule to periodically update groups on demand.
For molecular dynamics simulations, each group maintains a count of the number
of degrees of freedom given to the group by integration methods. This count is
used by `hoomd.md.compute.ThermodynamicQuantities` and the integration methods
themselves to compute the kinetic temperature. See
`hoomd.State.update_group_dof` for details on when HOOMD-blue updates this
count.
"""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
|
bb5b84cd71ff95bd2539afce75491139fbc6f066
|
pi_control_client/gpio.py
|
pi_control_client/gpio.py
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin': pin_number, 'action': 'on'})
def off(self, pin_number):
return self._call({'pin': pin_number, 'action': 'off'})
def read(self, pin_number):
return self._call({'pin': pin_number, 'action': 'read'})
def get_config(self, pin_number=None):
if pin_number:
return self._call({'pin': pin_number, 'action': 'get_config'})
return self._call({'action': 'get_config'})
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'on'})
def off(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'off'})
def read(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'read'})
def config(self, device_key, pin_number=None):
if pin_number:
return self._call(device_key, {'pin': pin_number, 'action': 'get_config'})
return self._call(device_key, {'action': 'get_config'})
|
Add device_key on every call in GPIO client
|
Add device_key on every call in GPIO client
|
Python
|
mit
|
HydAu/Projectweekends_Pi-Control-Client,projectweekend/Pi-Control-Client
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin': pin_number, 'action': 'on'})
def off(self, pin_number):
return self._call({'pin': pin_number, 'action': 'off'})
def read(self, pin_number):
return self._call({'pin': pin_number, 'action': 'read'})
def get_config(self, pin_number=None):
if pin_number:
return self._call({'pin': pin_number, 'action': 'get_config'})
return self._call({'action': 'get_config'})
Add device_key on every call in GPIO client
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'on'})
def off(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'off'})
def read(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'read'})
def config(self, device_key, pin_number=None):
if pin_number:
return self._call(device_key, {'pin': pin_number, 'action': 'get_config'})
return self._call(device_key, {'action': 'get_config'})
|
<commit_before>from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin': pin_number, 'action': 'on'})
def off(self, pin_number):
return self._call({'pin': pin_number, 'action': 'off'})
def read(self, pin_number):
return self._call({'pin': pin_number, 'action': 'read'})
def get_config(self, pin_number=None):
if pin_number:
return self._call({'pin': pin_number, 'action': 'get_config'})
return self._call({'action': 'get_config'})
<commit_msg>Add device_key on every call in GPIO client<commit_after>
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'on'})
def off(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'off'})
def read(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'read'})
def config(self, device_key, pin_number=None):
if pin_number:
return self._call(device_key, {'pin': pin_number, 'action': 'get_config'})
return self._call(device_key, {'action': 'get_config'})
|
from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin': pin_number, 'action': 'on'})
def off(self, pin_number):
return self._call({'pin': pin_number, 'action': 'off'})
def read(self, pin_number):
return self._call({'pin': pin_number, 'action': 'read'})
def get_config(self, pin_number=None):
if pin_number:
return self._call({'pin': pin_number, 'action': 'get_config'})
return self._call({'action': 'get_config'})
Add device_key on every call in GPIO clientfrom rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'on'})
def off(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'off'})
def read(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'read'})
def config(self, device_key, pin_number=None):
if pin_number:
return self._call(device_key, {'pin': pin_number, 'action': 'get_config'})
return self._call(device_key, {'action': 'get_config'})
|
<commit_before>from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin': pin_number, 'action': 'on'})
def off(self, pin_number):
return self._call({'pin': pin_number, 'action': 'off'})
def read(self, pin_number):
return self._call({'pin': pin_number, 'action': 'read'})
def get_config(self, pin_number=None):
if pin_number:
return self._call({'pin': pin_number, 'action': 'get_config'})
return self._call({'action': 'get_config'})
<commit_msg>Add device_key on every call in GPIO client<commit_after>from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'on'})
def off(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'off'})
def read(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action': 'read'})
def config(self, device_key, pin_number=None):
if pin_number:
return self._call(device_key, {'pin': pin_number, 'action': 'get_config'})
return self._call(device_key, {'action': 'get_config'})
|
266027514c740c30c0efae5fcd1e2932f1be9933
|
perfrunner/tests/ycsb2.py
|
perfrunner/tests/ycsb2.py
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
Check the number of items a little bit later
|
Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
|
Python
|
apache-2.0
|
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
<commit_before>from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
<commit_msg>Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com><commit_after>
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
<commit_before>from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
<commit_msg>Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com><commit_after>from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
0445c8a8e82d3ed5c05537b43616a3b94dcf786f
|
wye/workshops/templatetags/workshop_action_button.py
|
wye/workshops/templatetags/workshop_action_button.py
|
from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if workshop.status == WorkshopStatus.REQUESTED:
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
from datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if (workshop.status == WorkshopStatus.REQUESTED and
'tutor' in user.profile.get_user_type):
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
Add filter to show button only if selected role tutor
|
Add filter to show button only if selected role tutor
|
Python
|
mit
|
shankisg/wye,pythonindia/wye,harisibrahimkv/wye,DESHRAJ/wye,harisibrahimkv/wye,harisibrahimkv/wye,shankisg/wye,DESHRAJ/wye,pythonindia/wye,shankisg/wye,DESHRAJ/wye,shankig/wye,pythonindia/wye,DESHRAJ/wye,pythonindia/wye,harisibrahimkv/wye,shankig/wye,shankisg/wye,shankig/wye,shankig/wye
|
from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if workshop.status == WorkshopStatus.REQUESTED:
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
Add filter to show button only if selected role tutor
|
from datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if (workshop.status == WorkshopStatus.REQUESTED and
'tutor' in user.profile.get_user_type):
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
<commit_before>from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if workshop.status == WorkshopStatus.REQUESTED:
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
<commit_msg>Add filter to show button only if selected role tutor<commit_after>
|
from datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if (workshop.status == WorkshopStatus.REQUESTED and
'tutor' in user.profile.get_user_type):
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if workshop.status == WorkshopStatus.REQUESTED:
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
Add filter to show button only if selected role tutorfrom datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if (workshop.status == WorkshopStatus.REQUESTED and
'tutor' in user.profile.get_user_type):
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
<commit_before>from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if workshop.status == WorkshopStatus.REQUESTED:
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
<commit_msg>Add filter to show button only if selected role tutor<commit_after>from datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopStatus.DECLINED]
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_draft_button)
def show_requested_button(workshop, user):
if (workshop.status == WorkshopStatus.HOLD
and user in workshop.requester.user.all()):
return True
return False
register.filter(show_requested_button)
def show_accepted_button(workshop, user):
if (workshop.status == WorkshopStatus.REQUESTED and
'tutor' in user.profile.get_user_type):
return True
return False
register.filter(show_accepted_button)
def show_feedback_button(workshop, user):
if (workshop.status == WorkshopStatus.COMPLETED
and (user in workshop.requester.user.all()
or user in workshop.presenter.all())
and datetime.now().date() > workshop.expected_date):
return True
return False
register.filter(show_feedback_button)
def show_decline_button(workshop, user):
if (workshop.status == WorkshopStatus.ACCEPTED
and user in workshop.presenter.all()):
return True
return False
register.filter(show_decline_button)
|
65cd9eff50a95d53b75d9bd6a02e56e7a6b6262e
|
build/fbcode_builder/specs/fbthrift.py
|
build/fbcode_builder/specs/fbthrift.py
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
Migrate from Folly Format to fmt
|
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
|
Python
|
apache-2.0
|
facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
<commit_before>#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
<commit_msg>Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f<commit_after>
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
<commit_before>#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
<commit_msg>Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f<commit_after>#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, fmt, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
3c1e52ccd329c255649b0ca4e3727f60996f8e34
|
src/apps/console/views.py
|
src/apps/console/views.py
|
from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)})
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
|
Make the console app work with the new user model.
|
Make the console app work with the new user model.
|
Python
|
mit
|
anantb/datahub,anantb/datahub,anantb/datahub,datahuborg/datahub,anantb/datahub,anantb/datahub,anantb/datahub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,anantb/datahub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,RogerTangos/datahub-stub
|
from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)})Make the console app work with the new user model.
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
|
<commit_before>from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)})<commit_msg>Make the console app work with the new user model.<commit_after>
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
|
from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)})Make the console app work with the new user model.from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
|
<commit_before>from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)})<commit_msg>Make the console app work with the new user model.<commit_after>from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
|
4cb45f38cc291b2bf909344a0fc68ff94421a26a
|
alignak_app/locales/__init__.py
|
alignak_app/locales/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
Fix pep8 missing newline at end of file
|
Fix pep8 missing newline at end of file
|
Python
|
agpl-3.0
|
Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""Fix pep8 missing newline at end of file
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""<commit_msg>Fix pep8 missing newline at end of file<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""Fix pep8 missing newline at end of file#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""<commit_msg>Fix pep8 missing newline at end of file<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Matthieu Estrada, ttamalfor@gmail.com
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp). If not, see <http://www.gnu.org/licenses/>.
"""
The Locales package contains classes to manage translation.
"""
|
8b9454fdf9e54059edcc951f188c05cb0f34c0a4
|
lookup_isbn.py
|
lookup_isbn.py
|
#!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
book = Books('config.yml').lookup('9781449389734')
print yaml.dump(book, default_flow_style = False)
|
#!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
books = Books('config.yml')
for isbn in sys.argv[1:]:
book = books.lookup(isbn)
with open('raw_data/{0}.yml'.format(isbn), 'w') as out:
out.write(yaml.dump(book, default_flow_style = False))
|
Read commandline args as isbns
|
Read commandline args as isbns
|
Python
|
mit
|
sortelli/book_pivot,sortelli/book_pivot
|
#!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
book = Books('config.yml').lookup('9781449389734')
print yaml.dump(book, default_flow_style = False)
Read commandline args as isbns
|
#!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
books = Books('config.yml')
for isbn in sys.argv[1:]:
book = books.lookup(isbn)
with open('raw_data/{0}.yml'.format(isbn), 'w') as out:
out.write(yaml.dump(book, default_flow_style = False))
|
<commit_before>#!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
book = Books('config.yml').lookup('9781449389734')
print yaml.dump(book, default_flow_style = False)
<commit_msg>Read commandline args as isbns<commit_after>
|
#!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
books = Books('config.yml')
for isbn in sys.argv[1:]:
book = books.lookup(isbn)
with open('raw_data/{0}.yml'.format(isbn), 'w') as out:
out.write(yaml.dump(book, default_flow_style = False))
|
#!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
book = Books('config.yml').lookup('9781449389734')
print yaml.dump(book, default_flow_style = False)
Read commandline args as isbns#!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
books = Books('config.yml')
for isbn in sys.argv[1:]:
book = books.lookup(isbn)
with open('raw_data/{0}.yml'.format(isbn), 'w') as out:
out.write(yaml.dump(book, default_flow_style = False))
|
<commit_before>#!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
book = Books('config.yml').lookup('9781449389734')
print yaml.dump(book, default_flow_style = False)
<commit_msg>Read commandline args as isbns<commit_after>#!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
)
def lookup(self, isbn):
product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books")
book = {
'title': product.title,
'image_url': product.large_image_url,
'sales_rank': int(product.sales_rank),
'price': product.price_and_currency[0],
'offer_url': product.offer_url,
'authors': product.authors,
'publisher': product.publisher,
'isbn': isbn,
'binding': product.binding,
'pages': product.pages,
'publication_date': product.publication_date,
'list_price': product.list_price[0]
}
return book
books = Books('config.yml')
for isbn in sys.argv[1:]:
book = books.lookup(isbn)
with open('raw_data/{0}.yml'.format(isbn), 'w') as out:
out.write(yaml.dump(book, default_flow_style = False))
|
326c249e41e431112ae213c20bf948a7ae351a31
|
visualisation_display.py
|
visualisation_display.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
Add vmin, vmax and possible labels to display of images
|
Add vmin, vmax and possible labels to display of images
|
Python
|
mit
|
ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
Add vmin, vmax and possible labels to display of images
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
<commit_msg>Add vmin, vmax and possible labels to display of images<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
Add vmin, vmax and possible labels to display of images#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
<commit_msg>Add vmin, vmax and possible labels to display of images<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
bb0b72333b715956740373c3ba80a8193b99a8cc
|
app/services/updater_service.py
|
app/services/updater_service.py
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
|
Add message before running ansible.
|
Add message before running ansible.
|
Python
|
mit
|
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
Add message before running ansible.
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
|
<commit_before>from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
<commit_msg>Add message before running ansible.<commit_after>
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
|
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
Add message before running ansible.from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
|
<commit_before>from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
<commit_msg>Add message before running ansible.<commit_after>from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
|
d30355ace2c84cad198fd4bfcc3d6a211275fb76
|
src/ggrc_basic_permissions/roles/AuditorReader.py
|
src/ggrc_basic_permissions/roles/AuditorReader.py
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Snapshot",
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
Add support for reading snapshots for auditor reader
|
Add support for reading snapshots for auditor reader
|
Python
|
apache-2.0
|
AleksNeStu/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
Add support for reading snapshots for auditor reader
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Snapshot",
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
<commit_before># Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
<commit_msg>Add support for reading snapshots for auditor reader<commit_after>
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Snapshot",
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
Add support for reading snapshots for auditor reader# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Snapshot",
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
<commit_before># Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
<commit_msg>Add support for reading snapshots for auditor reader<commit_after># Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
required to perform the audit.
"""
permissions = {
"read": [
"Snapshot",
"Categorization",
"Category",
"ControlCategory",
"ControlAssertion",
"Control",
"Assessment",
"Issue",
"ControlControl",
"DataAsset",
"AccessGroup",
"Directive",
"Contract",
"Policy",
"Regulation",
"Standard",
"Document",
"Facility",
"Help",
"Market",
"Objective",
"ObjectDocument",
"ObjectPerson",
"Option",
"OrgGroup",
"Vendor",
"PopulationSample",
"Product",
"Project",
"Relationship",
"Section",
"Clause",
"SystemOrProcess",
"System",
"Process",
"SystemControl",
"SystemSystem",
"ObjectOwner",
"Person",
"Program",
"Role",
"Context",
{
"type": "BackgroundTask",
"terms": {
"property_name": "modified_by",
"value": "$current_user"
},
"condition": "is"
},
],
"create": [],
"view_object_page": [],
"update": [],
"delete": []
}
|
114eae527cce97423ec5cc5896a4728dc0764d2c
|
chunsabot/modules/images.py
|
chunsabot/modules/images.py
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
Fix some confusion of creating folders
|
Fix some confusion of creating folders
|
Python
|
mit
|
susemeee/Chunsabot-framework
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
Fix some confusion of creating folders
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
<commit_before>import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
<commit_msg>Fix some confusion of creating folders<commit_after>
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
Fix some confusion of creating foldersimport os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
<commit_before>import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, id_generator(), 'image_processing')
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
<commit_msg>Fix some confusion of creating folders<commit_after>import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@brain.route("@image")
def add_image_description(msg, extras):
attachment = extras['attachment']
if not attachment:
return None
path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing'))
if not os.path.isdir(path):
os.mkdir(path)
# Moving to temp path
img = shutil.move(attachment, path)
img_folder = os.path.dirname(img)
result = subprocess.run(
"th {}/eval.lua -model {} -gpuid -1 -image_folder {} -batch_size 1"\
.format(RNN_PATH, MODEL_PATH, img_folder)
)
os.rmdir(img_folder)
result_message = None
with open(os.path.join(result, "vis/vis.json"), 'r') as output:
json_output = json.loads(output)
result_message = json_output[0]['caption']
return result_message
|
dacd02835137a8729d326b0be549b8107ba59c25
|
ci/generate_pipeline_yml.py
|
ci/generate_pipeline_yml.py
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1_12', '2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
Remove PCF 1.12 from CI.
|
Remove PCF 1.12 from CI.
|
Python
|
apache-2.0
|
cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1_12', '2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
Remove PCF 1.12 from CI.
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
<commit_before>#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1_12', '2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
<commit_msg>Remove PCF 1.12 from CI.<commit_after>
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1_12', '2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
Remove PCF 1.12 from CI.#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
<commit_before>#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['1_12', '2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
<commit_msg>Remove PCF 1.12 from CI.<commit_after>#!/usr/bin/env python
import os
from jinja2 import Template
clusters = ['2_0', '2_1', '2_2']
# Commenting out this as we only have one example and it breaks
tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))]
with open('pipeline.yml.jinja2', 'r') as f:
t = Template(f.read());
with open('pipeline.yml', 'w') as f:
f.write(t.render(clusters=clusters, tiles=tiles))
print "Successfully generated pipeline.yml"
|
1f4349e20a98e622124c1e5bc121053e4775152f
|
login/signals.py
|
login/signals.py
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(m2m_changed, sender=User.groups.through)
def user_groups_changed_handler(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
# invalidate permissions cache
cache_clear()
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
Add signal to invalidate cache when groups change.
|
Add signal to invalidate cache when groups change.
|
Python
|
bsd-3-clause
|
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
Add signal to invalidate cache when groups change.
|
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(m2m_changed, sender=User.groups.through)
def user_groups_changed_handler(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
# invalidate permissions cache
cache_clear()
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
<commit_before>from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
<commit_msg>Add signal to invalidate cache when groups change.<commit_after>
|
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(m2m_changed, sender=User.groups.through)
def user_groups_changed_handler(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
# invalidate permissions cache
cache_clear()
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
Add signal to invalidate cache when groups change.from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(m2m_changed, sender=User.groups.through)
def user_groups_changed_handler(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
# invalidate permissions cache
cache_clear()
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
<commit_before>from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
<commit_msg>Add signal to invalidate cache when groups change.<commit_after>from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(m2m_changed, sender=User.groups.through)
def user_groups_changed_handler(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
# invalidate permissions cache
cache_clear()
# Add signal to automatically extend group profile
@receiver(post_save, sender=Group)
def create_group_profile(sender, instance, created, **kwargs):
if created:
GroupProfile.objects.create(group=instance)
|
48455d0d1b8632d6b512e257d6dd914defd7ae84
|
px/px_process_test.py
|
px/px_process_test.py
|
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
|
import getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
def test_get_all():
all = px_process.get_all()
# Assert that current PID is part of all
assert os.getpid() in map(lambda p: p.pid, all)
# Assert that all contains no duplicate PIDs
seen_pids = set()
for process in all:
pid = process.pid
assert pid not in seen_pids
seen_pids.add(pid)
# Assert that the current PID has the correct user name
current_process = filter(lambda process: process.pid == os.getpid(), all)[0]
assert current_process.username == getpass.getuser()
|
Add (failing) test for getting all processes
|
Add (failing) test for getting all processes
|
Python
|
mit
|
walles/px,walles/px
|
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
Add (failing) test for getting all processes
|
import getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
def test_get_all():
all = px_process.get_all()
# Assert that current PID is part of all
assert os.getpid() in map(lambda p: p.pid, all)
# Assert that all contains no duplicate PIDs
seen_pids = set()
for process in all:
pid = process.pid
assert pid not in seen_pids
seen_pids.add(pid)
# Assert that the current PID has the correct user name
current_process = filter(lambda process: process.pid == os.getpid(), all)[0]
assert current_process.username == getpass.getuser()
|
<commit_before>import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
<commit_msg>Add (failing) test for getting all processes<commit_after>
|
import getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
def test_get_all():
all = px_process.get_all()
# Assert that current PID is part of all
assert os.getpid() in map(lambda p: p.pid, all)
# Assert that all contains no duplicate PIDs
seen_pids = set()
for process in all:
pid = process.pid
assert pid not in seen_pids
seen_pids.add(pid)
# Assert that the current PID has the correct user name
current_process = filter(lambda process: process.pid == os.getpid(), all)[0]
assert current_process.username == getpass.getuser()
|
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
Add (failing) test for getting all processesimport getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
def test_get_all():
all = px_process.get_all()
# Assert that current PID is part of all
assert os.getpid() in map(lambda p: p.pid, all)
# Assert that all contains no duplicate PIDs
seen_pids = set()
for process in all:
pid = process.pid
assert pid not in seen_pids
seen_pids.add(pid)
# Assert that the current PID has the correct user name
current_process = filter(lambda process: process.pid == os.getpid(), all)[0]
assert current_process.username == getpass.getuser()
|
<commit_before>import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
<commit_msg>Add (failing) test for getting all processes<commit_after>import getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.PxProcess(process_builder)
assert test_me.pid == 7
assert test_me.user == "usernamex"
assert test_me.cpu_time_s == "1.300s"
assert test_me.memory_percent_s == "43%"
assert test_me.cmdline == "hej kontinent"
def test_get_all():
all = px_process.get_all()
# Assert that current PID is part of all
assert os.getpid() in map(lambda p: p.pid, all)
# Assert that all contains no duplicate PIDs
seen_pids = set()
for process in all:
pid = process.pid
assert pid not in seen_pids
seen_pids.add(pid)
# Assert that the current PID has the correct user name
current_process = filter(lambda process: process.pid == os.getpid(), all)[0]
assert current_process.username == getpass.getuser()
|
7352a257a08ad4d41261dd0c1076cde966d2a5c2
|
sharer/multi.py
|
sharer/multi.py
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
for sharer in self.sharers.itervalues():
sharer.send(*args, **kw)
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
services = kw.pop('_services', {})
for name, sharer in self.sharers.iteritems():
if services.get(name, True):
services[name] = sharer.send(*args, **kw)
return services
|
Add _services keyword argument to MultiSharer's send.
|
Add _services keyword argument to MultiSharer's send.
|
Python
|
mit
|
FelixLoether/python-sharer
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
for sharer in self.sharers.itervalues():
sharer.send(*args, **kw)
Add _services keyword argument to MultiSharer's send.
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
services = kw.pop('_services', {})
for name, sharer in self.sharers.iteritems():
if services.get(name, True):
services[name] = sharer.send(*args, **kw)
return services
|
<commit_before>from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
for sharer in self.sharers.itervalues():
sharer.send(*args, **kw)
<commit_msg>Add _services keyword argument to MultiSharer's send.<commit_after>
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
services = kw.pop('_services', {})
for name, sharer in self.sharers.iteritems():
if services.get(name, True):
services[name] = sharer.send(*args, **kw)
return services
|
from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
for sharer in self.sharers.itervalues():
sharer.send(*args, **kw)
Add _services keyword argument to MultiSharer's send.from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
services = kw.pop('_services', {})
for name, sharer in self.sharers.iteritems():
if services.get(name, True):
services[name] = sharer.send(*args, **kw)
return services
|
<commit_before>from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
for sharer in self.sharers.itervalues():
sharer.send(*args, **kw)
<commit_msg>Add _services keyword argument to MultiSharer's send.<commit_after>from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def send(self, *args, **kw):
services = kw.pop('_services', {})
for name, sharer in self.sharers.iteritems():
if services.get(name, True):
services[name] = sharer.send(*args, **kw)
return services
|
7209e44f913d2f28f94bb4d67ba875ff635261d2
|
myhdl/_compat.py
|
myhdl/_compat.py
|
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
|
from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
Revert "Remove the __future__ flags"
|
Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.
|
Python
|
lgpl-2.1
|
jmgc/myhdl-numeric,jmgc/myhdl-numeric,jmgc/myhdl-numeric
|
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.
|
from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
<commit_before>import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
<commit_msg>Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.<commit_after>
|
from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
<commit_before>import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', PyCF_ONLY_AST)
<commit_msg>Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.<commit_after>from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
c769b66c546ad3fd9d04c0607506a49e9d3bff4a
|
fortdepend/preprocessor.py
|
fortdepend/preprocessor.py
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
Fix super() call for py2.7
|
Fix super() call for py2.7
|
Python
|
mit
|
ZedThree/fort_depend.py,ZedThree/fort_depend.py
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
Fix super() call for py2.7
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
<commit_before>import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
<commit_msg>Fix super() call for py2.7<commit_after>
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
Fix super() call for py2.7import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
<commit_before>import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
<commit_msg>Fix super() call for py2.7<commit_after>import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
83c52f6a294b69e48d455f9037be088420d4cfa8
|
selectable/__init__.py
|
selectable/__init__.py
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
|
Simplify version string and update to reflect current status.
|
Simplify version string and update to reflect current status.
|
Python
|
bsd-2-clause
|
mlavin/django-selectable,affan2/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
Simplify version string and update to reflect current status.
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
|
<commit_before>"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
<commit_msg>Simplify version string and update to reflect current status.<commit_after>
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
|
"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
Simplify version string and update to reflect current status."""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
|
<commit_before>"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
<commit_msg>Simplify version string and update to reflect current status.<commit_after>"""
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
|
394e3ffd4221a749bcc8df7d11da2f3bc3ace5f9
|
getalltext.py
|
getalltext.py
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages. '
'If someone doesn\'t have a username, the line will start with "@: ".'
'Useful when output will be read back as a chatlog.',
action='store_true')
parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when '
'output will be piped into analysis expecting newline separated messages. ',
action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
if 'username' in event['from']:
print('@' + event['from']['username'],end=': ')
else:
print('@',end=': ')
if args.no_newlines:
print(event['text'].replace('\n',''))
else:
print(event["text"])
if __name__ == "__main__":
main()
|
Add option to remove newlines; remove bug on messages sent by someone without a username
|
Add option to remove newlines; remove bug on messages sent by someone without a username
|
Python
|
mit
|
expectocode/telegram-analysis,expectocode/telegramAnalysis
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
Add option to remove newlines; remove bug on messages sent by someone without a username
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages. '
'If someone doesn\'t have a username, the line will start with "@: ".'
'Useful when output will be read back as a chatlog.',
action='store_true')
parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when '
'output will be piped into analysis expecting newline separated messages. ',
action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
if 'username' in event['from']:
print('@' + event['from']['username'],end=': ')
else:
print('@',end=': ')
if args.no_newlines:
print(event['text'].replace('\n',''))
else:
print(event["text"])
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
<commit_msg>Add option to remove newlines; remove bug on messages sent by someone without a username<commit_after>
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages. '
'If someone doesn\'t have a username, the line will start with "@: ".'
'Useful when output will be read back as a chatlog.',
action='store_true')
parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when '
'output will be piped into analysis expecting newline separated messages. ',
action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
if 'username' in event['from']:
print('@' + event['from']['username'],end=': ')
else:
print('@',end=': ')
if args.no_newlines:
print(event['text'].replace('\n',''))
else:
print(event["text"])
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
Add option to remove newlines; remove bug on messages sent by someone without a username#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages. '
'If someone doesn\'t have a username, the line will start with "@: ".'
'Useful when output will be read back as a chatlog.',
action='store_true')
parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when '
'output will be piped into analysis expecting newline separated messages. ',
action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
if 'username' in event['from']:
print('@' + event['from']['username'],end=': ')
else:
print('@',end=': ')
if args.no_newlines:
print(event['text'].replace('\n',''))
else:
print(event["text"])
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages',action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
print(event['from']['username'],end=': ')
#do i need the "from" here?
print(event["text"])
if __name__ == "__main__":
main()
<commit_msg>Add option to remove newlines; remove bug on messages sent by someone without a username<commit_after>#!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to analyse')
parser.add_argument('-u','--usernames', help='Show usernames before messages. '
'If someone doesn\'t have a username, the line will start with "@: ".'
'Useful when output will be read back as a chatlog.',
action='store_true')
parser.add_argument('-n','--no-newlines', help='Remove all newlines from messages. Useful when '
'output will be piped into analysis expecting newline separated messages. ',
action='store_true')
args=parser.parse_args()
filepath = args.filepath
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if args.usernames:
if 'username' in event['from']:
print('@' + event['from']['username'],end=': ')
else:
print('@',end=': ')
if args.no_newlines:
print(event['text'].replace('\n',''))
else:
print(event["text"])
if __name__ == "__main__":
main()
|
a1da5e7171a03f98612395f90766c7d4adf1dd61
|
zinnia_twitter/management/commands/get_twitter_access.py
|
zinnia_twitter/management/commands/get_twitter_access.py
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token)
print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
|
Fix an error accessing the twitter returned auth object
|
Fix an error accessing the twitter returned auth object
|
Python
|
bsd-3-clause
|
django-blog-zinnia/zinnia-twitter
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
Fix an error accessing the twitter returned auth object
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token)
print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
|
<commit_before>"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
<commit_msg>Fix an error accessing the twitter returned auth object<commit_after>
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token)
print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
|
"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
Fix an error accessing the twitter returned auth object"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token)
print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
|
<commit_before>"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
<commit_msg>Fix an error accessing the twitter returned auth object<commit_after>"""
Command for getting the Twitter oauth access.
http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
"""
from django.core.management.base import NoArgsCommand
import tweepy
class Command(NoArgsCommand):
"""
This is an implementation of script showed in the
step 3 of the tutorial.
"""
help = 'Get access to your Twitter account'
def handle_noargs(self, **options):
CONSUMER_KEY = raw_input('Paste your Consumer Key here: ')
CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token)
print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
|
eea1ba0273b8e5362f6b27854e29e6053555fb2a
|
gittip/cli.py
|
gittip/cli.py
|
"""This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
"""This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to trust changes to statement_timeout. The point
# here is that we want to turn off statement_timeout for payday.
os.environ['DATABASE_MAXCONN'] = '1'
db = wireup.db()
db.run("SET statement_timeout = 0")
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
Configure payday for no db timeout
|
Configure payday for no db timeout
|
Python
|
mit
|
mccolgst/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com
|
"""This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
Configure payday for no db timeout
|
"""This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to trust changes to statement_timeout. The point
# here is that we want to turn off statement_timeout for payday.
os.environ['DATABASE_MAXCONN'] = '1'
db = wireup.db()
db.run("SET statement_timeout = 0")
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
<commit_before>"""This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
<commit_msg>Configure payday for no db timeout<commit_after>
|
"""This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to trust changes to statement_timeout. The point
# here is that we want to turn off statement_timeout for payday.
os.environ['DATABASE_MAXCONN'] = '1'
db = wireup.db()
db.run("SET statement_timeout = 0")
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
"""This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
Configure payday for no db timeout"""This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to trust changes to statement_timeout. The point
# here is that we want to turn off statement_timeout for payday.
os.environ['DATABASE_MAXCONN'] = '1'
db = wireup.db()
db.run("SET statement_timeout = 0")
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
<commit_before>"""This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
<commit_msg>Configure payday for no db timeout<commit_after>"""This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to trust changes to statement_timeout. The point
# here is that we want to turn off statement_timeout for payday.
os.environ['DATABASE_MAXCONN'] = '1'
db = wireup.db()
db.run("SET statement_timeout = 0")
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip before calling wireup.billing.
from gittip.billing.payday import Payday
try:
Payday(db).run()
except KeyboardInterrupt:
pass
except:
import aspen
import traceback
aspen.log(traceback.format_exc())
|
191e62a2547c4d3d013cb4c68fed60f1619fe82c
|
pyheufybot/modules/say.py
|
pyheufybot/modules/say.py
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line."
def execute(self, message):
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
return True
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line."
def execute(self, message):
if message.params[0].lower() == "say":
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
elif message.params[0].lower() == "sayremote":
if len(message.params) < 3:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.params[1], " ".join(message.params[2:]))
return True
|
Add a remote option to Say
|
Add a remote option to Say
|
Python
|
mit
|
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line."
def execute(self, message):
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
return True
Add a remote option to Say
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line."
def execute(self, message):
if message.params[0].lower() == "say":
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
elif message.params[0].lower() == "sayremote":
if len(message.params) < 3:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.params[1], " ".join(message.params[2:]))
return True
|
<commit_before>from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line."
def execute(self, message):
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
return True
<commit_msg>Add a remote option to Say<commit_after>
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line."
def execute(self, message):
if message.params[0].lower() == "say":
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
elif message.params[0].lower() == "sayremote":
if len(message.params) < 3:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.params[1], " ".join(message.params[2:]))
return True
|
from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line."
def execute(self, message):
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
return True
Add a remote option to Sayfrom pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line."
def execute(self, message):
if message.params[0].lower() == "say":
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
elif message.params[0].lower() == "sayremote":
if len(message.params) < 3:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.params[1], " ".join(message.params[2:]))
return True
|
<commit_before>from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line."
def execute(self, message):
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
return True
<commit_msg>Add a remote option to Say<commit_after>from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
self.messageTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message>/sayremote <target> <message> | Makes the bot say the given line."
def execute(self, message):
if message.params[0].lower() == "say":
if len(message.params) == 1:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.replyTo, " ".join(message.params[1:]))
elif message.params[0].lower() == "sayremote":
if len(message.params) < 3:
self.bot.msg(message.replyTo, "Say what?")
else:
self.bot.msg(message.params[1], " ".join(message.params[2:]))
return True
|
f80cbe4b962fc9dd6341e9a59848238f5d7dee5e
|
src/sas/qtgui/MainWindow/UnitTesting/WelcomePanelTest.py
|
src/sas/qtgui/MainWindow/UnitTesting/WelcomePanelTest.py
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
assert "Build:" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
Fix test for change in panel text
|
Fix test for change in panel text
|
Python
|
bsd-3-clause
|
SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
assert "Build:" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
Fix test for change in panel text
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
<commit_before>import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
assert "Build:" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
<commit_msg>Fix test for change in panel text<commit_after>
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
assert "Build:" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
Fix test for change in panel textimport sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
<commit_before>import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
assert "Build:" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
<commit_msg>Fix test for change in panel text<commit_after>import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePanel(None)
yield w
w.close()
def testDefaults(self, widget):
'''Test the GUI in its default state'''
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == "Welcome"
def testVersion(self, widget):
'''Test the version string'''
version = widget.lblVersion
assert isinstance(version, QtWidgets.QLabel)
assert "SasView" in version.text()
for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "):
assert inst in version.text()
|
78032531e9fe1ab99f6c0e021250754fe5375ab9
|
src/zeit/content/article/edit/browser/tests/test_sync.py
|
src/zeit/content/article/edit/browser/tests/test_sync.py
|
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
|
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article
|
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
<commit_before>import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
<commit_msg>Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.<commit_after>
|
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
<commit_before>import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
<commit_msg>Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.<commit_after>import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
ee1aea5ab2002f14fbf0191e3e1a94988fcb7e08
|
guetzli_img_compression.py
|
guetzli_img_compression.py
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffix)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
Update the output file name
|
Update the output file name
|
Python
|
mit
|
JonyFang/guetzli-img-compression
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
Update the output file name
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffix)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
<commit_before># -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
<commit_msg>Update the output file name<commit_after>
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffix)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
Update the output file name# -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffix)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
<commit_before># -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
<commit_msg>Update the output file name<commit_after># -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffix)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
###########################################################################
#main
def main():
if os.path.isdir(source):
for root, dirs, files in os.walk(source):
for a_file in files:
suffix = os.path.splitext(a_file)[1]
if suffix in TYPES:
convert_a_img(os.path.join(root, a_file))
pass
elif os.path.isfile(source):
convert_a_img(source)
else:
print('Please check the input, not found any files or folders.')
main()
|
8c88da640f2fab19254e96a144461f2c65aff720
|
wagtailstartproject/project_template/tests/middleware.py
|
wagtailstartproject/project_template/tests/middleware.py
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'),
1
)
return response
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes(
'<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code),
encoding='ascii'
),
1
)
response['Content-Length'] = str(len(response.content))
return response
|
Reset Content-Length after changing the length of the response
|
Reset Content-Length after changing the length of the response
|
Python
|
mit
|
leukeleu/wagtail-startproject,leukeleu/wagtail-startproject
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'),
1
)
return response
Reset Content-Length after changing the length of the response
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes(
'<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code),
encoding='ascii'
),
1
)
response['Content-Length'] = str(len(response.content))
return response
|
<commit_before>try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'),
1
)
return response
<commit_msg>Reset Content-Length after changing the length of the response<commit_after>
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes(
'<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code),
encoding='ascii'
),
1
)
response['Content-Length'] = str(len(response.content))
return response
|
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'),
1
)
return response
Reset Content-Length after changing the length of the responsetry:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes(
'<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code),
encoding='ascii'
),
1
)
response['Content-Length'] = str(len(response.content))
return response
|
<commit_before>try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'),
1
)
return response
<commit_msg>Reset Content-Length after changing the length of the response<commit_after>try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_response(self, request, response):
# Only do this for HTML pages
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
b'</head>',
bytes(
'<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code),
encoding='ascii'
),
1
)
response['Content-Length'] = str(len(response.content))
return response
|
ae4e4dc7f00afbd1d93b43bf5d383139891d5596
|
hoover/search/ratelimit.py
|
hoover/search/ratelimit.py
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
Fix `is_anonymous` for Django 2
|
Fix `is_anonymous` for Django 2
|
Python
|
mit
|
hoover/search,hoover/search,hoover/search
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
Fix `is_anonymous` for Django 2
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
<commit_before>from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
<commit_msg>Fix `is_anonymous` for Django 2<commit_after>
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
Fix `is_anonymous` for Django 2from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
<commit_before>from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
<commit_msg>Fix `is_anonymous` for Django 2<commit_after>from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
a10c7ed55151533a647332c6b910b3724d5b3af1
|
il2fb/ds/airbridge/json.py
|
il2fb/ds/airbridge/json.py
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubclass(cls, TimestampedData):
result = {
key: getattr(obj, key)
for key in cls.__slots__
}
elif hasattr(obj, 'to_primitive'):
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
Update custom JSONEncoder to treat TimestampedData as dict
|
Update custom JSONEncoder to treat TimestampedData as dict
|
Python
|
mit
|
IL2HorusTeam/il2fb-ds-airbridge
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
Update custom JSONEncoder to treat TimestampedData as dict
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubclass(cls, TimestampedData):
result = {
key: getattr(obj, key)
for key in cls.__slots__
}
elif hasattr(obj, 'to_primitive'):
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
<commit_before># -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
<commit_msg>Update custom JSONEncoder to treat TimestampedData as dict<commit_after>
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubclass(cls, TimestampedData):
result = {
key: getattr(obj, key)
for key in cls.__slots__
}
elif hasattr(obj, 'to_primitive'):
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
Update custom JSONEncoder to treat TimestampedData as dict# -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubclass(cls, TimestampedData):
result = {
key: getattr(obj, key)
for key in cls.__slots__
}
elif hasattr(obj, 'to_primitive'):
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
<commit_before># -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
<commit_msg>Update custom JSONEncoder to treat TimestampedData as dict<commit_after># -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubclass(cls, TimestampedData):
result = {
key: getattr(obj, key)
for key in cls.__slots__
}
elif hasattr(obj, 'to_primitive'):
result = obj.to_primitive()
result['__type__'] = f"{cls.__module__}.{cls.__name__}"
if issubclass(cls, Event):
result.pop('name')
result.pop('verbose_name')
elif hasattr(obj, 'isoformat'):
result = obj.isoformat()
else:
result = super().default(obj)
return result
def object_decoder(obj):
return obj
dumps = partial(_json.dumps, cls=JSONEncoder)
loads = partial(_json.loads, object_hook=object_decoder)
|
2b1dadb57cce89f12e825dc24a2136fe27a8d0db
|
cattr/function_dispatch.py
|
cattr/function_dispatch.py
|
import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs = attr.ib(init=False, default=attr.Factory(list))
_cache = attr.ib(init=False, default=attr.Factory(dict))
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self._cache.clear()
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
try:
return self._cache[typ]
except KeyError:
self._cache[typ] = self._dispatch(typ)
return self._cache[typ]
def _dispatch(self, typ):
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
__slots__ = ('_handler_pairs', 'dispatch')
def __init__(self):
self._handler_pairs = []
self.dispatch = lru_cache(64)(self._dispatch)
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self.dispatch.cache_clear()
def _dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
Use lru_cache instead of a dict cache in FunctionDispatch
|
Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.
|
Python
|
mit
|
python-attrs/cattrs,Tinche/cattrs
|
import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs = attr.ib(init=False, default=attr.Factory(list))
_cache = attr.ib(init=False, default=attr.Factory(dict))
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self._cache.clear()
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
try:
return self._cache[typ]
except KeyError:
self._cache[typ] = self._dispatch(typ)
return self._cache[typ]
def _dispatch(self, typ):
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.
|
from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
__slots__ = ('_handler_pairs', 'dispatch')
def __init__(self):
self._handler_pairs = []
self.dispatch = lru_cache(64)(self._dispatch)
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self.dispatch.cache_clear()
def _dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
<commit_before>import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs = attr.ib(init=False, default=attr.Factory(list))
_cache = attr.ib(init=False, default=attr.Factory(dict))
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self._cache.clear()
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
try:
return self._cache[typ]
except KeyError:
self._cache[typ] = self._dispatch(typ)
return self._cache[typ]
def _dispatch(self, typ):
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
<commit_msg>Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.<commit_after>
|
from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
__slots__ = ('_handler_pairs', 'dispatch')
def __init__(self):
self._handler_pairs = []
self.dispatch = lru_cache(64)(self._dispatch)
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self.dispatch.cache_clear()
def _dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs = attr.ib(init=False, default=attr.Factory(list))
_cache = attr.ib(init=False, default=attr.Factory(dict))
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self._cache.clear()
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
try:
return self._cache[typ]
except KeyError:
self._cache[typ] = self._dispatch(typ)
return self._cache[typ]
def _dispatch(self, typ):
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
__slots__ = ('_handler_pairs', 'dispatch')
def __init__(self):
self._handler_pairs = []
self.dispatch = lru_cache(64)(self._dispatch)
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self.dispatch.cache_clear()
def _dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
<commit_before>import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
_handler_pairs = attr.ib(init=False, default=attr.Factory(list))
_cache = attr.ib(init=False, default=attr.Factory(dict))
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self._cache.clear()
def dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
try:
return self._cache[typ]
except KeyError:
self._cache[typ] = self._dispatch(typ)
return self._cache[typ]
def _dispatch(self, typ):
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
<commit_msg>Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.<commit_after>from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
"""
__slots__ = ('_handler_pairs', 'dispatch')
def __init__(self):
self._handler_pairs = []
self.dispatch = lru_cache(64)(self._dispatch)
def register(self, can_handle, func):
self._handler_pairs.insert(0, (can_handle, func))
self.dispatch.cache_clear()
def _dispatch(self, typ):
"""
returns the appropriate handler, for the object passed.
"""
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(typ))
|
99360f7b128c2691763c283406f3758db69d8bca
|
serrano/formatters.py
|
serrano/formatters.py
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
Add `delimiter` and `html_map` to HTML formatter and do not register it by default
|
Add `delimiter` and `html_map` to HTML formatter and do not register it by default
|
Python
|
bsd-2-clause
|
rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
Add `delimiter` and `html_map` to HTML formatter and do not register it by default
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
<commit_before>from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
<commit_msg>Add `delimiter` and `html_map` to HTML formatter and do not register it by default<commit_after>
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
Add `delimiter` and `html_map` to HTML formatter and do not register it by defaultfrom django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
<commit_before>from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return u' '.join(toks)
to_html.process_multiple = True
registry.register(HTMLFormatter, 'HTML')
<commit_msg>Add `delimiter` and `html_map` to HTML formatter and do not register it by default<commit_after>from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Check the html_map first
if value in self.html_map:
tok = self.html_map[value]
# Ignore NoneTypes
elif value is None:
continue
# Prettify floats
elif type(value) is float:
tok = filters.floatformat(value)
else:
tok = unicode(value)
toks.append(tok)
return self.delimiter.join(toks)
to_html.process_multiple = True
|
561060423d0979e51b92a7209482e76680734d51
|
dallinger/dev_server/app.py
|
dallinger/dev_server/app.py
|
import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
Apply gevent patch earlier based on output of `flask run`
|
Apply gevent patch earlier based on output of `flask run`
|
Python
|
mit
|
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger
|
import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
Apply gevent patch earlier based on output of `flask run`
|
import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
<commit_before>import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
<commit_msg>Apply gevent patch earlier based on output of `flask run`<commit_after>
|
import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
Apply gevent patch earlier based on output of `flask run`import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
<commit_before>import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
<commit_msg>Apply gevent patch earlier based on output of `flask run`<commit_after>import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
|
4dca51fe6cd976c0312156ab32f787cecbb765a2
|
task_router/tests/test_views.py
|
task_router/tests/test_views.py
|
from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
|
from xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
@skip("WIP")
def test_incoming_call(self):
# Act
response = self.client.get('/')
root = self.assertXmlDocument(response.data)
say = root.xpath('./Gather/say()')
# <Response>
# <Gather action="/call/enqueue" numDigits="1" timeout="5">
# <Say>For ACME Rockets, press one.&</Say>
# <Say>For ACME TNT, press two.</Say>
# </Gather>
# </Response>
self.assertEquals(2, len(sat), response.data)
self.assertEquals('For ACME Rockets, press one.', say[0])
self.assertEquals('For ACME TNT, press two.', say[1])
|
Add test for test incoming call
|
Add test for test incoming call
|
Python
|
mit
|
TwilioDevEd/task-router-django,TwilioDevEd/task-router-django,TwilioDevEd/task-router-django
|
from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
Add test for test incoming call
|
from xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
@skip("WIP")
def test_incoming_call(self):
# Act
response = self.client.get('/')
root = self.assertXmlDocument(response.data)
say = root.xpath('./Gather/say()')
# <Response>
# <Gather action="/call/enqueue" numDigits="1" timeout="5">
# <Say>For ACME Rockets, press one.&</Say>
# <Say>For ACME TNT, press two.</Say>
# </Gather>
# </Response>
self.assertEquals(2, len(sat), response.data)
self.assertEquals('For ACME Rockets, press one.', say[0])
self.assertEquals('For ACME TNT, press two.', say[1])
|
<commit_before>from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
<commit_msg>Add test for test incoming call<commit_after>
|
from xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
@skip("WIP")
def test_incoming_call(self):
# Act
response = self.client.get('/')
root = self.assertXmlDocument(response.data)
say = root.xpath('./Gather/say()')
# <Response>
# <Gather action="/call/enqueue" numDigits="1" timeout="5">
# <Say>For ACME Rockets, press one.&</Say>
# <Say>For ACME TNT, press two.</Say>
# </Gather>
# </Response>
self.assertEquals(2, len(sat), response.data)
self.assertEquals('For ACME Rockets, press one.', say[0])
self.assertEquals('For ACME TNT, press two.', say[1])
|
from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
Add test for test incoming callfrom xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
@skip("WIP")
def test_incoming_call(self):
# Act
response = self.client.get('/')
root = self.assertXmlDocument(response.data)
say = root.xpath('./Gather/say()')
# <Response>
# <Gather action="/call/enqueue" numDigits="1" timeout="5">
# <Say>For ACME Rockets, press one.&</Say>
# <Say>For ACME TNT, press two.</Say>
# </Gather>
# </Response>
self.assertEquals(2, len(sat), response.data)
self.assertEquals('For ACME Rockets, press one.', say[0])
self.assertEquals('For ACME TNT, press two.', say[1])
|
<commit_before>from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
<commit_msg>Add test for test incoming call<commit_after>from xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests to make sure it works. We'll check for a bit of copy, though
self.assertIn('Task Router', str(response.content))
@skip("WIP")
def test_incoming_call(self):
# Act
response = self.client.get('/')
root = self.assertXmlDocument(response.data)
say = root.xpath('./Gather/say()')
# <Response>
# <Gather action="/call/enqueue" numDigits="1" timeout="5">
# <Say>For ACME Rockets, press one.&</Say>
# <Say>For ACME TNT, press two.</Say>
# </Gather>
# </Response>
self.assertEquals(2, len(sat), response.data)
self.assertEquals('For ACME Rockets, press one.', say[0])
self.assertEquals('For ACME TNT, press two.', say[1])
|
67b681697ebd3c1ea1ebda335c098e628da60b58
|
cinder/tests/test_test_utils.py
|
cinder/tests/test_test_utils.py
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
# TODO(soren): This should verify the full interface context
# objects expose.
self.assertTrue(ctxt.is_admin)
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
self.assertIsNone(ctxt.project_id)
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.domain)
self.assertIsNone(ctxt.project_domain)
self.assertIsNone(ctxt.user_domain)
self.assertIsNone(ctxt.project_name)
self.assertIsNone(ctxt.remote_address)
self.assertIsNone(ctxt.auth_token)
self.assertIsNone(ctxt.quota_class)
self.assertIsNotNone(ctxt.request_id)
self.assertIsNotNone(ctxt.timestamp)
self.assertEqual(['admin'], ctxt.roles)
self.assertEqual([], ctxt.service_catalog)
self.assertEqual('no', ctxt.read_deleted)
self.assertTrue(ctxt.read_deleted)
self.assertTrue(ctxt.is_admin)
|
Verify the full interface of the context object
|
Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267
|
Python
|
apache-2.0
|
Nexenta/cinder,nikesh-mahalka/cinder,eharney/cinder,NetApp/cinder,abusse/cinder,CloudServer/cinder,saeki-masaki/cinder,phenoxim/cinder,Accelerite/cinder,dims/cinder,takeshineshiro/cinder,NetApp/cinder,manojhirway/ExistingImagesOnNFS,Akrog/cinder,Hybrid-Cloud/cinder,scottdangelo/RemoveVolumeMangerLocks,mahak/cinder,manojhirway/ExistingImagesOnNFS,eharney/cinder,Paul-Ezell/cinder-1,openstack/cinder,mahak/cinder,saeki-masaki/cinder,tlakshman26/cinder-new-branch,Nexenta/cinder,bswartz/cinder,julianwang/cinder,nexusriot/cinder,petrutlucian94/cinder,leilihh/cinder,potsmaster/cinder,j-griffith/cinder,winndows/cinder,bswartz/cinder,Akrog/cinder,tlakshman26/cinder-bug-fix-volume-conversion-full,dims/cinder,phenoxim/cinder,apporc/cinder,ge0rgi/cinder,CloudServer/cinder,leilihh/cinder,tlakshman26/cinder-new-branch,openstack/cinder,JioCloud/cinder,potsmaster/cinder,sasukeh/cinder,j-griffith/cinder,tlakshman26/cinder-https-changes,winndows/cinder,julianwang/cinder,hguemar/cinder,cloudbase/cinder,Accelerite/cinder,Datera/cinder,scality/cinder,duhzecca/cinder,cloudbase/cinder,takeshineshiro/cinder,hguemar/cinder,sasukeh/cinder,Datera/cinder,abusse/cinder,blueboxgroup/cinder,rakeshmi/cinder,duhzecca/cinder,scottdangelo/RemoveVolumeMangerLocks,scality/cinder,Hybrid-Cloud/cinder,nikesh-mahalka/cinder,nexusriot/cinder,tlakshman26/cinder-bug-fix-volume-conversion-full,petrutlucian94/cinder,blueboxgroup/cinder,apporc/cinder,tlakshman26/cinder-https-changes,rakeshmi/cinder,JioCloud/cinder,Paul-Ezell/cinder-1
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
# TODO(soren): This should verify the full interface context
# objects expose.
self.assertTrue(ctxt.is_admin)
Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
self.assertIsNone(ctxt.project_id)
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.domain)
self.assertIsNone(ctxt.project_domain)
self.assertIsNone(ctxt.user_domain)
self.assertIsNone(ctxt.project_name)
self.assertIsNone(ctxt.remote_address)
self.assertIsNone(ctxt.auth_token)
self.assertIsNone(ctxt.quota_class)
self.assertIsNotNone(ctxt.request_id)
self.assertIsNotNone(ctxt.timestamp)
self.assertEqual(['admin'], ctxt.roles)
self.assertEqual([], ctxt.service_catalog)
self.assertEqual('no', ctxt.read_deleted)
self.assertTrue(ctxt.read_deleted)
self.assertTrue(ctxt.is_admin)
|
<commit_before>#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
# TODO(soren): This should verify the full interface context
# objects expose.
self.assertTrue(ctxt.is_admin)
<commit_msg>Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267<commit_after>
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
self.assertIsNone(ctxt.project_id)
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.domain)
self.assertIsNone(ctxt.project_domain)
self.assertIsNone(ctxt.user_domain)
self.assertIsNone(ctxt.project_name)
self.assertIsNone(ctxt.remote_address)
self.assertIsNone(ctxt.auth_token)
self.assertIsNone(ctxt.quota_class)
self.assertIsNotNone(ctxt.request_id)
self.assertIsNotNone(ctxt.timestamp)
self.assertEqual(['admin'], ctxt.roles)
self.assertEqual([], ctxt.service_catalog)
self.assertEqual('no', ctxt.read_deleted)
self.assertTrue(ctxt.read_deleted)
self.assertTrue(ctxt.is_admin)
|
#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
# TODO(soren): This should verify the full interface context
# objects expose.
self.assertTrue(ctxt.is_admin)
Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
self.assertIsNone(ctxt.project_id)
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.domain)
self.assertIsNone(ctxt.project_domain)
self.assertIsNone(ctxt.user_domain)
self.assertIsNone(ctxt.project_name)
self.assertIsNone(ctxt.remote_address)
self.assertIsNone(ctxt.auth_token)
self.assertIsNone(ctxt.quota_class)
self.assertIsNotNone(ctxt.request_id)
self.assertIsNotNone(ctxt.timestamp)
self.assertEqual(['admin'], ctxt.roles)
self.assertEqual([], ctxt.service_catalog)
self.assertEqual('no', ctxt.read_deleted)
self.assertTrue(ctxt.read_deleted)
self.assertTrue(ctxt.is_admin)
|
<commit_before>#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
# TODO(soren): This should verify the full interface context
# objects expose.
self.assertTrue(ctxt.is_admin)
<commit_msg>Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267<commit_after>#
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import test
from cinder.tests import utils as test_utils
class TestUtilsTestCase(test.TestCase):
def test_get_test_admin_context(self):
"""get_test_admin_context's return value behaves like admin context."""
ctxt = test_utils.get_test_admin_context()
self.assertIsNone(ctxt.project_id)
self.assertIsNone(ctxt.user_id)
self.assertIsNone(ctxt.domain)
self.assertIsNone(ctxt.project_domain)
self.assertIsNone(ctxt.user_domain)
self.assertIsNone(ctxt.project_name)
self.assertIsNone(ctxt.remote_address)
self.assertIsNone(ctxt.auth_token)
self.assertIsNone(ctxt.quota_class)
self.assertIsNotNone(ctxt.request_id)
self.assertIsNotNone(ctxt.timestamp)
self.assertEqual(['admin'], ctxt.roles)
self.assertEqual([], ctxt.service_catalog)
self.assertEqual('no', ctxt.read_deleted)
self.assertTrue(ctxt.read_deleted)
self.assertTrue(ctxt.is_admin)
|
6fb0db3cd83bc91f683fd31f0b25f59473970790
|
package_name/__meta__.py
|
package_name/__meta__.py
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.dev0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
Make default version number be a dev version
|
MAINT: Make default version number be a dev version
|
Python
|
mit
|
scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
MAINT: Make default version number be a dev version
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.dev0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
<commit_before>name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
<commit_msg>MAINT: Make default version number be a dev version<commit_after>
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.dev0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
MAINT: Make default version number be a dev versionname = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.dev0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
<commit_before>name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
<commit_msg>MAINT: Make default version number be a dev version<commit_after>name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.dev0' # https://python.org/dev/peps/pep-0440 https://semver.org
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepage
license = 'MIT' # See https://choosealicense.com
|
05acf13b46a3515d5a1362515984b42115b01ca3
|
clone_everything/github.py
|
clone_everything/github.py
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
req = requests.get(url)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
headers = {'User-Agent': 'https://github.com/tomleese/clone-everything'}
req = requests.get(url, headers=headers)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
Add user agent to GitHub cloning
|
Add user agent to GitHub cloning
|
Python
|
mit
|
tomleese/clone-everything,thomasleese/clone-everything
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
req = requests.get(url)
for repo in req.json():
yield repo['name'], repo['ssh_url']
Add user agent to GitHub cloning
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
headers = {'User-Agent': 'https://github.com/tomleese/clone-everything'}
req = requests.get(url, headers=headers)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
<commit_before>import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
req = requests.get(url)
for repo in req.json():
yield repo['name'], repo['ssh_url']
<commit_msg>Add user agent to GitHub cloning<commit_after>
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
headers = {'User-Agent': 'https://github.com/tomleese/clone-everything'}
req = requests.get(url, headers=headers)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
req = requests.get(url)
for repo in req.json():
yield repo['name'], repo['ssh_url']
Add user agent to GitHub cloningimport re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
headers = {'User-Agent': 'https://github.com/tomleese/clone-everything'}
req = requests.get(url, headers=headers)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
<commit_before>import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
req = requests.get(url)
for repo in req.json():
yield repo['name'], repo['ssh_url']
<commit_msg>Add user agent to GitHub cloning<commit_after>import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
if match is None:
raise ValueError('Not a GitHub URL.')
account = match.group('account')
url = 'https://api.github.com/users/{0}/repos'.format(account)
headers = {'User-Agent': 'https://github.com/tomleese/clone-everything'}
req = requests.get(url, headers=headers)
for repo in req.json():
yield repo['name'], repo['ssh_url']
|
6aee57bbad3d443e0ff7117a04c4587561795632
|
tests/query_test/test_decimal_queries.py
|
tests/query_test/test_decimal_queries.py
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
Update decimal tests to only run on text/none.
|
Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
|
Python
|
apache-2.0
|
gerashegalov/Impala,cgvarela/Impala,placrosse/ImpalaToGo,caseyching/Impala,ImpalaToGo/ImpalaToGo,placrosse/ImpalaToGo,bratatidas9/Impala-1,ImpalaToGo/ImpalaToGo,kapilrastogi/Impala,bratatidas9/Impala-1,placrosse/ImpalaToGo,caseyching/Impala,ibmsoe/ImpalaPPC,kapilrastogi/Impala,XiaominZhang/Impala,lnliuxing/Impala,XiaominZhang/Impala,kapilrastogi/Impala,bratatidas9/Impala-1,kapilrastogi/Impala,gerashegalov/Impala,ImpalaToGo/ImpalaToGo,XiaominZhang/Impala,caseyching/Impala,placrosse/ImpalaToGo,XiaominZhang/Impala,bratatidas9/Impala-1,ImpalaToGo/ImpalaToGo,tempbottle/Impala,kapilrastogi/Impala,scalingdata/Impala,gerashegalov/Impala,rdblue/Impala,lirui-intel/Impala,grundprinzip/Impala,cgvarela/Impala,kapilrastogi/Impala,cloudera/recordservice,tempbottle/Impala,cchanning/Impala,lirui-intel/Impala,cchanning/Impala,scalingdata/Impala,gerashegalov/Impala,gerashegalov/Impala,lirui-intel/Impala,grundprinzip/Impala,rdblue/Impala,mapr/impala,placrosse/ImpalaToGo,theyaa/Impala,bratatidas9/Impala-1,grundprinzip/Impala,brightchen/Impala,scalingdata/Impala,cchanning/Impala,lnliuxing/Impala,caseyching/Impala,ibmsoe/ImpalaPPC,cchanning/Impala,tempbottle/Impala,cloudera/recordservice,cgvarela/Impala,XiaominZhang/Impala,bowlofstew/Impala,ImpalaToGo/ImpalaToGo,henryr/Impala,ibmsoe/ImpalaPPC,lnliuxing/Impala,gerashegalov/Impala,henryr/Impala,brightchen/Impala,ibmsoe/ImpalaPPC,caseyching/Impala,lirui-intel/Impala,mapr/impala,brightchen/Impala,henryr/Impala,tempbottle/Impala,ibmsoe/ImpalaPPC,tempbottle/Impala,brightchen/Impala,cchanning/Impala,bratatidas9/Impala-1,grundprinzip/Impala,theyaa/Impala,cgvarela/Impala,scalingdata/Impala,brightchen/Impala,rdblue/Impala,cloudera/recordservice,cloudera/recordservice,lirui-intel/Impala,bowlofstew/Impala,rdblue/Impala,mapr/impala,scalingdata/Impala,bowlofstew/Impala,cloudera/recordservice,caseyching/Impala,cloudera/recordservice,lirui-intel/Impala,bowlofstew/Impala,mapr/impala,rdblue/Impala,cgvarela/Impala,bowlofstew/Impala,mapr/impala,ibmsoe/ImpalaPPC,henryr/Impala,cloudera/recordservice,tempbottle/Impala,theyaa/Impala,brightchen/Impala,lnliuxing/Impala,caseyching/Impala,theyaa/Impala,theyaa/Impala,ibmsoe/ImpalaPPC,lnliuxing/Impala,bowlofstew/Impala,theyaa/Impala,tempbottle/Impala,brightchen/Impala,cgvarela/Impala,scalingdata/Impala,rdblue/Impala,theyaa/Impala,XiaominZhang/Impala,XiaominZhang/Impala,grundprinzip/Impala,grundprinzip/Impala,kapilrastogi/Impala,cchanning/Impala,lnliuxing/Impala,ImpalaToGo/ImpalaToGo,bowlofstew/Impala,cgvarela/Impala,henryr/Impala,lirui-intel/Impala,cchanning/Impala,bratatidas9/Impala-1,rdblue/Impala,lnliuxing/Impala,henryr/Impala,gerashegalov/Impala,placrosse/ImpalaToGo
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
<commit_msg>Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com><commit_after>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
<commit_msg>Update decimal tests to only run on text/none.
Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217
Tested-by: jenkins
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com><commit_after>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestDecimalQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES))
# TODO: add parquet when that is supported.
# On CDH4, hive does not support decimal so we can't run these tests against
# the other file formats. Enable them on C5.
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_queries(self, vector):
new_vector = copy(vector)
new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size')
self.run_test_case('QueryTest/decimal', new_vector)
|
65731fff94cd18a0d196c463b5e2aee444027d77
|
salt/utils/pycrypto.py
|
salt/utils/pycrypto.py
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'}
if algorithm not in hash_algorithms:
raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm))
if password is None:
password = secure_password()
if salt is None:
salt = secure_password(8)
salt = hash_algorithms[algorithm] + salt
return crypt.crypt(password, salt)
|
Add algorithm argument to get_hash
|
Add algorithm argument to get_hash
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
Add algorithm argument to get_hash
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'}
if algorithm not in hash_algorithms:
raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm))
if password is None:
password = secure_password()
if salt is None:
salt = secure_password(8)
salt = hash_algorithms[algorithm] + salt
return crypt.crypt(password, salt)
|
<commit_before>
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
<commit_msg>Add algorithm argument to get_hash<commit_after>
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'}
if algorithm not in hash_algorithms:
raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm))
if password is None:
password = secure_password()
if salt is None:
salt = secure_password(8)
salt = hash_algorithms[algorithm] + salt
return crypt.crypt(password, salt)
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
Add algorithm argument to get_hash
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'}
if algorithm not in hash_algorithms:
raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm))
if password is None:
password = secure_password()
if salt is None:
salt = secure_password(8)
salt = hash_algorithms[algorithm] + salt
return crypt.crypt(password, salt)
|
<commit_before>
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
<commit_msg>Add algorithm argument to get_hash<commit_after>
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
'''
Generate a secure password.
'''
if not HAS_RANDOM:
raise ImportError('generating passwords requires >= pycrypto v2.1.0')
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
hash_algorithms = {'md5':'$1$', 'blowfish':'$2a$', 'sha256':'$5$', 'sha512':'$6$'}
if algorithm not in hash_algorithms:
raise salt.exceptions.SaltInvocationError('Not support {0} algorithm'.format(algorithm))
if password is None:
password = secure_password()
if salt is None:
salt = secure_password(8)
salt = hash_algorithms[algorithm] + salt
return crypt.crypt(password, salt)
|
6c12f97bfed8b8a4749f75e1a508caf0ea310423
|
docker/update-production.py
|
docker/update-production.py
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
Make sure to update correct load balancer
|
Make sure to update correct load balancer
|
Python
|
mit
|
muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
Make sure to update correct load balancer
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
<commit_before>#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
<commit_msg>Make sure to update correct load balancer<commit_after>
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
Make sure to update correct load balancer#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
<commit_before>#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
<commit_msg>Make sure to update correct load balancer<commit_after>#!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode(
'utf-8')
data = json.loads(output)
linked_service = data['linked_to_service'][0]['name']
info('Currently linked service is \'{}\''.format(linked_service))
if linked_service == 'muzhack-green':
link_to = 'muzhack-blue'
else:
assert linked_service == 'muzhack-blue'
link_to = 'muzhack-green'
info('Redeploying service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE)
info('Linking to service \'{}\'...'.format(link_to))
subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to),
'--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE)
info('Successfully switched production service to {}'.format(link_to))
|
87c32abc97bc6a2a1cfc41eb9557d721619a33b5
|
django_auth_kerberos/backends.py
|
django_auth_kerberos/backends.py
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if self.check_password(user, password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def check_password(self, user, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username, password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
Create unknown users, when authenticated successfully
|
Create unknown users, when authenticated successfully
|
Python
|
mit
|
mkesper/django-auth-kerberos,02strich/django-auth-kerberos
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if self.check_password(user, password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def check_password(self, user, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username, password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
Create unknown users, when authenticated successfully
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
<commit_before>import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if self.check_password(user, password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def check_password(self, user, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username, password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
<commit_msg>Create unknown users, when authenticated successfully<commit_after>
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if self.check_password(user, password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def check_password(self, user, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username, password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
Create unknown users, when authenticated successfullyimport kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
<commit_before>import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if self.check_password(user, password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def check_password(self, user, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username, password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
<commit_msg>Create unknown users, when authenticated successfully<commit_after>import kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Django Authentication backend using Kerberos for password checking.
"""
def authenticate(self, username=None, password=None):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if not self.check_password(username, password):
return None
UserModel = get_user_model()
user, created = UserModel.objects.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
return user
def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
kerberos.checkPassword(username.lower(), password, settings.KRB5_SERVICE, settings.KRB5_REALM)
return True
except kerberos.BasicAuthError:
if getattr(settings, "KRB5_DEBUG", False):
logger.exception("Failure during authentication")
return False
|
98581828a9e82ff7ebae6abdb4f2c497f22441d1
|
trex/urls.py
|
trex/urls.py
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$",
project.ProjectEntriesListAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^api/1/entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
Use api/1/ as url prefix for all REST interfaces
|
Use api/1/ as url prefix for all REST interfaces
This allows separating the "normal" web code from the rest api.
|
Python
|
mit
|
bjoernricks/trex,bjoernricks/trex
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
Use api/1/ as url prefix for all REST interfaces
This allows separating the "normal" web code from the rest api.
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$",
project.ProjectEntriesListAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^api/1/entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
<commit_before># -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
<commit_msg>Use api/1/ as url prefix for all REST interfaces
This allows separating the "normal" web code from the rest api.<commit_after>
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$",
project.ProjectEntriesListAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^api/1/entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
Use api/1/ as url prefix for all REST interfaces
This allows separating the "normal" web code from the rest api.# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$",
project.ProjectEntriesListAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^api/1/entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
<commit_before># -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
<commit_msg>Use api/1/ as url prefix for all REST interfaces
This allows separating the "normal" web code from the rest api.<commit_after># -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
project.ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$",
project.ProjectEntriesListAPIView.as_view(),
name="project-detail"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$",
project.ProjectZeiterfassungAPIView.as_view(),
name="project-zeiterfassung"),
url(r"^api/1/entries/(?P<pk>[0-9]+)/$",
project.EntryDetailAPIView.as_view(),
name="entry-detail"),
)
|
2dba75be67e07a98fb2b7093e0d0d2771fd7146f
|
satchmo/apps/payment/modules/giftcertificate/processor.py
|
satchmo/apps/payment/modules/giftcertificate/processor.py
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
Fix the gift certificate module so that an invalid code won't throw an exception.
|
Fix the gift certificate module so that an invalid code won't throw an exception.
|
Python
|
bsd-3-clause
|
grengojbo/satchmo,grengojbo/satchmo
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
Fix the gift certificate module so that an invalid code won't throw an exception.
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
<commit_before>"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
<commit_msg>Fix the gift certificate module so that an invalid code won't throw an exception.<commit_after>
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
Fix the gift certificate module so that an invalid code won't throw an exception."""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
<commit_before>"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
<commit_msg>Fix the gift certificate module so that an invalid code won't throw an exception.<commit_after>"""
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
5f40ac5ef2b42052bdc7c3cfcf662ca4614032ca
|
scripts/get_python_lib.py
|
scripts/get_python_lib.py
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
#
# However, using this would not respect a python virtual environments, so in a way this is better!
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
Add note about virtualenv support
|
Add note about virtualenv support
|
Python
|
agpl-3.0
|
rTreutlein/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])Add note about virtualenv support
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
#
# However, using this would not respect a python virtual environments, so in a way this is better!
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
<commit_before>import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])<commit_msg>Add note about virtualenv support<commit_after>
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
#
# However, using this would not respect a python virtual environments, so in a way this is better!
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])Add note about virtualenv supportimport sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
#
# However, using this would not respect a python virtual environments, so in a way this is better!
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
<commit_before>import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])<commit_msg>Add note about virtualenv support<commit_after>import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix))
#
# However, using this would not respect a python virtual environments, so in a way this is better!
prefix = sys.argv[1]
# use sites if the prefix is recognized and the sites module is available
# (virtualenv is missing getsitepackages())
if hasattr(site, 'getsitepackages'):
paths = [p for p in site.getsitepackages() if p.startswith(prefix)]
if len(paths) == 1:
print(paths[0])
exit(0)
# use sysconfig platlib as the fall back
print(sysconfig.get_paths()['platlib'])
|
46cec51fa3b81da21662da5d36ccaf1f409caaea
|
gem/personalise/templatetags/personalise_extras.py
|
gem/personalise/templatetags/personalise_extras.py
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
|
Fix error when displaying other types of surveys
|
Fix error when displaying other types of surveys
|
Python
|
bsd-2-clause
|
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
Fix error when displaying other types of surveys
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
|
<commit_before>from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
<commit_msg>Fix error when displaying other types of surveys<commit_after>
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
|
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
Fix error when displaying other types of surveysfrom django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
|
<commit_before>from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
<commit_msg>Fix error when displaying other types of surveys<commit_after>from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
|
780dc99953060113f793c1a0da7058efe8f194fc
|
kokki/cookbooks/aws/recipes/default.py
|
kokki/cookbooks/aws/recipes/default.py
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
Revert that last change.. and do a proper fix
|
Revert that last change.. and do a proper fix
|
Python
|
bsd-3-clause
|
samuel/kokki
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
Revert that last change.. and do a proper fix
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
<commit_before>
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
<commit_msg>Revert that last change.. and do a proper fix<commit_after>
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
Revert that last change.. and do a proper fix
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
<commit_before>
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
<commit_msg>Revert that last change.. and do a proper fix<commit_after>
import os
from kokki import *
env.include_recipe("boto")
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol.get('name') or vol['volume_id'],
volume_id = vol.get('volume_id'),
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach" if vol.get('volume_id') else ["create", "attach"])
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
ee629fca605b27ee6f34c8fa7584f670ae60b121
|
whylog/constraints/constraint_manager.py
|
whylog/constraints/constraint_manager.py
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
@classmethod
def constraint_from_name(cls, constraint_name):
return cls.CONSTRAINTS.get(constraint_name)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
Add constraint from name method
|
Add constraint from name method
|
Python
|
bsd-3-clause
|
epawlowska/whylog,kgromadzki/whylog,kgromadzki/whylog,konefalg/whylog,9livesdata/whylog,konefalg/whylog,andrzejgorski/whylog,epawlowska/whylog,9livesdata/whylog,andrzejgorski/whylog
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
Add constraint from name method
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
@classmethod
def constraint_from_name(cls, constraint_name):
return cls.CONSTRAINTS.get(constraint_name)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
<commit_before>from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
<commit_msg>Add constraint from name method<commit_after>
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
@classmethod
def constraint_from_name(cls, constraint_name):
return cls.CONSTRAINTS.get(constraint_name)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
Add constraint from name methodfrom whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
@classmethod
def constraint_from_name(cls, constraint_name):
return cls.CONSTRAINTS.get(constraint_name)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
<commit_before>from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
<commit_msg>Add constraint from name method<commit_after>from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint
from whylog.constraints.exceptions import UnsupportedConstraintTypeError
class ConstraintRegistry(object):
CONSTRAINTS = {
'identical': IdenticalConstraint,
'time': TimeConstraint,
'different': DifferentConstraint
# register your constraint here
} # yapf: disable
@classmethod
def get_constraint(cls, constraint_data):
if constraint_data['name'] in cls.CONSTRAINTS:
return cls.CONSTRAINTS[constraint_data['name']](
param_dict=constraint_data['params'],
params_checking=False
)
raise UnsupportedConstraintTypeError(constraint_data)
@classmethod
def constraint_from_name(cls, constraint_name):
return cls.CONSTRAINTS.get(constraint_name)
class ConstraintManager(object):
"""
there should be one such object per rule being verified
"""
def __init__(self):
self._actual_constraints = {}
def __getitem__(self, constraint_data):
constraint = self._actual_constraints.get(constraint_data['name'])
if constraint is None:
constraint_verifier = ConstraintRegistry.get_constraint(constraint_data)
self._actual_constraints[constraint_data['name']] = constraint_verifier
return self._actual_constraints[constraint_data['name']]
|
6fa6090189e405e57db19b3a77f2adb46aef1242
|
create_english_superset.py
|
create_english_superset.py
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
|
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.
|
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.
|
Python
|
mit
|
brendandc/multilingual-google-image-scraper
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
|
<commit_before>import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
<commit_msg>Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.<commit_after>
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
|
import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
|
<commit_before>import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
# skip if word had no translation
if foreign_word != word:
all_english_words.add(word)
with open(full_path+'\\english.superset', 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(all_english_words))
<commit_msg>Refactor create english superset code to create english superset dictionaries in batches of 10K. Also re-include untranslated words.<commit_after>import optparse
import os
optparser = optparse.OptionParser()
optparser.add_option("-d", "--directory", dest="directory", default="dictionaries/", help="Directory with dictionaries")
(opts, _) = optparser.parse_args()
full_path = os.path.abspath(opts.directory)
all_english_words = set()
for filename in os.listdir(full_path):
if filename.startswith('dict'):
for line in open(full_path+'\\'+filename, encoding='utf-8'):
translations = line.strip().split('\t')
foreign_word = translations[0]
# skip the first word because it is the foreign word
for word in translations[1:]:
all_english_words.add(word)
all_english_words_list = list(all_english_words)
words_per_batch = 10000
words_by_batch = [all_english_words_list[i:i+words_per_batch] for i in range(0, len(all_english_words_list), words_per_batch)]
for i, word_batch in enumerate(words_by_batch):
with open(full_path+'\\english.superset'+"{0:0=2d}".format(i+1), 'w', encoding='utf-8') as text_file:
text_file.write("\n".join(word_batch))
|
421dbe962dae44cad7aa734a397cb16fe9b1632f
|
reactive/datanode.py
|
reactive/datanode.py
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
Update charms.hadoop reference to follow convention
|
Update charms.hadoop reference to follow convention
|
Python
|
apache-2.0
|
johnsca/layer-apache-hadoop-datanode,juju-solutions/layer-apache-hadoop-datanode
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
Update charms.hadoop reference to follow convention
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
<commit_before>from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
<commit_msg>Update charms.hadoop reference to follow convention<commit_after>
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
Update charms.hadoop reference to follow conventionfrom charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
<commit_before>from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
<commit_msg>Update charms.hadoop reference to follow convention<commit_after>from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import HDFS
from jujubigdata import utils
@when('namenode.ready')
@when_not('datanode.started')
def start_datanode(namenode):
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.configure_datanode(namenode.namenodes()[0], namenode.port())
utils.install_ssh_key('hdfs', namenode.ssh_key())
utils.update_kv_hosts(namenode.hosts_map())
utils.manage_etc_hosts()
hdfs.start_datanode()
hadoop.open_ports('datanode')
set_state('datanode.started')
@when('datanode.started')
@when_not('namenode.ready')
def stop_datanode():
hadoop = get_hadoop_base()
hdfs = HDFS(hadoop)
hdfs.stop_datanode()
hadoop.close_ports('datanode')
remove_state('datanode.started')
|
5b0246f1c287fc7eba8cfcd37144fdbe5487354a
|
tests/test_mplleaflet.py
|
tests/test_mplleaflet.py
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 0], [1, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 1], [0, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
Fix the basic test to make a line
|
Fix the basic test to make a line
|
Python
|
bsd-3-clause
|
BibMartin/mplleaflet,ocefpaf/mplleaflet,zeapo/mplleaflet,jwass/mplleaflet,zeapo/mplleaflet,ocefpaf/mplleaflet,BibMartin/mplleaflet,jwass/mplleaflet
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 0], [1, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
Fix the basic test to make a line
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 1], [0, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
<commit_before>import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 0], [1, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
<commit_msg>Fix the basic test to make a line<commit_after>
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 1], [0, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 0], [1, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
Fix the basic test to make a lineimport matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 1], [0, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
<commit_before>import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 0], [1, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
<commit_msg>Fix the basic test to make a line<commit_after>import matplotlib.pyplot as plt
import mplleaflet
def test_basic():
plt.plot([0, 1], [0, 1])
mplleaflet.fig_to_html()
def test_scatter():
plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.fig_to_html()
|
b7b691d82accc012ee4308849a82ba8514e4a156
|
migrations/versions/20140430220209_4093ccb6d914.py
|
migrations/versions/20140430220209_4093ccb6d914.py
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.Text(), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.types.VARCHAR(length=255), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
Allow MySQL to set a default role
|
Allow MySQL to set a default role
|
Python
|
mit
|
taeram/ineffable,taeram/ineffable,taeram/ineffable
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.Text(), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
Allow MySQL to set a default role
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.types.VARCHAR(length=255), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
<commit_before>"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.Text(), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
<commit_msg>Allow MySQL to set a default role<commit_after>
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.types.VARCHAR(length=255), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.Text(), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
Allow MySQL to set a default role"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.types.VARCHAR(length=255), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
<commit_before>"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.Text(), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
<commit_msg>Allow MySQL to set a default role<commit_after>"""empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('share_code', sa.Text(), nullable=False),
sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow),
sa.Column('created', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('folder')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.types.VARCHAR(length=255), nullable=False),
sa.Column('password', sa.Text(), nullable=False),
sa.Column('role', sa.types.VARCHAR(length=255), nullable=False, server_default="user"),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
def downgrade():
op.drop_table('user')
op.drop_table('gallery')
|
06659d9d92b7f2b51db5905555293d23905cf7a4
|
sinon/lib/SinonSandbox.py
|
sinon/lib/SinonSandbox.py
|
properties = ["SinonSpy", "SinonStub", "SinonMock"]
production_properties = ["spy", "stub", "mock"]
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
properties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"]
production_properties = ["spy", "stub", "mock", "assert"]
def _clear_assertion_message(obj):
setattr(obj, "message", "")
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
if prop == "assert":
_clear_assertion_message(getattr(f.__globals__["sinon"], prop))
else:
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
if prop == "SinonAssertion":
_clear_assertion_message(f.__globals__[prop])
else:
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
Reset message into empty string of sinonAssertion
|
Reset message into empty string of sinonAssertion
|
Python
|
bsd-2-clause
|
note35/sinon,note35/sinon
|
properties = ["SinonSpy", "SinonStub", "SinonMock"]
production_properties = ["spy", "stub", "mock"]
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
Reset message into empty string of sinonAssertion
|
properties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"]
production_properties = ["spy", "stub", "mock", "assert"]
def _clear_assertion_message(obj):
setattr(obj, "message", "")
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
if prop == "assert":
_clear_assertion_message(getattr(f.__globals__["sinon"], prop))
else:
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
if prop == "SinonAssertion":
_clear_assertion_message(f.__globals__[prop])
else:
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
<commit_before>properties = ["SinonSpy", "SinonStub", "SinonMock"]
production_properties = ["spy", "stub", "mock"]
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
<commit_msg>Reset message into empty string of sinonAssertion<commit_after>
|
properties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"]
production_properties = ["spy", "stub", "mock", "assert"]
def _clear_assertion_message(obj):
setattr(obj, "message", "")
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
if prop == "assert":
_clear_assertion_message(getattr(f.__globals__["sinon"], prop))
else:
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
if prop == "SinonAssertion":
_clear_assertion_message(f.__globals__[prop])
else:
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
properties = ["SinonSpy", "SinonStub", "SinonMock"]
production_properties = ["spy", "stub", "mock"]
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
Reset message into empty string of sinonAssertionproperties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"]
production_properties = ["spy", "stub", "mock", "assert"]
def _clear_assertion_message(obj):
setattr(obj, "message", "")
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
if prop == "assert":
_clear_assertion_message(getattr(f.__globals__["sinon"], prop))
else:
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
if prop == "SinonAssertion":
_clear_assertion_message(f.__globals__[prop])
else:
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
<commit_before>properties = ["SinonSpy", "SinonStub", "SinonMock"]
production_properties = ["spy", "stub", "mock"]
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
<commit_msg>Reset message into empty string of sinonAssertion<commit_after>properties = ["SinonSpy", "SinonStub", "SinonMock", "SinonAssertion"]
production_properties = ["spy", "stub", "mock", "assert"]
def _clear_assertion_message(obj):
setattr(obj, "message", "")
def _clear_item_in_queue(queue):
for item in reversed(queue):
item.restore()
def sinontest(f):
def fn(*args, **kwargs):
ret = f(*args, **kwargs)
# handle production mode (called by sinon.py)
for prop in production_properties:
if "sinon" in f.__globals__ and prop in dir(f.__globals__["sinon"]):
if prop == "assert":
_clear_assertion_message(getattr(f.__globals__["sinon"], prop))
else:
_clear_item_in_queue(getattr(f.__globals__["sinon"], prop)._queue)
# handle unittest (direct use)
for prop in properties:
if prop in f.__globals__.keys():
if prop == "SinonAssertion":
_clear_assertion_message(f.__globals__[prop])
else:
_clear_item_in_queue(f.__globals__[prop]._queue)
return ret
return fn
class SinonSandbox(object):
def __init__(self):
pass
def create(self, config=None):
pass
def spy(self):
pass
def stub(self):
pass
def mock(self):
pass
def restore(self):
pass
|
1cb4ba75b0c4eb34606ea0eb4e30f0bd89f03518
|
bin/travis.py
|
bin/travis.py
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file: %s", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file: %s", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
Fix error logging in galaxy-cachefile-external-validator
|
Fix error logging in galaxy-cachefile-external-validator
bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py
|
Python
|
mit
|
erasche/community-package-cache,erasche/community-package-cache,galaxyproject/cargo-port,galaxyproject/cargo-port,gregvonkuster/cargo-port,gregvonkuster/cargo-port,erasche/community-package-cache,gregvonkuster/cargo-port
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
Fix error logging in galaxy-cachefile-external-validator
bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file: %s", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file: %s", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
<commit_msg>Fix error logging in galaxy-cachefile-external-validator
bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py<commit_after>
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file: %s", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file: %s", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
Fix error logging in galaxy-cachefile-external-validator
bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file: %s", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file: %s", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
<commit_msg>Fix error logging in galaxy-cachefile-external-validator
bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py<commit_after>#!/usr/bin/env python
import sys
import logging
from cargoport.utils import yield_packages, download_url, package_to_path, verify_file
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
def main():
retcode = 0
for package in yield_packages(sys.stdin):
print package
# Remove the '+' at the beginning
package['id'] = package['id'][1:]
output_package_path = package_to_path(**package) + package['ext']
err = download_url(package['url'], output_package_path)
if err is not None:
log.error("Could not download file: %s", err)
retcode = 1
else:
log.info("%s downloaded successfully", output_package_path)
err = verify_file(output_package_path, package['sha256sum'])
if err is not None:
log.error("Could not verify file: %s", err)
retcode = 1
else:
log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum'])
exit(retcode)
if __name__ == '__main__':
main()
|
35255e3c6bda4f862ed3d891b356e383eef02bda
|
dsppkeras/datasets/dspp.py
|
dsppkeras/datasets/dspp.py
|
from ..utils.data_utils import get_file
import numpy as np
import cPickle as pickle
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
database = pickle.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
from ..utils.data_utils import get_file
import json
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
#print("Load json {}".format(f))
database = json.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
Switch to JSON containing database.tar.gz
|
Switch to JSON containing database.tar.gz
|
Python
|
agpl-3.0
|
PeptoneInc/dspp-keras
|
from ..utils.data_utils import get_file
import numpy as np
import cPickle as pickle
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
database = pickle.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
Switch to JSON containing database.tar.gz
|
from ..utils.data_utils import get_file
import json
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
#print("Load json {}".format(f))
database = json.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
<commit_before>from ..utils.data_utils import get_file
import numpy as np
import cPickle as pickle
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
database = pickle.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
<commit_msg>Switch to JSON containing database.tar.gz<commit_after>
|
from ..utils.data_utils import get_file
import json
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
#print("Load json {}".format(f))
database = json.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
from ..utils.data_utils import get_file
import numpy as np
import cPickle as pickle
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
database = pickle.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
Switch to JSON containing database.tar.gzfrom ..utils.data_utils import get_file
import json
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
#print("Load json {}".format(f))
database = json.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
<commit_before>from ..utils.data_utils import get_file
import numpy as np
import cPickle as pickle
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
database = pickle.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
<commit_msg>Switch to JSON containing database.tar.gz<commit_after>from ..utils.data_utils import get_file
import json
import tarfile
def load_data(path='peptone_dspp.tar.gz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true')
tar = tarfile.open(path, "r:gz")
#print("Open archive at {}".format(path))
for member in tar.getmembers():
f = tar.extractfile(member)
if f is None: continue
#print("Load json {}".format(f))
database = json.load(f)
break
X, Y = database['X'], database['Y']
f.close()
return (X, Y)
|
47f7d42c118a00c94d99981b5b1deb34d67ff04a
|
mangacork/scripts/check_len_chapter.py
|
mangacork/scripts/check_len_chapter.py
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
|
Write name of last page in txt file
|
Write name of last page in txt file
|
Python
|
mit
|
ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
Write name of last page in txt file
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
|
<commit_before>import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
<commit_msg>Write name of last page in txt file<commit_after>
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
|
import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
Write name of last page in txt fileimport os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
|
<commit_before>import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
<commit_msg>Write name of last page in txt file<commit_after>import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
|
5a43c61c0688e2837492e7f034a0dd2c157c6e4d
|
hypatia/__init__.py
|
hypatia/__init__.py
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
__version__ = "0.2.8"
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
class Version:
"""A represntation of Hypatia's current version.
This class contains integer fields for the major, minor, and patch
version numbers, respectively. This is useful for comparison
within code if it becomes necessary to have code behave
differently based on the version, e.g. for backwards
compatibility. The class also supports str() which converts an
instance into a human-readable string, e.g. '0.2.8'.
Public Properties:
* major
* minor
* patch
"""
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.patch)
# str(__version__) will produce a string like "0.2.8"
__version__ = Version(0, 2, 8)
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
Add a class for representing the current version
|
[Feature] Add a class for representing the current version
This patch implements the `Version` class inside of the `__init__.py`
file alongside the rest of Hypatia's meta-data. The class has public
integer properties representing the major, minor, and patch portions
of the version number. This makes it possible for other code in the
engine to support or deprecate features based on the version by
comparing their numeric values, e.g.
if Version.major < 3:
# Report some error about a deprecated feature.
The `Version` class also implements `__str__()` so that it is possible
to convert `__version__` into a string, e.g. for `print()`, for the
purpose of output, e.g.
print(__version__) # "0.2.8"
Signed-off-by: Eric James Michael Ritz <3d928645612786af07f011fdfbce45f81efe5a40@plutono.com>
|
Python
|
mit
|
lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,brechin/hypatia,lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,Applemann/hypatia,Applemann/hypatia,brechin/hypatia
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
__version__ = "0.2.8"
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
[Feature] Add a class for representing the current version
This patch implements the `Version` class inside of the `__init__.py`
file alongside the rest of Hypatia's meta-data. The class has public
integer properties representing the major, minor, and patch portions
of the version number. This makes it possible for other code in the
engine to support or deprecate features based on the version by
comparing their numeric values, e.g.
if Version.major < 3:
# Report some error about a deprecated feature.
The `Version` class also implements `__str__()` so that it is possible
to convert `__version__` into a string, e.g. for `print()`, for the
purpose of output, e.g.
print(__version__) # "0.2.8"
Signed-off-by: Eric James Michael Ritz <3d928645612786af07f011fdfbce45f81efe5a40@plutono.com>
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
class Version:
"""A represntation of Hypatia's current version.
This class contains integer fields for the major, minor, and patch
version numbers, respectively. This is useful for comparison
within code if it becomes necessary to have code behave
differently based on the version, e.g. for backwards
compatibility. The class also supports str() which converts an
instance into a human-readable string, e.g. '0.2.8'.
Public Properties:
* major
* minor
* patch
"""
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.patch)
# str(__version__) will produce a string like "0.2.8"
__version__ = Version(0, 2, 8)
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
<commit_before>"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
__version__ = "0.2.8"
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
<commit_msg>[Feature] Add a class for representing the current version
This patch implements the `Version` class inside of the `__init__.py`
file alongside the rest of Hypatia's meta-data. The class has public
integer properties representing the major, minor, and patch portions
of the version number. This makes it possible for other code in the
engine to support or deprecate features based on the version by
comparing their numeric values, e.g.
if Version.major < 3:
# Report some error about a deprecated feature.
The `Version` class also implements `__str__()` so that it is possible
to convert `__version__` into a string, e.g. for `print()`, for the
purpose of output, e.g.
print(__version__) # "0.2.8"
Signed-off-by: Eric James Michael Ritz <3d928645612786af07f011fdfbce45f81efe5a40@plutono.com><commit_after>
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
class Version:
"""A represntation of Hypatia's current version.
This class contains integer fields for the major, minor, and patch
version numbers, respectively. This is useful for comparison
within code if it becomes necessary to have code behave
differently based on the version, e.g. for backwards
compatibility. The class also supports str() which converts an
instance into a human-readable string, e.g. '0.2.8'.
Public Properties:
* major
* minor
* patch
"""
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.patch)
# str(__version__) will produce a string like "0.2.8"
__version__ = Version(0, 2, 8)
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
__version__ = "0.2.8"
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
[Feature] Add a class for representing the current version
This patch implements the `Version` class inside of the `__init__.py`
file alongside the rest of Hypatia's meta-data. The class has public
integer properties representing the major, minor, and patch portions
of the version number. This makes it possible for other code in the
engine to support or deprecate features based on the version by
comparing their numeric values, e.g.
if Version.major < 3:
# Report some error about a deprecated feature.
The `Version` class also implements `__str__()` so that it is possible
to convert `__version__` into a string, e.g. for `print()`, for the
purpose of output, e.g.
print(__version__) # "0.2.8"
Signed-off-by: Eric James Michael Ritz <3d928645612786af07f011fdfbce45f81efe5a40@plutono.com>"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
class Version:
"""A represntation of Hypatia's current version.
This class contains integer fields for the major, minor, and patch
version numbers, respectively. This is useful for comparison
within code if it becomes necessary to have code behave
differently based on the version, e.g. for backwards
compatibility. The class also supports str() which converts an
instance into a human-readable string, e.g. '0.2.8'.
Public Properties:
* major
* minor
* patch
"""
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.patch)
# str(__version__) will produce a string like "0.2.8"
__version__ = Version(0, 2, 8)
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
<commit_before>"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
__version__ = "0.2.8"
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
<commit_msg>[Feature] Add a class for representing the current version
This patch implements the `Version` class inside of the `__init__.py`
file alongside the rest of Hypatia's meta-data. The class has public
integer properties representing the major, minor, and patch portions
of the version number. This makes it possible for other code in the
engine to support or deprecate features based on the version by
comparing their numeric values, e.g.
if Version.major < 3:
# Report some error about a deprecated feature.
The `Version` class also implements `__str__()` so that it is possible
to convert `__version__` into a string, e.g. for `print()`, for the
purpose of output, e.g.
print(__version__) # "0.2.8"
Signed-off-by: Eric James Michael Ritz <3d928645612786af07f011fdfbce45f81efe5a40@plutono.com><commit_after>"""This module contains all of the important meta-information for
Hypatia such as the author's name, the copyright and license, status,
and so on.
"""
__author__ = "Lillian Lemmer"
__copyright__ = "Copyright 2015 Lillian Lemmer"
__credits__ = ["Lillian Lemmer"]
__license__ = "MIT"
__maintainer__ = __author__
__site__ = "http://lillian-lemmer.github.io/hypatia/"
__email__ = "lillian.lynn.lemmer@gmail.com"
__status__ = "Development"
class Version:
"""A represntation of Hypatia's current version.
This class contains integer fields for the major, minor, and patch
version numbers, respectively. This is useful for comparison
within code if it becomes necessary to have code behave
differently based on the version, e.g. for backwards
compatibility. The class also supports str() which converts an
instance into a human-readable string, e.g. '0.2.8'.
Public Properties:
* major
* minor
* patch
"""
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.patch)
# str(__version__) will produce a string like "0.2.8"
__version__ = Version(0, 2, 8)
__contributors__ = [
"Lillian Lemmer",
"Brian Houston Morrow",
"Eric James Michael Ritz"
]
|
28198f5f200fa655b1b509d0c744391eaa714577
|
python/executeprocess.py
|
python/executeprocess.py
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if sys.platform.startswith("win"):
for index,item in enumerate(args):
if '\\' in item:
args[index] = item.replace('\\', '/')
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
Convert back slashes to forward slashes before executing Python processes
|
[trunk] Convert back slashes to forward slashes before executing Python processes
|
Python
|
bsd-3-clause
|
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
[trunk] Convert back slashes to forward slashes before executing Python processes
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if sys.platform.startswith("win"):
for index,item in enumerate(args):
if '\\' in item:
args[index] = item.replace('\\', '/')
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
<commit_before>import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
<commit_msg>[trunk] Convert back slashes to forward slashes before executing Python processes<commit_after>
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if sys.platform.startswith("win"):
for index,item in enumerate(args):
if '\\' in item:
args[index] = item.replace('\\', '/')
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
[trunk] Convert back slashes to forward slashes before executing Python processesimport subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if sys.platform.startswith("win"):
for index,item in enumerate(args):
if '\\' in item:
args[index] = item.replace('\\', '/')
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
<commit_before>import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
<commit_msg>[trunk] Convert back slashes to forward slashes before executing Python processes<commit_after>import subprocess
import sys
def ExecuteProcess(args, verbose=False, isCSharp=False):
if sys.platform.startswith("win"):
for index,item in enumerate(args):
if '\\' in item:
args[index] = item.replace('\\', '/')
if isCSharp and sys.platform.startswith("darwin"):
newArgs = ["mono"]
newArgs.extend(args)
args = newArgs
if verbose:
print "Executing: '%s'" % " ".join(args)
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output = process.communicate()
if process.returncode != 0:
raise RuntimeError("Command '%s' failed" % (" ".join(args)))
return output
|
f4e5904fc277eba2a8dfb37a6a1b598b197b20c8
|
spacy/lang/es/__init__.py
|
spacy/lang/es/__init__.py
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
Fix Spanish noun_chunks failure caused by typo
|
Fix Spanish noun_chunks failure caused by typo
|
Python
|
mit
|
honnibal/spaCy,recognai/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
Fix Spanish noun_chunks failure caused by typo
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
<commit_before># coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
<commit_msg>Fix Spanish noun_chunks failure caused by typo<commit_after>
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
Fix Spanish noun_chunks failure caused by typo# coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
<commit_before># coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
<commit_msg>Fix Spanish noun_chunks failure caused by typo<commit_after># coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
|
d663f5e5456b3907e6bd3fd2700ecaa301ce4403
|
ehriportal/portal/utils.py
|
ehriportal/portal/utils.py
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
return transformations.cc_to_cn(code)
except KeyError:
pass
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
# Hacky dictionary of official country/languages names
# we want to substitute for friendlier versions...
# A more permenant solution is needed to this.
SUBNAMES = {
"United Kingdom of Great Britain & Northern Ireland": "United Kingdom",
}
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
name = transformations.cc_to_cn(code)
return SUBNAMES.get(name, name)
except KeyError:
pass
|
Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain.
|
Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain.
|
Python
|
mit
|
mikesname/ehri-collections,mikesname/ehri-collections,mikesname/ehri-collections
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
return transformations.cc_to_cn(code)
except KeyError:
pass
Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain.
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
# Hacky dictionary of official country/languages names
# we want to substitute for friendlier versions...
# A more permenant solution is needed to this.
SUBNAMES = {
"United Kingdom of Great Britain & Northern Ireland": "United Kingdom",
}
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
name = transformations.cc_to_cn(code)
return SUBNAMES.get(name, name)
except KeyError:
pass
|
<commit_before>"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
return transformations.cc_to_cn(code)
except KeyError:
pass
<commit_msg>Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain.<commit_after>
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
# Hacky dictionary of official country/languages names
# we want to substitute for friendlier versions...
# A more permenant solution is needed to this.
SUBNAMES = {
"United Kingdom of Great Britain & Northern Ireland": "United Kingdom",
}
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
name = transformations.cc_to_cn(code)
return SUBNAMES.get(name, name)
except KeyError:
pass
|
"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
return transformations.cc_to_cn(code)
except KeyError:
pass
Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain."""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
# Hacky dictionary of official country/languages names
# we want to substitute for friendlier versions...
# A more permenant solution is needed to this.
SUBNAMES = {
"United Kingdom of Great Britain & Northern Ireland": "United Kingdom",
}
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
name = transformations.cc_to_cn(code)
return SUBNAMES.get(name, name)
except KeyError:
pass
|
<commit_before>"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
return transformations.cc_to_cn(code)
except KeyError:
pass
<commit_msg>Add a hacky method of subbing 'official' names which are awkward, for more handy ones. i.e. 'United Kingdom of Great Britain & Northern Ireland -> Great Britain.<commit_after>"""Utility functions for dealing with repository and geo data."""
from incf.countryutils import transformations
import babel
# Hacky dictionary of official country/languages names
# we want to substitute for friendlier versions...
# A more permenant solution is needed to this.
SUBNAMES = {
"United Kingdom of Great Britain & Northern Ireland": "United Kingdom",
}
def language_name_from_code(code, locale="en"):
"""Get lang display name."""
# TODO: Find the correct way to do this
return babel.Locale(locale).languages.get(code, "")
def get_country_from_code(code):
"""Get the country code from a coutry name."""
try:
name = transformations.cc_to_cn(code)
return SUBNAMES.get(name, name)
except KeyError:
pass
|
225ae01e3147bbee5c03462dad7dcfef22297f51
|
elevator/utils/patterns.py
|
elevator/utils/patterns.py
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
def destructurate(container):
class DestructurationError(Exception):
pass
if isinstance(container, Sequence):
return container[0], container[1:]
else:
raise DestructurationError("Can't destructurate a non-sequence container")
return container
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
class DestructurationError(Exception):
pass
def destructurate(container):
try:
return container[0], container[1:]
except (KeyError, AttributeError):
raise DestructurationError("Can't destructurate a non-sequence container")
|
Update : try/except in destructurate greatly enhances performances on mass read/write
|
Update : try/except in destructurate greatly enhances performances on mass read/write
|
Python
|
mit
|
oleiade/Elevator
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
def destructurate(container):
class DestructurationError(Exception):
pass
if isinstance(container, Sequence):
return container[0], container[1:]
else:
raise DestructurationError("Can't destructurate a non-sequence container")
return container
Update : try/except in destructurate greatly enhances performances on mass read/write
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
class DestructurationError(Exception):
pass
def destructurate(container):
try:
return container[0], container[1:]
except (KeyError, AttributeError):
raise DestructurationError("Can't destructurate a non-sequence container")
|
<commit_before>from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
def destructurate(container):
class DestructurationError(Exception):
pass
if isinstance(container, Sequence):
return container[0], container[1:]
else:
raise DestructurationError("Can't destructurate a non-sequence container")
return container
<commit_msg>Update : try/except in destructurate greatly enhances performances on mass read/write<commit_after>
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
class DestructurationError(Exception):
pass
def destructurate(container):
try:
return container[0], container[1:]
except (KeyError, AttributeError):
raise DestructurationError("Can't destructurate a non-sequence container")
|
from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
def destructurate(container):
class DestructurationError(Exception):
pass
if isinstance(container, Sequence):
return container[0], container[1:]
else:
raise DestructurationError("Can't destructurate a non-sequence container")
return container
Update : try/except in destructurate greatly enhances performances on mass read/writefrom collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
class DestructurationError(Exception):
pass
def destructurate(container):
try:
return container[0], container[1:]
except (KeyError, AttributeError):
raise DestructurationError("Can't destructurate a non-sequence container")
|
<commit_before>from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
def destructurate(container):
class DestructurationError(Exception):
pass
if isinstance(container, Sequence):
return container[0], container[1:]
else:
raise DestructurationError("Can't destructurate a non-sequence container")
return container
<commit_msg>Update : try/except in destructurate greatly enhances performances on mass read/write<commit_after>from collections import Sequence
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
def __del__(cls, *args, **kw):
cls.instance is None
class DestructurationError(Exception):
pass
def destructurate(container):
try:
return container[0], container[1:]
except (KeyError, AttributeError):
raise DestructurationError("Can't destructurate a non-sequence container")
|
a3f981006fae846714bdb5aa0de98ac829a57bc0
|
registration/__init__.py
|
registration/__init__.py
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
|
Fix dependency order issue in get_version
|
Fix dependency order issue in get_version
|
Python
|
bsd-3-clause
|
ildarsamit/django-registration,ildarsamit/django-registration
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
Fix dependency order issue in get_version
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
|
<commit_before>VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
<commit_msg>Fix dependency order issue in get_version<commit_after>
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
|
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
Fix dependency order issue in get_versionVERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
|
<commit_before>VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
<commit_msg>Fix dependency order issue in get_version<commit_after>VERSION = (0, 9, 0, 'beta', 1)
def get_version():
try:
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
except ImportError:
return ".".join(str(n) for n in VERSION)
|
7d9a85c57deb6a6d89dcf9764ffe8baf3cb2981b
|
wcontrol/db/db_create.py
|
wcontrol/db/db_create.py
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
Modify config to fit with PEP8 standard
|
Modify config to fit with PEP8 standard
|
Python
|
mit
|
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
Modify config to fit with PEP8 standard
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
<commit_before>#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
<commit_msg>Modify config to fit with PEP8 standard<commit_after>
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
Modify config to fit with PEP8 standard#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
<commit_before>#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
<commit_msg>Modify config to fit with PEP8 standard<commit_after>#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
5c80b42df31b03b5eb433e704a58f77624e2d24a
|
tests/urls.py
|
tests/urls.py
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tinyblog.tests.views.test_404'
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tests.views.test_404'
|
Fix path to 404 handler
|
Fix path to 404 handler
|
Python
|
bsd-3-clause
|
dominicrodger/tinyblog,dominicrodger/tinyblog
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tinyblog.tests.views.test_404'
Fix path to 404 handler
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tests.views.test_404'
|
<commit_before>from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tinyblog.tests.views.test_404'
<commit_msg>Fix path to 404 handler<commit_after>
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tests.views.test_404'
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tinyblog.tests.views.test_404'
Fix path to 404 handlerfrom django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tests.views.test_404'
|
<commit_before>from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tinyblog.tests.views.test_404'
<commit_msg>Fix path to 404 handler<commit_after>from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^', include('tinyblog.urls')),
)
handler404 = 'tests.views.test_404'
|
272d0bbc590fefa393317f27d2fa0c5912d654a9
|
django_cbtp_email/example_project/tests/test_basic.py
|
django_cbtp_email/example_project/tests/test_basic.py
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
assert TestMailer.subject in sent_message.subject
assert TestMailer.to in sent_message.to
assert "<p style=\"font-size:42pt\">" in sent_message.body
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
self.assertIn(TestMailer.subject, sent_message.subject)
self.assertIn(TestMailer.to, sent_message.to)
self.assertIn("<p style=\"font-size:42pt\">", sent_message.body)
# noinspection PyMethodMayBeStatic
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
Use assertIn in tests for better error message.
|
Use assertIn in tests for better error message.
|
Python
|
mit
|
illagrenan/django-cbtp-email,illagrenan/django-cbtp-email
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
assert TestMailer.subject in sent_message.subject
assert TestMailer.to in sent_message.to
assert "<p style=\"font-size:42pt\">" in sent_message.body
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
Use assertIn in tests for better error message.
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
self.assertIn(TestMailer.subject, sent_message.subject)
self.assertIn(TestMailer.to, sent_message.to)
self.assertIn("<p style=\"font-size:42pt\">", sent_message.body)
# noinspection PyMethodMayBeStatic
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
<commit_before># -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
assert TestMailer.subject in sent_message.subject
assert TestMailer.to in sent_message.to
assert "<p style=\"font-size:42pt\">" in sent_message.body
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
<commit_msg>Use assertIn in tests for better error message.<commit_after>
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
self.assertIn(TestMailer.subject, sent_message.subject)
self.assertIn(TestMailer.to, sent_message.to)
self.assertIn("<p style=\"font-size:42pt\">", sent_message.body)
# noinspection PyMethodMayBeStatic
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
assert TestMailer.subject in sent_message.subject
assert TestMailer.to in sent_message.to
assert "<p style=\"font-size:42pt\">" in sent_message.body
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
Use assertIn in tests for better error message.# -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
self.assertIn(TestMailer.subject, sent_message.subject)
self.assertIn(TestMailer.to, sent_message.to)
self.assertIn("<p style=\"font-size:42pt\">", sent_message.body)
# noinspection PyMethodMayBeStatic
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
<commit_before># -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
assert TestMailer.subject in sent_message.subject
assert TestMailer.to in sent_message.to
assert "<p style=\"font-size:42pt\">" in sent_message.body
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
<commit_msg>Use assertIn in tests for better error message.<commit_after># -*- encoding: utf-8 -*-
# ! python2
from __future__ import (absolute_import, division, print_function, unicode_literals)
import os
import tempfile
from django.test import TestCase
from ..tests.mailers import TestMailer
class BasicUsageTestCase(TestCase):
def test_message_will_be_sent_with_inlined_css(self):
test_mailer = TestMailer()
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
sent_message = outbox[0]
""":type : django.core.mail.EmailMessage """
self.assertIn(TestMailer.subject, sent_message.subject)
self.assertIn(TestMailer.to, sent_message.to)
self.assertIn("<p style=\"font-size:42pt\">", sent_message.body)
# noinspection PyMethodMayBeStatic
def test_attachment(self):
test_mailer = TestMailer()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
test_mailer.attach_file(temp.name)
test_mailer.send_message()
from django.core.mail import outbox
assert len(outbox) == 1
os.remove(temp.name)
def test_empty_recipient(self):
test_mailer = TestMailer(to=None)
# Recipient is not set
self.assertRaises(ValueError, test_mailer.send_message)
|
4601937752f707110d303e403153cc4412bcde58
|
oshino/util.py
|
oshino/util.py
|
from time import time
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
return int(time() * 1000)
|
from datetime import datetime
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
utcnow = datetime.utcnow()
return int(utcnow.timestamp() * 1000)
|
Use UTC timestamp as timestamp
|
Use UTC timestamp as timestamp
|
Python
|
mit
|
CodersOfTheNight/oshino
|
from time import time
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
return int(time() * 1000)
Use UTC timestamp as timestamp
|
from datetime import datetime
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
utcnow = datetime.utcnow()
return int(utcnow.timestamp() * 1000)
|
<commit_before>from time import time
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
return int(time() * 1000)
<commit_msg>Use UTC timestamp as timestamp<commit_after>
|
from datetime import datetime
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
utcnow = datetime.utcnow()
return int(utcnow.timestamp() * 1000)
|
from time import time
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
return int(time() * 1000)
Use UTC timestamp as timestampfrom datetime import datetime
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
utcnow = datetime.utcnow()
return int(utcnow.timestamp() * 1000)
|
<commit_before>from time import time
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
return int(time() * 1000)
<commit_msg>Use UTC timestamp as timestamp<commit_after>from datetime import datetime
def dynamic_import(path):
module, builder = path.rsplit(".", 1)
return getattr(__import__(module, fromlist=[builder]), builder)
def current_ts():
"""
Just gives current timestamp.
"""
utcnow = datetime.utcnow()
return int(utcnow.timestamp() * 1000)
|
6480a810b66a437ac716eb164c20f5bcc97d0934
|
src/handlers/admin.py
|
src/handlers/admin.py
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
column_list = ('id', 'perspective', 'start_time')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
column_list = ('id', 'gender', 'text', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class SubmissionModelView(ModelView):
column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(SubmissionModelView, self).__init__(
schema.Submission,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
|
Fix list columns for all models
|
Fix list columns for all models
|
Python
|
apache-2.0
|
pascalc/narrative-roulette,pascalc/narrative-roulette
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
Fix list columns for all models
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
column_list = ('id', 'perspective', 'start_time')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
column_list = ('id', 'gender', 'text', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class SubmissionModelView(ModelView):
column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(SubmissionModelView, self).__init__(
schema.Submission,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
|
<commit_before>from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
<commit_msg>Fix list columns for all models<commit_after>
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
column_list = ('id', 'perspective', 'start_time')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
column_list = ('id', 'gender', 'text', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class SubmissionModelView(ModelView):
column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(SubmissionModelView, self).__init__(
schema.Submission,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
|
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
Fix list columns for all modelsfrom flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
column_list = ('id', 'perspective', 'start_time')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
column_list = ('id', 'gender', 'text', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class SubmissionModelView(ModelView):
column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(SubmissionModelView, self).__init__(
schema.Submission,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
|
<commit_before>from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))
<commit_msg>Fix list columns for all models<commit_after>from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
import db.schema as schema
import db.query as query
from handlers.rest import app
admin = Admin(app, url="/admin")
class RoundModelView(ModelView):
column_list = ('id', 'perspective', 'start_time')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(RoundModelView, self).__init__(
schema.Round,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class PerspectiveModelView(ModelView):
form_columns = \
('gender',
'text')
column_list = ('id', 'gender', 'text', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(PerspectiveModelView, self).__init__(
schema.Perspective,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
class SubmissionModelView(ModelView):
column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
super(SubmissionModelView, self).__init__(
schema.Submission,
query.session,
name=name,
category=category,
endpoint=endpoint,
url=url
)
admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())
|
c97c07b1f4ccc5798a935bf1bbcfe84986cb9f65
|
tikplay/tests/test_server.py
|
tikplay/tests/test_server.py
|
import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
import unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
Add a dummy server - Tests are broken
|
Add a dummy server - Tests are broken
|
Python
|
mit
|
tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay
|
import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
Add a dummy server - Tests are broken
|
import unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
<commit_before>import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
<commit_msg>Add a dummy server - Tests are broken<commit_after>
|
import unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
Add a dummy server - Tests are brokenimport unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
<commit_before>import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
<commit_msg>Add a dummy server - Tests are broken<commit_after>import unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
cd2ff46284a8144755b880c035d0a89938474955
|
salt/grains/extra.py
|
salt/grains/extra.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
import salt.utils.platform
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
if salt.utils.platform.is_windows():
env_var = 'COMSPEC'
default = r'C:\Windows\system32\cmd.exe'
else:
env_var = 'SHELL'
default = '/bin/sh'
return {'shell': os.environ.get(env_var, default)}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
Return COMSPEC as the shell for Windows
|
Return COMSPEC as the shell for Windows
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
Return COMSPEC as the shell for Windows
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
import salt.utils.platform
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
if salt.utils.platform.is_windows():
env_var = 'COMSPEC'
default = r'C:\Windows\system32\cmd.exe'
else:
env_var = 'SHELL'
default = '/bin/sh'
return {'shell': os.environ.get(env_var, default)}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
<commit_msg>Return COMSPEC as the shell for Windows<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
import salt.utils.platform
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
if salt.utils.platform.is_windows():
env_var = 'COMSPEC'
default = r'C:\Windows\system32\cmd.exe'
else:
env_var = 'SHELL'
default = '/bin/sh'
return {'shell': os.environ.get(env_var, default)}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
Return COMSPEC as the shell for Windows# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
import salt.utils.platform
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
if salt.utils.platform.is_windows():
env_var = 'COMSPEC'
default = r'C:\Windows\system32\cmd.exe'
else:
env_var = 'SHELL'
default = '/bin/sh'
return {'shell': os.environ.get(env_var, default)}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
return {'shell': os.environ.get('SHELL', '/bin/sh')}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
<commit_msg>Return COMSPEC as the shell for Windows<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import
# Import python libs
import os
# Import third party libs
import yaml
import logging
# Import salt libs
import salt.utils.files
import salt.utils.platform
log = logging.getLogger(__name__)
def shell():
'''
Return the default shell to use on this system
'''
# Provides:
# shell
if salt.utils.platform.is_windows():
env_var = 'COMSPEC'
default = r'C:\Windows\system32\cmd.exe'
else:
env_var = 'SHELL'
default = '/bin/sh'
return {'shell': os.environ.get(env_var, default)}
def config():
'''
Return the grains set in the grains file
'''
if 'conf_file' not in __opts__:
return {}
if os.path.isdir(__opts__['conf_file']):
gfn = os.path.join(
__opts__['conf_file'],
'grains'
)
else:
gfn = os.path.join(
os.path.dirname(__opts__['conf_file']),
'grains'
)
if os.path.isfile(gfn):
with salt.utils.files.fopen(gfn, 'rb') as fp_:
try:
return yaml.safe_load(fp_.read())
except Exception:
log.warning("Bad syntax in grains file! Skipping.")
return {}
return {}
|
255b3f645d42464d4f8c80e97200d4dacc513616
|
keras/preprocessing/__init__.py
|
keras/preprocessing/__init__.py
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model."""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to preprocess data before training.
Warning: `tf.keras.preprocessing` APIs do not operate on tensors and are
not recommended for new code. Prefer loading data with either
`tf.keras.utils.text_dataset_from_directory` or
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. These approaches will offer
better performance and intergration with the broader Tensorflow ecosystem. For
more information, see the tutorials for [loading text](
https://www.tensorflow.org/tutorials/load_data/text), [loading images](
https://www.tensorflow.org/tutorials/load_data/images), and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/keras/preprocessing_layers).
"""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
Add a toplevel warning against legacy keras.preprocessing utilities
|
Add a toplevel warning against legacy keras.preprocessing utilities
PiperOrigin-RevId: 434866390
|
Python
|
apache-2.0
|
keras-team/keras,keras-team/keras
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model."""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
Add a toplevel warning against legacy keras.preprocessing utilities
PiperOrigin-RevId: 434866390
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to preprocess data before training.
Warning: `tf.keras.preprocessing` APIs do not operate on tensors and are
not recommended for new code. Prefer loading data with either
`tf.keras.utils.text_dataset_from_directory` or
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. These approaches will offer
better performance and intergration with the broader Tensorflow ecosystem. For
more information, see the tutorials for [loading text](
https://www.tensorflow.org/tutorials/load_data/text), [loading images](
https://www.tensorflow.org/tutorials/load_data/images), and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/keras/preprocessing_layers).
"""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
<commit_before># Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model."""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
<commit_msg>Add a toplevel warning against legacy keras.preprocessing utilities
PiperOrigin-RevId: 434866390<commit_after>
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to preprocess data before training.
Warning: `tf.keras.preprocessing` APIs do not operate on tensors and are
not recommended for new code. Prefer loading data with either
`tf.keras.utils.text_dataset_from_directory` or
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. These approaches will offer
better performance and intergration with the broader Tensorflow ecosystem. For
more information, see the tutorials for [loading text](
https://www.tensorflow.org/tutorials/load_data/text), [loading images](
https://www.tensorflow.org/tutorials/load_data/images), and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/keras/preprocessing_layers).
"""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model."""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
Add a toplevel warning against legacy keras.preprocessing utilities
PiperOrigin-RevId: 434866390# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to preprocess data before training.
Warning: `tf.keras.preprocessing` APIs do not operate on tensors and are
not recommended for new code. Prefer loading data with either
`tf.keras.utils.text_dataset_from_directory` or
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. These approaches will offer
better performance and intergration with the broader Tensorflow ecosystem. For
more information, see the tutorials for [loading text](
https://www.tensorflow.org/tutorials/load_data/text), [loading images](
https://www.tensorflow.org/tutorials/load_data/images), and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/keras/preprocessing_layers).
"""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
<commit_before># Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides keras data preprocessing utils to pre-process tf.data.Datasets before they are fed to the model."""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
<commit_msg>Add a toplevel warning against legacy keras.preprocessing utilities
PiperOrigin-RevId: 434866390<commit_after># Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to preprocess data before training.
Warning: `tf.keras.preprocessing` APIs do not operate on tensors and are
not recommended for new code. Prefer loading data with either
`tf.keras.utils.text_dataset_from_directory` or
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. These approaches will offer
better performance and intergration with the broader Tensorflow ecosystem. For
more information, see the tutorials for [loading text](
https://www.tensorflow.org/tutorials/load_data/text), [loading images](
https://www.tensorflow.org/tutorials/load_data/images), and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/keras/preprocessing_layers).
"""
from keras import backend
from keras.preprocessing import image
from keras.preprocessing import sequence
from keras.preprocessing import text
from keras.preprocessing import timeseries
from keras.utils import all_utils as utils
|
1e182ec0fd7cf550c809f2e6792629caeb8d5553
|
sauce/lib/helpers.py
|
sauce/lib/helpers.py
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
|
Use striptags from genshi for striphtml, since we have to have genshi anyway
|
Use striptags from genshi for striphtml, since we have to have genshi anyway
|
Python
|
agpl-3.0
|
moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
Use striptags from genshi for striphtml, since we have to have genshi anyway
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
|
<commit_before># -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
<commit_msg>Use striptags from genshi for striphtml, since we have to have genshi anyway<commit_after>
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
|
# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
Use striptags from genshi for striphtml, since we have to have genshi anyway# -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
|
<commit_before># -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
def striphtml(text):
return re.sub('<[^<]+?>', ' ', text).strip()
<commit_msg>Use striptags from genshi for striphtml, since we have to have genshi anyway<commit_after># -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhelpers.date import distance_of_time_in_words
from genshi.core import striptags
import re
#log = logging.getLogger(__name__)
cut = lambda text, max=200: truncate(text, max, whole_word=True)
strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity)
striphtml = striptags
def link(label, url='', **attrs):
return link_to(label, tgurl(url), **attrs)
|
b9c66ca635d48c6d6d04d8b68e7befe910cad347
|
scattergun/scattergun_coreapp/tests.py
|
scattergun/scattergun_coreapp/tests.py
|
from django.test import TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
|
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
class TeamViewTestCase(TestCase):
def test_team_views(self):
views = ('scattergun-team-add', 'scattergun-team-list')
client = Client()
for view in views:
response = self.client.get(reverse(view))
self.assertEqual(response.status_code, 200)
|
Add unit test for team views
|
Add unit test for team views
|
Python
|
mit
|
Team4761/Scattergun,Team4761/Scattergun,Team4761/Scattergun
|
from django.test import TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)Add unit test for team views
|
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
class TeamViewTestCase(TestCase):
def test_team_views(self):
views = ('scattergun-team-add', 'scattergun-team-list')
client = Client()
for view in views:
response = self.client.get(reverse(view))
self.assertEqual(response.status_code, 200)
|
<commit_before>from django.test import TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)<commit_msg>Add unit test for team views<commit_after>
|
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
class TeamViewTestCase(TestCase):
def test_team_views(self):
views = ('scattergun-team-add', 'scattergun-team-list')
client = Client()
for view in views:
response = self.client.get(reverse(view))
self.assertEqual(response.status_code, 200)
|
from django.test import TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)Add unit test for team viewsfrom django.core.urlresolvers import reverse
from django.test import Client, TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
class TeamViewTestCase(TestCase):
def test_team_views(self):
views = ('scattergun-team-add', 'scattergun-team-list')
client = Client()
for view in views:
response = self.client.get(reverse(view))
self.assertEqual(response.status_code, 200)
|
<commit_before>from django.test import TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)<commit_msg>Add unit test for team views<commit_after>from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from .models import Team
class TeamTestCase(TestCase):
def setUp(self):
Team.objects.create(name="Test Team 1", number=1)
def test_team_created_correctly(self):
test_team_1 = Team.objects.get(number=1)
self.assertEqual(test_team_1.name, "Test Team 1")
self.assertEqual(test_team_1.number, 1)
class TeamViewTestCase(TestCase):
def test_team_views(self):
views = ('scattergun-team-add', 'scattergun-team-list')
client = Client()
for view in views:
response = self.client.get(reverse(view))
self.assertEqual(response.status_code, 200)
|
28c11c91ad056735952f904c86c2fb726ef90f81
|
test/util.py
|
test/util.py
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'pytest-warnings', 'warnings', 'warning':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'warnings':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
Remove checks for deprecated keys in outcomes
|
Remove checks for deprecated keys in outcomes
|
Python
|
mit
|
ropez/pytest-describe
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'pytest-warnings', 'warnings', 'warning':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
Remove checks for deprecated keys in outcomes
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'warnings':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
<commit_before>def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'pytest-warnings', 'warnings', 'warning':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
<commit_msg>Remove checks for deprecated keys in outcomes<commit_after>
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'warnings':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'pytest-warnings', 'warnings', 'warning':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
Remove checks for deprecated keys in outcomesdef assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'warnings':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
<commit_before>def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'pytest-warnings', 'warnings', 'warning':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
<commit_msg>Remove checks for deprecated keys in outcomes<commit_after>def assert_outcomes(result, **expected):
outcomes = result.parseoutcomes()
for key in 'seconds', 'warnings':
if key in outcomes:
del outcomes[key]
assert outcomes == expected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.