commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
a179b2afff8af8dce5ae816d6f97a002a9151cf4
booger_test.py
booger_test.py
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # <thenoviceoof> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you can buy me a beer in # return # Nathan Hwang <thenoviceoof> # ---------------------------------------------------------------------------- ################################################################################ from unittest import TestCase ################################################################################ # Nosetest parser from booger import NOSE_DIV_WIDTH, NosetestsParser class NosetestsParserTest(TestCase): def setUp(self): self.parser = NosetestsParser() def short_output_test(self): inp = '=' * 70 out, end = self.parser.parse_short_output(inp) assert end == True
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # <thenoviceoof> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you can buy me a beer in # return # Nathan Hwang <thenoviceoof> ################################################################################ from unittest import TestCase ################################################################################ # Nosetest parser from booger import NOSE_DIV_WIDTH, NosetestsParser class NosetestsParserTest(TestCase): def setUp(self): self.parser = NosetestsParser() def short_output_end_test(self): ''' Make sure we recognise the end of the short output ''' inp = '=' * 70 out, end = self.parser.parse_short_output(inp) assert end == False def short_output_ok_test(self): ''' Recognize `msg ... ok` messages ''' msg = 'msg ... ok' out, end = self.parser.parse_short_output(msg) assert out == 'ok' def short_output_fail_test(self): ''' Recognize `msg ... FAIL` messages ''' msg = 'msg ... FAIL' out, end = self.parser.parse_short_output(msg) assert out == 'fail' def short_output_error_test(self): ''' Recognize `msg ... ERROR` messages ''' msg = 'msg ... ERROR' out, end = self.parser.parse_short_output(msg) assert out == 'error'
Write some more tests for the short nosetests parser
Write some more tests for the short nosetests parser
Python
mit
thenoviceoof/booger,thenoviceoof/booger
--- +++ @@ -6,7 +6,6 @@ # and you think this stuff is worth it, you can buy me a beer in # return # Nathan Hwang <thenoviceoof> -# ---------------------------------------------------------------------------- ################################################################################ from unittest import TestCase @@ -19,7 +18,32 @@ class NosetestsParserTest(TestCase): def setUp(self): self.parser = NosetestsParser() - def short_output_test(self): + + def short_output_end_test(self): + ''' + Make sure we recognise the end of the short output + ''' inp = '=' * 70 out, end = self.parser.parse_short_output(inp) - assert end == True + assert end == False + def short_output_ok_test(self): + ''' + Recognize `msg ... ok` messages + ''' + msg = 'msg ... ok' + out, end = self.parser.parse_short_output(msg) + assert out == 'ok' + def short_output_fail_test(self): + ''' + Recognize `msg ... FAIL` messages + ''' + msg = 'msg ... FAIL' + out, end = self.parser.parse_short_output(msg) + assert out == 'fail' + def short_output_error_test(self): + ''' + Recognize `msg ... ERROR` messages + ''' + msg = 'msg ... ERROR' + out, end = self.parser.parse_short_output(msg) + assert out == 'error'
65731a34e152d085f55893c65607b8fa25dcfd63
pathvalidate/_interface.py
pathvalidate/_interface.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass def is_valid(self, value): try: self.validate(value) except (TypeError, ValidationError): return False return True @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
Add is_valid method for file sanitizer classes
Add is_valid method for file sanitizer classes
Python
mit
thombashi/pathvalidate
--- +++ @@ -10,6 +10,7 @@ from ._common import validate_null_string from ._six import add_metaclass +from .error import ValidationError @add_metaclass(abc.ABCMeta) @@ -22,6 +23,14 @@ def validate(self, value): # pragma: no cover pass + def is_valid(self, value): + try: + self.validate(value) + except (TypeError, ValidationError): + return False + + return True + @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass
95d498009eca0a9e179a14eec05e7e3738a72bfb
twitter/stream_example.py
twitter/stream_example.py
""" Example program for the Stream API. This prints public status messages from the "sample" stream as fast as possible. USAGE twitter-stream-example <username> <password> """ from __future__ import print_function import sys from .stream import TwitterStream from .auth import UserPassAuth from .util import printNicely def main(args=sys.argv[1:]): if not args[1:]: print(__doc__) return 1 # When using twitter stream you must authorize. UserPass or OAuth. stream = TwitterStream(auth=UserPassAuth(args[0], args[1])) # Iterate over the sample stream. tweet_iter = stream.statuses.sample() for tweet in tweet_iter: # You must test that your tweet has text. It might be a delete # or data message. if tweet.get('text'): printNicely(tweet['text'])
""" Example program for the Stream API. This prints public status messages from the "sample" stream as fast as possible. USAGE stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret> """ from __future__ import print_function import argparse from twitter.stream import TwitterStream from twitter.oauth import OAuth from twitter.util import printNicely def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-t', '--token', help='The Twitter Access Token.') parser.add_argument('-ts', '--token_secret', help='The Twitter Access Token Secret.') parser.add_argument('-ck', '--consumer_key', help='The Twitter Consumer Key.') parser.add_argument('-cs', '--consumer_secret', help='The Twitter Consumer Secret.') return parser.parse_args() ## parse_arguments() def main(): args = parse_arguments() # When using twitter stream you must authorize. stream = TwitterStream(auth=OAuth(args.token, args.token_secret, args.consumer_key, args.consumer_secret)) # Iterate over the sample stream. tweet_iter = stream.statuses.sample() for tweet in tweet_iter: # You must test that your tweet has text. It might be a delete # or data message. if tweet.get('text'): printNicely(tweet['text']) ## main() if __name__ == '__main__': main()
Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
Python
mit
Adai0808/twitter,tytek2012/twitter,adonoho/twitter,miragshin/twitter,hugovk/twitter,sixohsix/twitter,jessamynsmith/twitter
--- +++ @@ -4,25 +4,39 @@ USAGE - twitter-stream-example <username> <password> + stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret> """ from __future__ import print_function -import sys +import argparse -from .stream import TwitterStream -from .auth import UserPassAuth -from .util import printNicely +from twitter.stream import TwitterStream +from twitter.oauth import OAuth +from twitter.util import printNicely -def main(args=sys.argv[1:]): - if not args[1:]: - print(__doc__) - return 1 - # When using twitter stream you must authorize. UserPass or OAuth. - stream = TwitterStream(auth=UserPassAuth(args[0], args[1])) +def parse_arguments(): + + parser = argparse.ArgumentParser() + + parser.add_argument('-t', '--token', help='The Twitter Access Token.') + parser.add_argument('-ts', '--token_secret', help='The Twitter Access Token Secret.') + parser.add_argument('-ck', '--consumer_key', help='The Twitter Consumer Key.') + parser.add_argument('-cs', '--consumer_secret', help='The Twitter Consumer Secret.') + + return parser.parse_args() + +## parse_arguments() + + +def main(): + + args = parse_arguments() + + # When using twitter stream you must authorize. + stream = TwitterStream(auth=OAuth(args.token, args.token_secret, args.consumer_key, args.consumer_secret)) # Iterate over the sample stream. tweet_iter = stream.statuses.sample() @@ -31,3 +45,8 @@ # or data message. if tweet.get('text'): printNicely(tweet['text']) + +## main() + +if __name__ == '__main__': + main()
70c98a42326471d3ed615def61954905673c5972
typhon/nonlte/__init__.py
typhon/nonlte/__init__.py
# -*- coding: utf-8 -*- from .version import __version__ try: __ATRASU_SETUP__ except: __ATRASU_SETUP__ = False if not __ATRASU_SETUP__: from . import spectra from . import setup_atmosphere from . import const from . import nonltecalc from . import mathmatics from . import rtc
# -*- coding: utf-8 -*- try: __ATRASU_SETUP__ except: __ATRASU_SETUP__ = False if not __ATRASU_SETUP__: from . import spectra from . import setup_atmosphere from . import const from . import nonltecalc from . import mathmatics from . import rtc
Remove import of removed version module.
Remove import of removed version module.
Python
mit
atmtools/typhon,atmtools/typhon
--- +++ @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- - -from .version import __version__ try: __ATRASU_SETUP__
9ccdbcc01d1bf6323256b8b8f19fa1446bb57d59
tests/unit/test_authenticate.py
tests/unit/test_authenticate.py
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) record.has_calls([call().create(auth_token)])
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) assert call().create(auth_token) in record.mock_calls
Fix Bug in Test Assertion
Fix Bug in Test Assertion Need to train myself better on red-green-refactor. The previous assert always passed, because I wasn't triggering an actual Mock method. I had to change to verifying that the call is in the list of calls. I've verified that it fails when the call isn't made from the code under test and that it passes when it is.
Python
apache-2.0
Jitsusama/lets-do-dns
--- +++ @@ -18,4 +18,4 @@ Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) - record.has_calls([call().create(auth_token)]) + assert call().create(auth_token) in record.mock_calls
e1291e88e8d5cf1f50e9547fa78a4a53032cc89a
reproject/overlap.py
reproject/overlap.py
from ._overlap_wrapper import _computeOverlap def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.): """ Compute the overlap between two 'pixels' in spherical coordinates Parameters ---------- ilon : np.ndarray The longitudes defining the four corners of the input pixel ilat : np.ndarray The latitudes defining the four corners of the input pixel olon : np.ndarray The longitudes defining the four corners of the output pixel olat : np.ndarray The latitudes defining the four corners of the output pixel energy_mode : bool Whether to work in energy-conserving or surface-brightness-conserving mode reference_area : float To be determined """ return _computeOverlap(ilon, ilat, olon, olat, int(energy_mode), reference_area)
from ._overlap_wrapper import _computeOverlap def compute_overlap(ilon, ilat, olon, olat): """ Compute the overlap between two 'pixels' in spherical coordinates Parameters ---------- ilon : np.ndarray The longitudes defining the four corners of the input pixel ilat : np.ndarray The latitudes defining the four corners of the input pixel olon : np.ndarray The longitudes defining the four corners of the output pixel olat : np.ndarray The latitudes defining the four corners of the output pixel """ return _computeOverlap(ilon, ilat, olon, olat, 0, 1.)
Remove options until we actually need and understand them
Remove options until we actually need and understand them
Python
bsd-3-clause
barentsen/reproject,astrofrog/reproject,barentsen/reproject,mwcraig/reproject,astrofrog/reproject,astrofrog/reproject,mwcraig/reproject,barentsen/reproject,bsipocz/reproject,bsipocz/reproject
--- +++ @@ -1,6 +1,6 @@ from ._overlap_wrapper import _computeOverlap -def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.): +def compute_overlap(ilon, ilat, olon, olat): """ Compute the overlap between two 'pixels' in spherical coordinates @@ -14,11 +14,7 @@ The longitudes defining the four corners of the output pixel olat : np.ndarray The latitudes defining the four corners of the output pixel - energy_mode : bool - Whether to work in energy-conserving or surface-brightness-conserving mode - reference_area : float - To be determined """ - return _computeOverlap(ilon, ilat, olon, olat, int(energy_mode), reference_area) + return _computeOverlap(ilon, ilat, olon, olat, 0, 1.)
2c1673930a40fc94c3d7c7d4f764ea423b638d26
mccurse/cli.py
mccurse/cli.py
"""Package command line interface.""" import click from .curse import Game, Mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of search data.' ) @click.argument('text', nargs=-1, type=str) def search(refresh, text): """Search for TEXT in mods on CurseForge.""" mc = Game(**MINECRAFT) text = ' '.join(text) refresh = refresh or not mc.have_fresh_data() if refresh: click.echo('Refreshing search data, please wait…', err=True) mc.refresh_data() mod_fmt = '{0.name}: {0.summary}' for mod in Mod.search(mc.database.session(), text): click.echo(mod_fmt.format(mod)) # If run as a package, run whole cli cli()
"""Package command line interface.""" import click from .curse import Game, Mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of search data.' ) @click.argument('text', nargs=-1, type=str) def search(refresh, text): """Search for TEXT in mods on CurseForge.""" if not text: raise SystemExit('No text to search for!') mc = Game(**MINECRAFT) text = ' '.join(text) refresh = refresh or not mc.have_fresh_data() if refresh: click.echo('Refreshing search data, please wait…', err=True) mc.refresh_data() mod_fmt = '{0.name}: {0.summary}' for mod in Mod.search(mc.database.session(), text): click.echo(mod_fmt.format(mod)) # If run as a package, run whole cli cli()
Raise error when there is no term to search for
Raise error when there is no term to search for
Python
agpl-3.0
khardix/mccurse
--- +++ @@ -23,6 +23,9 @@ def search(refresh, text): """Search for TEXT in mods on CurseForge.""" + if not text: + raise SystemExit('No text to search for!') + mc = Game(**MINECRAFT) text = ' '.join(text)
6bdcda14c8bd5b66bc6fcb4bb6a520e326211f74
poll/models.py
poll/models.py
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Question(models.Model): text = models.TextField() question_group = models.ForeignKey(QuestionGroup) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Choice(models.Model): text = models.TextField() question = models.ForeignKey(Question) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Session(models.Model): name = models.TextField(blank=True) ip = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now=True) date_submitted = models.DateTimeField(null=True) class Response(models.Model): choice = models.ForeignKey(Choice) session = models.ForeignKey(Session) value = models.IntegerField() date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True)
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.heading class Question(models.Model): text = models.TextField() question_group = models.ForeignKey(QuestionGroup) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.text class Choice(models.Model): text = models.TextField() question = models.ForeignKey(Question) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.text class Session(models.Model): name = models.TextField(blank=True) ip = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now=True) date_submitted = models.DateTimeField(null=True) class Response(models.Model): choice = models.ForeignKey(Choice) session = models.ForeignKey(Session) value = models.IntegerField() date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True)
Implement __str__ for proper printing in admin
Implement __str__ for proper printing in admin
Python
mit
gabriel-v/psi,gabriel-v/psi,gabriel-v/psi
--- +++ @@ -7,6 +7,9 @@ date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) + def __str__(self): + return str(self.id) + ". " + self.heading + class Question(models.Model): text = models.TextField() @@ -14,12 +17,18 @@ date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) + def __str__(self): + return str(self.id) + ". " + self.text + class Choice(models.Model): text = models.TextField() question = models.ForeignKey(Question) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return str(self.id) + ". " + self.text class Session(models.Model):
0989089aa4e9766739359b57b2bd56e5b70fa53b
update_ip/ip_getters/__init__.py
update_ip/ip_getters/__init__.py
import base import getters ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random remaining= ALL[:] while remaining: getter= random.choice(remaining) try: return getter.get_ip() except base.GetIpFailed: remaining.remove( getter ) raise base.GetIpFailed("None of the ip_getters returned a good ip")
import base import getters import logging log= logging.getLogger('update_ip.ip_getters') ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random getters= ALL[:] random.shuffle( getters ) #for load balancing purposes for getter in getters: log.debug("Getting ip with getter {0}".format(getter.NAME)) try: return getter.get_ip() except base.GetIpFailed as e: log.info("IpGetter {0} failed to get IP: {1}".format(getter.NAME, e)) raise base.GetIpFailed("None of the ip_getters returned a good ip")
Add basic logging to ip_getters
Add basic logging to ip_getters
Python
bsd-3-clause
bkonkle/update-ip
--- +++ @@ -1,16 +1,19 @@ import base import getters +import logging +log= logging.getLogger('update_ip.ip_getters') ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random - remaining= ALL[:] - while remaining: - getter= random.choice(remaining) + getters= ALL[:] + random.shuffle( getters ) #for load balancing purposes + for getter in getters: + log.debug("Getting ip with getter {0}".format(getter.NAME)) try: return getter.get_ip() - except base.GetIpFailed: - remaining.remove( getter ) + except base.GetIpFailed as e: + log.info("IpGetter {0} failed to get IP: {1}".format(getter.NAME, e)) raise base.GetIpFailed("None of the ip_getters returned a good ip")
35d5dc83d8abc4e33988ebf26a6fafadf9b815d4
fontGenerator/util.py
fontGenerator/util.py
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( path, "w" ) as f: f.write(data) f.close() def read_by_base64(path): f = open(path, "r") data = f.read() f.close() return base64.b64encode(data) def delete_file(path): os.remove(path) def delete_files(paths): for path in paths: delete_file(path)
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( path, "w" ) as f: f.write(data) f.close() def read_by_base64(path): with open(path, "r") as f: data = f.read() f.close() return base64.b64encode(data) def delete_file(path): os.remove(path) def delete_files(paths): for path in paths: delete_file(path)
Use `with` syntax to open file
Use `with` syntax to open file
Python
mit
eHanlin/font-generator,eHanlin/font-generator
--- +++ @@ -16,9 +16,9 @@ f.close() def read_by_base64(path): - f = open(path, "r") - data = f.read() - f.close() + with open(path, "r") as f: + data = f.read() + f.close() return base64.b64encode(data)
c43e6a69fa1391b5fd00a43628111f8d52ec8792
pct_vs_time.py
pct_vs_time.py
from deuces.deuces import Card, Deck from convenience import who_wins p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] win_record = [] for i in range(100000): deck = Deck() b = [] while len(b) < 5: c = deck.draw() if c in p1 or c in p2: continue b.append(c) win_record.append(who_wins(b, p1, p2, printout = False)) Card.print_pretty_cards(p1) print win_record.count(1) / float(len(win_record)) Card.print_pretty_cards(p2) print win_record.count(2) / float(len(win_record))
from deuces.deuces import Card, Deck from convenience import who_wins, pr from copy import deepcopy p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] def find_pcts(p1, p2, start_b = [], iter = 10000): win_record = [] for i in range(iter): deck = Deck() b = deepcopy(start_b) while len(b) < 5: c = deck.draw() if c in p1 + p2 + b: continue b.append(c) win_record.append(who_wins(b, p1, p2, printout = False)) return [win_record.count(1) / float(len(win_record)), win_record.count(2) / float(len(win_record)) ] Card.print_pretty_cards(p1) Card.print_pretty_cards(p2) print find_pcts(p1, p2)
Make find_pcts() function that can repetitively run.
Make find_pcts() function that can repetitively run.
Python
mit
zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments
--- +++ @@ -1,21 +1,25 @@ from deuces.deuces import Card, Deck -from convenience import who_wins +from convenience import who_wins, pr +from copy import deepcopy p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] -win_record = [] -for i in range(100000): - deck = Deck() - b = [] - while len(b) < 5: - c = deck.draw() - if c in p1 or c in p2: - continue - b.append(c) - win_record.append(who_wins(b, p1, p2, printout = False)) +def find_pcts(p1, p2, start_b = [], iter = 10000): + win_record = [] + for i in range(iter): + deck = Deck() + b = deepcopy(start_b) + while len(b) < 5: + c = deck.draw() + if c in p1 + p2 + b: + continue + b.append(c) + win_record.append(who_wins(b, p1, p2, printout = False)) + return [win_record.count(1) / float(len(win_record)), + win_record.count(2) / float(len(win_record)) + ] Card.print_pretty_cards(p1) -print win_record.count(1) / float(len(win_record)) Card.print_pretty_cards(p2) -print win_record.count(2) / float(len(win_record)) +print find_pcts(p1, p2)
89a9d812f68fee1bda300be853cdf9536da6ba6b
pelicanconf.py
pelicanconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'Glowstone Organization' SITENAME = 'Glowstone' SITEURL = '' PATH = 'content' TIMEZONE = 'UTC' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None THEME = "theme" # Blogroll LINKS = (('Pelican', 'https://getpelican.com/'), ('Python.org', 'https://www.python.org/'), ('Jinja2', 'https://palletsprojects.com/p/jinja/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'Glowstone Organization' SITENAME = 'Glowstone' SITEURL = '' PATH = 'content' PAGE_PATHS = [''] PAGE_URL = '{slug}/' PAGE_SAVE_AS = '{slug}/index.html' TIMEZONE = 'UTC' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None THEME = "theme" # Blogroll LINKS = (('Pelican', 'https://getpelican.com/'), ('Python.org', 'https://www.python.org/'), ('Jinja2', 'https://palletsprojects.com/p/jinja/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
Move pages to root URL
Move pages to root URL Fixes #1
Python
artistic-2.0
GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io
--- +++ @@ -6,6 +6,10 @@ SITEURL = '' PATH = 'content' + +PAGE_PATHS = [''] +PAGE_URL = '{slug}/' +PAGE_SAVE_AS = '{slug}/index.html' TIMEZONE = 'UTC'
0292bf82de87483ec0391ecd580e93f42bf6a95b
more/jinja2/main.py
more/jinja2/main.py
import os import morepath import jinja2 class Jinja2App(morepath.App): pass @Jinja2App.setting_section(section='jinja2') def get_setting_section(): return { 'auto_reload': False, 'autoescape': True, 'extensions': ['jinja2.ext.autoescape'] } @Jinja2App.template_engine(extension='.jinja2') def get_jinja2_render(path, original_render, settings): config = settings.jinja2.__dict__ # XXX creates a new environment and loader each time, # which could slow startup somewhat dirpath, filename = os.path.split(path) environment = jinja2.Environment( loader=jinja2.FileSystemLoader(dirpath), **config) template = environment.get_template(filename) def render(content, request): variables = {'request': request} variables.update(content) return original_render(template.render(**variables), request) return render
import os import morepath import jinja2 class Jinja2App(morepath.App): pass @Jinja2App.setting_section(section='jinja2') def get_setting_section(): return { 'auto_reload': False, 'autoescape': True, 'extensions': ['jinja2.ext.autoescape'] } @Jinja2App.template_engine(extension='.jinja2') def get_jinja2_render(path, original_render, settings): config = settings.jinja2.__dict__ # XXX creates a new environment and loader each time, # which could slow startup somewhat # XXX and probably breaks caching if you have one template inherit # from another dirpath, filename = os.path.split(path) environment = jinja2.Environment( loader=jinja2.FileSystemLoader(dirpath), **config) template = environment.get_template(filename) def render(content, request): variables = {'request': request} variables.update(content) return original_render(template.render(**variables), request) return render
Add another note about caching.
Add another note about caching.
Python
bsd-3-clause
morepath/more.jinja2
--- +++ @@ -21,6 +21,8 @@ config = settings.jinja2.__dict__ # XXX creates a new environment and loader each time, # which could slow startup somewhat + # XXX and probably breaks caching if you have one template inherit + # from another dirpath, filename = os.path.split(path) environment = jinja2.Environment( loader=jinja2.FileSystemLoader(dirpath),
82b517426804e9e6984317f4b3aa5bbda5e3dc5e
tests/qctests/test_density_inversion.py
tests/qctests/test_density_inversion.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check density inversion QC test """ from numpy import ma from cotede.qctests import density_inversion def test(): dummy_data = { 'PRES': ma.masked_array([0.0, 100, 5000]), 'TEMP': ma.masked_array([25.18, 19.73, 2.13]), 'PSAL': ma.masked_array([36.00, 34.74, 34.66]) } cfg = { 'threshold': -0.03, 'flag_good': 1, 'flag_bad': 4 } f, x = density_inversion(dummy_data, cfg, saveaux=True) assert (f == [0,4,4]).all()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check density inversion QC test """ from numpy import ma from cotede.qctests import density_inversion def test(): try: import gsw except: print('GSW package not available. Can\'t run density_inversion test.') return dummy_data = { 'PRES': ma.masked_array([0.0, 100, 5000]), 'TEMP': ma.masked_array([25.18, 19.73, 2.13]), 'PSAL': ma.masked_array([36.00, 34.74, 34.66]) } cfg = { 'threshold': -0.03, 'flag_good': 1, 'flag_bad': 4 } f, x = density_inversion(dummy_data, cfg, saveaux=True) assert (f == [0,4,4]).all()
Exit density inversion test if gsw is not available.
Exit density inversion test if gsw is not available.
Python
bsd-3-clause
castelao/CoTeDe
--- +++ @@ -10,6 +10,12 @@ def test(): + try: + import gsw + except: + print('GSW package not available. Can\'t run density_inversion test.') + return + dummy_data = { 'PRES': ma.masked_array([0.0, 100, 5000]), 'TEMP': ma.masked_array([25.18, 19.73, 2.13]),
053239698dcb0842a8c8fcc019092c65b7f436e7
spec_cleaner/rpmbuild.py
spec_cleaner/rpmbuild.py
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): line = self.embrace_macros(line) line = self.reg.re_jobs.sub('%{?_smp_mflags}', line) # add jobs if we have just make call on line # if user want single thread he should specify -j1 if line.startswith('make'): # if there are no smp_flags or jobs spec just append it if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting if not line.endswith('\\'): line = '{0} {1}'.format(line, '%{?_smp_mflags}') # if user uses cmake directly just recommend him using the macros if line.startswith('cmake'): self.lines.append('# FIXME: you should use %cmake macros') Section.add(self, line)
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): line = self.embrace_macros(line) line = self.reg.re_jobs.sub('%{?_smp_mflags}', line) # add jobs if we have just make call on line # if user want single thread he should specify -j1 if line.startswith('make'): # if there are no smp_flags or jobs spec just append it if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting if not line.endswith('\\') and not '||' in line: line = '{0} {1}'.format(line, '%{?_smp_mflags}') # if user uses cmake directly just recommend him using the macros if line.startswith('cmake'): self.lines.append('# FIXME: you should use %cmake macros') Section.add(self, line)
Fix parsing make with || on line.
Fix parsing make with || on line.
Python
bsd-3-clause
pombredanne/spec-cleaner,pombredanne/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner
--- +++ @@ -23,7 +23,7 @@ if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting - if not line.endswith('\\'): + if not line.endswith('\\') and not '||' in line: line = '{0} {1}'.format(line, '%{?_smp_mflags}') # if user uses cmake directly just recommend him using the macros
a6491e62201e070665020e8e123d1cd65fc2cca6
Examples/THINGS/submit_all_THINGS.py
Examples/THINGS/submit_all_THINGS.py
import os ''' Submits a job for every sample defined in the info dict ''' script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) # Now submit it! os.system("qsub -v INP={1} {0}".format(submit_file, galaxy_path))
import os from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' def timestring(): return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lustre/home/ekoch/THINGS/" for name in galaxy_props: galaxy_path = os.path.join(datapath, name) now_time = timestring() error_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) output_file = \ os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, galaxy_path, error_file, output_file))
Write the error and output files with the galaxy name and in the right folder
Write the error and output files with the galaxy name and in the right folder
Python
mit
e-koch/BaSiCs
--- +++ @@ -1,9 +1,14 @@ import os +from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' + + +def timestring(): + return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" @@ -16,5 +21,13 @@ for name in galaxy_props: galaxy_path = os.path.join(datapath, name) + now_time = timestring() + error_file = \ + os.path.join(galaxy_path, "{0}_bubbles_{1}.err".format(name, now_time)) + output_file = \ + os.path.join(galaxy_path, "{0}_bubbles_{1}.out".format(name, now_time)) # Now submit it! - os.system("qsub -v INP={1} {0}".format(submit_file, galaxy_path)) + os.system("qsub -e {2} -o {3} -v INP={1} {0}".format(submit_file, + galaxy_path, + error_file, + output_file))
ad68b5f75bc58f467ba92be6b8835bad60bcbcd5
common/http.py
common/http.py
# -*- coding: utf-8 -*- from django.template import RequestContext, loader from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden # A custom Http403 exception # from http://theglenbot.com/creating-a-custom-http403-exception-in-django/ class Http403(Exception): pass def render_to_403(*args, **kwargs): if not isinstance(args,list): args = [] args.append('403.html') httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} response = HttpResponseForbidden(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) return response class Http403Middleware(object): def process_exception(self,request,exception): if isinstance(exception,Http403): if getattr(settings, 'DEBUG'): raise PermissionDenied return render_to_403(context_instance=RequestContext(request))
# -*- coding: utf-8 -*- from django.template import RequestContext, loader from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden # A custom Http403 exception # from http://theglenbot.com/creating-a-custom-http403-exception-in-django/ class Http403(Exception): pass def render_to_403(*args, **kwargs): if not isinstance(args,list): args = [] args.append('403.html') httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} response = HttpResponseForbidden(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) return response class Http403Middleware(object): def process_exception(self,request,exception): if isinstance(exception,Http403): if getattr(settings, 'DEBUG'): raise PermissionDenied return render_to_403(context_instance=RequestContext(request))
Update mimetype to content_type here, too.
common: Update mimetype to content_type here, too.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -16,7 +16,7 @@ args = [] args.append('403.html') - httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} + httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} response = HttpResponseForbidden(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) return response
8db9ab08725ebbdb3a9b5a70b1f8071433b01a04
data/models.py
data/models.py
""" The data models """ class Repository(object): def __init__(self, base_url, identifier): self.base_url = base_url self.identifier = identifier class GitObject(object): def __init__(self, sha1): self.sha1 = sha1 class Blog(Object): @property def commits(self): pass class Tree(Object): @property def commits(self): pass class Commit(Object): @property def repositories(self): pass
""" The data models """ class Repository(object): def __init__(self, base_url, identifier): self.base_url = base_url self.identifier = identifier class GitObject(object): def __init__(self, sha1): self.sha1 = sha1 class Blog(GitObject): @property def commits(self): pass class Tree(GitObject): @property def commits(self): pass class Commit(GitObject): @property def repositories(self): pass
Replace Object everywhere, not just the class definition.
Replace Object everywhere, not just the class definition.
Python
mit
ebroder/anygit,ebroder/anygit
--- +++ @@ -11,17 +11,17 @@ def __init__(self, sha1): self.sha1 = sha1 -class Blog(Object): +class Blog(GitObject): @property def commits(self): pass -class Tree(Object): +class Tree(GitObject): @property def commits(self): pass -class Commit(Object): +class Commit(GitObject): @property def repositories(self): pass
443cc0114d7669471e39661c97e2bad91c8eabb8
tests/basics/set_difference.py
tests/basics/set_difference.py
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s))
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) s.difference_update(s) print(s)
Add test for set.difference_update with arg being itself.
tests/basics: Add test for set.difference_update with arg being itself.
Python
mit
blazewicz/micropython,tobbad/micropython,tuc-osg/micropython,henriknelson/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,ryannathans/micropython,Timmenem/micropython,alex-robbins/micropython,PappaPeppar/micropython,dxxb/micropython,Peetz0r/micropython-esp32,jmarcelino/pycom-micropython,hiway/micropython,cwyark/micropython,pramasoul/micropython,lowRISC/micropython,jmarcelino/pycom-micropython,trezor/micropython,selste/micropython,dmazzella/micropython,HenrikSolver/micropython,alex-march/micropython,tralamazza/micropython,hosaka/micropython,deshipu/micropython,alex-march/micropython,SHA2017-badge/micropython-esp32,chrisdearman/micropython,hiway/micropython,pramasoul/micropython,bvernoux/micropython,Peetz0r/micropython-esp32,torwag/micropython,pramasoul/micropython,ryannathans/micropython,dxxb/micropython,tuc-osg/micropython,deshipu/micropython,adafruit/circuitpython,ryannathans/micropython,puuu/micropython,TDAbboud/micropython,oopy/micropython,HenrikSolver/micropython,AriZuu/micropython,kerneltask/micropython,oopy/micropython,mhoffma/micropython,blazewicz/micropython,micropython/micropython-esp32,infinnovation/micropython,blazewicz/micropython,pozetroninc/micropython,SHA2017-badge/micropython-esp32,Peetz0r/micropython-esp32,puuu/micropython,dmazzella/micropython,alex-march/micropython,tralamazza/micropython,alex-robbins/micropython,AriZuu/micropython,toolmacher/micropython,PappaPeppar/micropython,swegener/micropython,pramasoul/micropython,trezor/micropython,puuu/micropython,Timmenem/micropython,tobbad/micropython,tuc-osg/micropython,alex-march/micropython,MrSurly/micropython-esp32,kerneltask/micropython,puuu/micropython,dmazzella/micropython,hosaka/micropython,adafruit/micropython,pfalcon/micropython,pozetroninc/micropython,MrSurly/micropython-esp32,selste/micropython,selste/micropython,adafruit/circuitpython,infinnovation/micropython,henriknelson/micropython,ryannathans/micropython,tobbad/micropython,HenrikSolver/micropython,hosaka/micropython,matthewelse/micropython,adafruit/circuitpython,AriZuu/micropython,matthewelse/micropython,mhoffma/micropython,dxxb/micropython,kerneltask/micropython,SHA2017-badge/micropython-esp32,hiway/micropython,tralamazza/micropython,selste/micropython,toolmacher/micropython,turbinenreiter/micropython,dxxb/micropython,deshipu/micropython,cwyark/micropython,hosaka/micropython,swegener/micropython,Timmenem/micropython,pfalcon/micropython,ryannathans/micropython,bvernoux/micropython,kerneltask/micropython,bvernoux/micropython,torwag/micropython,cwyark/micropython,cwyark/micropython,chrisdearman/micropython,infinnovation/micropython,tuc-osg/micropython,dmazzella/micropython,alex-march/micropython,micropython/micropython-esp32,jmarcelino/pycom-micropython,mhoffma/micropython,hiway/micropython,TDAbboud/micropython,lowRISC/micropython,chrisdearman/micropython,MrSurly/micropython,alex-robbins/micropython,selste/micropython,adafruit/micropython,tobbad/micropython,swegener/micropython,deshipu/micropython,micropython/micropython-esp32,mhoffma/micropython,tuc-osg/micropython,Timmenem/micropython,turbinenreiter/micropython,lowRISC/micropython,PappaPeppar/micropython,tobbad/micropython,MrSurly/micropython-esp32,HenrikSolver/micropython,jmarcelino/pycom-micropython,pozetroninc/micropython,toolmacher/micropython,adafruit/micropython,TDAbboud/micropython,lowRISC/micropython,torwag/micropython,adafruit/micropython,pozetroninc/micropython,swegener/micropython,pfalcon/micropython,bvernoux/micropython,deshipu/micropython,adafruit/circuitpython,MrSurly/micropython-esp32,PappaPeppar/micropython,blazewicz/micropython,mhoffma/micropython,oopy/micropython,MrSurly/micropython,jmarcelino/pycom-micropython,pramasoul/micropython,chrisdearman/micropython,toolmacher/micropython,MrSurly/micropython,blazewicz/micropython,puuu/micropython,toolmacher/micropython,hosaka/micropython,torwag/micropython,swegener/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,henriknelson/micropython,AriZuu/micropython,adafruit/circuitpython,matthewelse/micropython,tralamazza/micropython,matthewelse/micropython,Timmenem/micropython,matthewelse/micropython,HenrikSolver/micropython,adafruit/circuitpython,torwag/micropython,kerneltask/micropython,infinnovation/micropython,turbinenreiter/micropython,adafruit/micropython,trezor/micropython,oopy/micropython,hiway/micropython,oopy/micropython,pfalcon/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,MrSurly/micropython,MrSurly/micropython,alex-robbins/micropython,TDAbboud/micropython,dxxb/micropython,SHA2017-badge/micropython-esp32,turbinenreiter/micropython,turbinenreiter/micropython,pozetroninc/micropython,Peetz0r/micropython-esp32,pfalcon/micropython,matthewelse/micropython,trezor/micropython,henriknelson/micropython,lowRISC/micropython,infinnovation/micropython,micropython/micropython-esp32,bvernoux/micropython,AriZuu/micropython,PappaPeppar/micropython,trezor/micropython,alex-robbins/micropython,TDAbboud/micropython
--- +++ @@ -14,3 +14,6 @@ print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) + +s.difference_update(s) +print(s)
9a4afbab2aded6e6e0ad1088f8cc2d92cfd7684a
26-lazy-rivers/tf-26.py
26-lazy-rivers/tf-26.py
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): # We found the start of a word word = c.lower() start_char = False else: pass else: if c.isalnum(): word += c.lower() else: # We found end of word, emit it start_char = True yield word def non_stop_words(filename): stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase)) for w in all_words(filename): if not w in stopwords: yield w def count_and_sort(filename): freqs = {} for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 return sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) # # The main function # word_freqs = count_and_sort(sys.argv[1]) for (w, c) in word_freqs[0:25]: print w, ' - ', c
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): # We found the start of a word word = c.lower() start_char = False else: pass else: if c.isalnum(): word += c.lower() else: # We found end of word, emit it start_char = True yield word def non_stop_words(filename): stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase)) for w in all_words(filename): if not w in stopwords: yield w def count_and_sort(filename): freqs, i = {}, 1 for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 if i % 5000 == 0: yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) i = i+1 yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) # # The main function # for word_freqs in count_and_sort(sys.argv[1]): print "-----------------------------" for (w, c) in word_freqs[0:25]: print w, ' - ', c
Make the last function also a generator, so that the explanation flows better
Make the last function also a generator, so that the explanation flows better
Python
mit
alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style
--- +++ @@ -31,15 +31,18 @@ yield w def count_and_sort(filename): - freqs = {} + freqs, i = {}, 1 for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 - return sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) - + if i % 5000 == 0: + yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) + i = i+1 + yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) # # The main function # -word_freqs = count_and_sort(sys.argv[1]) -for (w, c) in word_freqs[0:25]: - print w, ' - ', c +for word_freqs in count_and_sort(sys.argv[1]): + print "-----------------------------" + for (w, c) in word_freqs[0:25]: + print w, ' - ', c
6c2354a1e56477eb983b0adbcc2d15223c158184
foodsaving/subscriptions/consumers.py
foodsaving/subscriptions/consumers.py
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) message.reply_channel.send({"accept": True}) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() message.reply_channel.send({"accept": True})
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete()
Remove redundant ws accept replies
Remove redundant ws accept replies It's only relevent on connection
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
--- +++ @@ -20,7 +20,6 @@ if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) - message.reply_channel.send({"accept": True}) @channel_session_user @@ -29,4 +28,3 @@ user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() - message.reply_channel.send({"accept": True})
9f76a0a673b83b2de6a5f8a37b0628796da4a88c
tests/hello/hello/__init__.py
tests/hello/hello/__init__.py
import pkg_resources version = pkg_resources.require(__name__)[0].version def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
import pkg_resources try: version = pkg_resources.require(__name__)[0].version except: version = 'unknown' def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
Allow 'hello' test package to be used unpackaged
Allow 'hello' test package to be used unpackaged
Python
apache-2.0
comoyo/python-transmute
--- +++ @@ -1,6 +1,7 @@ import pkg_resources -version = pkg_resources.require(__name__)[0].version +try: version = pkg_resources.require(__name__)[0].version +except: version = 'unknown' def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
8d5ac7efd98426394040fb01f0096f35a804b1b7
tests/plugins/test_generic.py
tests/plugins/test_generic.py
import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from .utils import create_har_entry class TestGenericPlugin(object): @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class MyGenericPlugin(GenericPlugin): pass x = MyGenericPlugin() with pytest.raises(NotImplementedError): x.get_information(entry=None) assert x.ptype == 'generic' @pytest.mark.parametrize('plugin_name,indicator,name', [ ( 'wordpress_generic', {'url': 'http://domain.tld/wp-content/plugins/example/'}, 'example', ) ]) def test_real_generic_plugin(self, plugin_name, indicator, name, plugins): plugin = plugins.get(plugin_name) matcher_type = [k for k in indicator.keys()][0] har_entry = create_har_entry(indicator, matcher_type) matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators') # Call presence method in related matcher class matcher_instance = MATCHERS[matcher_type] assert matcher_instance.check_presence(har_entry, *matchers_in_plugin) assert plugin.get_information(har_entry)['name'] == name
import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from tests import create_pm from .utils import create_har_entry class TestGenericPlugin: @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class MyGenericPlugin(GenericPlugin): pass x = MyGenericPlugin() with pytest.raises(NotImplementedError): x.get_information(entry=None) assert x.ptype == 'generic' @pytest.mark.parametrize( 'plugin_name,matcher_type,har_content,name', [( 'wordpress_generic', 'url', 'http://domain.tld/wp-content/plugins/example/', 'example', )] ) def test_real_generic_plugin( self, plugin_name, matcher_type, har_content, name, plugins ): plugin = plugins.get(plugin_name) har_entry = create_har_entry(matcher_type, value=har_content) # Verify presence using matcher class matchers = plugin.get_matchers(matcher_type) matcher_instance = MATCHERS[matcher_type] assert matcher_instance.get_info( har_entry, *matchers, ) == create_pm(presence=True) assert plugin.get_information(har_entry)['name'] == name
Fix test for generic plugins
Fix test for generic plugins
Python
mit
spectresearch/detectem
--- +++ @@ -2,10 +2,11 @@ from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin +from tests import create_pm from .utils import create_har_entry -class TestGenericPlugin(object): +class TestGenericPlugin: @pytest.fixture def plugins(self): return load_plugins() @@ -20,22 +21,27 @@ assert x.ptype == 'generic' - @pytest.mark.parametrize('plugin_name,indicator,name', [ - ( + @pytest.mark.parametrize( + 'plugin_name,matcher_type,har_content,name', [( 'wordpress_generic', - {'url': 'http://domain.tld/wp-content/plugins/example/'}, + 'url', + 'http://domain.tld/wp-content/plugins/example/', 'example', - ) - ]) - def test_real_generic_plugin(self, plugin_name, indicator, name, plugins): + )] + ) + def test_real_generic_plugin( + self, plugin_name, matcher_type, har_content, name, plugins + ): plugin = plugins.get(plugin_name) - matcher_type = [k for k in indicator.keys()][0] + har_entry = create_har_entry(matcher_type, value=har_content) - har_entry = create_har_entry(indicator, matcher_type) - matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators') + # Verify presence using matcher class + matchers = plugin.get_matchers(matcher_type) + matcher_instance = MATCHERS[matcher_type] - # Call presence method in related matcher class - matcher_instance = MATCHERS[matcher_type] - assert matcher_instance.check_presence(har_entry, *matchers_in_plugin) + assert matcher_instance.get_info( + har_entry, + *matchers, + ) == create_pm(presence=True) assert plugin.get_information(har_entry)['name'] == name
a33ccab017bd6dfab03e12242c7e1306b47b2bed
seed_stage_based_messaging/testsettings.py
seed_stage_based_messaging/testsettings.py
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' SCHEDULER_URL = "http://seed-scheduler/api/v1" SCHEDULER_API_TOKEN = "REPLACEME" IDENTITY_STORE_URL = "http://seed-identity-store/api/v1" IDENTITY_STORE_TOKEN = "REPLACEME" MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1" MESSAGE_SENDER_TOKEN = "REPLACEME" METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME"
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' SCHEDULER_URL = "http://seed-scheduler/api/v1" SCHEDULER_API_TOKEN = "REPLACEME" IDENTITY_STORE_URL = "http://seed-identity-store/api/v1" IDENTITY_STORE_TOKEN = "REPLACEME" MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1" MESSAGE_SENDER_TOKEN = "REPLACEME" METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME" PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
Change password hasher for tests for faster tests
Change password hasher for tests for faster tests
Python
bsd-3-clause
praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-staged-based-messaging
--- +++ @@ -24,3 +24,5 @@ METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME" + +PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
ade69178edac1d4d73dedee0ad933d4106e22c82
knox/crypto.py
knox/crypto.py
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from OpenSSL.rand import bytes as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hexlify( generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2)) ).decode() def create_salt_string(): return binascii.hexlify( generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode() def hash_token(token, salt): ''' Calculates the hash of a token and salt. input is unhexlified ''' digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(binascii.unhexlify(salt)) return binascii.hexlify(digest.finalize()).decode()
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from os import urandom as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hexlify( generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2)) ).decode() def create_salt_string(): return binascii.hexlify( generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode() def hash_token(token, salt): ''' Calculates the hash of a token and salt. input is unhexlified ''' digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(binascii.unhexlify(salt)) return binascii.hexlify(digest.finalize()).decode()
Use os.urandom instead of OpenSSL.rand.bytes
Use os.urandom instead of OpenSSL.rand.bytes Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
Python
mit
James1345/django-rest-knox,James1345/django-rest-knox
--- +++ @@ -2,7 +2,7 @@ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes -from OpenSSL.rand import bytes as generate_bytes +from os import urandom as generate_bytes from knox.settings import knox_settings, CONSTANTS
d0ca3952a34a74f0167b76bbedfa3cf8875a399c
var/spack/repos/builtin/packages/py-scikit-learn/package.py
var/spack/repos/builtin/packages/py-scikit-learn/package.py
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
Add version 0.17.1 of scikit-learn.
Add version 0.17.1 of scikit-learn.
Python
lgpl-2.1
matthiasdiener/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spack,iulian787/spack,iulian787/spack,iulian787/spack,mfherbst/spack,tmerrick1/spack,mfherbst/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,mfherbst/spack,lgarren/spack,LLNL/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,krafczyk/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,krafczyk/spack,iulian787/spack,lgarren/spack,tmerrick1/spack,EmreAtes/spack,EmreAtes/spack,krafczyk/spack,lgarren/spack,matthiasdiener/spack,lgarren/spack,iulian787/spack,LLNL/spack,lgarren/spack,skosukhin/spack,krafczyk/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,EmreAtes/spack,tmerrick1/spack
--- +++ @@ -7,6 +7,7 @@ version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') + version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python')
1d017e9e07e48a8a1960de4c16fd49b4b40abbc2
ldap-helper.py
ldap-helper.py
# Handles queries to the LDAP backend # Reads the LDAP server configuration from a JSON file import json import ldap first_connect = True # The default config filename config_file = 'config.json' def load_config(): with open(config_file, 'r') as f: config = json.load(f) ldap_server = config['ldap_server'] ldap_version = config['ldap_version'] ldap_password = config['ldap_password'] ldap_user = config['ldap_user'] def connect(): if first_connect: load_config() first_connect = False l = ldap.initialize('ldap://' + ldap_server) try: l.protocol_version = ldap.VERSION3 # parse this from config instead l.simple_bind_s(ldap_user, ldap_password) valid = True except ldap.INVALID_CREDENTIALS: print "Invalid login credentials" sys.exit(-1) except ldap.LDAPError, e: if type(e.message) == dict and e.message.has_key('desc'): print e.message['desc'] else: print e sys.exit(-2)
# Handles queries to the LDAP backend # Reads the LDAP server configuration from a JSON file import json import ldap first_connect = True # The default config filename config_file = 'config.json' def load_config(): with open(config_file, 'r') as f: config = json.load(f) ldap_server = config['ldap_server'] ldap_version = config['ldap_version'] ldap_password = config['ldap_password'] ldap_user = config['ldap_user'] def connect(): if first_connect: load_config() first_connect = False l = ldap.initialize('ldap://' + ldap_server) try: l.protocol_version = ldap_version l.simple_bind_s(ldap_user, ldap_password) valid = True except ldap.INVALID_CREDENTIALS: print "Invalid login credentials" sys.exit(-1) except ldap.LDAPError, e: if type(e.message) == dict and e.message.has_key('desc'): print e.message['desc'] else: print e sys.exit(-2)
Add LDAP version to depend on config instead
Add LDAP version to depend on config instead
Python
mit
motorolja/ldap-updater
--- +++ @@ -22,7 +22,7 @@ first_connect = False l = ldap.initialize('ldap://' + ldap_server) try: - l.protocol_version = ldap.VERSION3 # parse this from config instead + l.protocol_version = ldap_version l.simple_bind_s(ldap_user, ldap_password) valid = True except ldap.INVALID_CREDENTIALS:
2a241bd07a4abd66656e3fb505310798f398db7f
respawn/cli.py
respawn/cli.py
""" CLI Entry point for respawn """ from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --help respawn --version Options: --help This usage information --version Package version """ version = require("respawn")[0].version args = docopt(generate.__doc__, version=version) scheme = Schema({ '<yaml>': Use(str), '--help': Or(True, False), '--version': Or(True, False), }) args = scheme.validate(args) gen_location = "/".join(respawn.__file__.split("/")[:-1]) + "/gen.py" print gen_location try: check_call(["cfn_py_generate", gen_location, "-o", args['<yaml>']]) return 0 except CalledProcessError, e: return 1
""" CLI Entry point for respawn """ from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn import os def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --help respawn --version Options: --help This usage information --version Package version """ version = require("respawn")[0].version args = docopt(generate.__doc__, version=version) scheme = Schema({ '<yaml>': Use(str), '--help': Or(True, False), '--version': Or(True, False), }) args = scheme.validate(args) # The pyplates library takes a python script that specifies options # that is not in scope. As a result, the file cannot be imported, so # the path of the library is used and gen.py is appended gen_location = os.path.join(os.path.dirname(respawn.__file__), "gen.py") try: check_call(["cfn_py_generate", gen_location, "-o", args['<yaml>']]) return 0 except CalledProcessError: return 1
Remove test print and use better practice to get path of gen.py
Remove test print and use better practice to get path of gen.py
Python
isc
dowjones/respawn,dowjones/respawn
--- +++ @@ -7,6 +7,7 @@ from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn +import os def generate(): @@ -32,11 +33,13 @@ }) args = scheme.validate(args) - gen_location = "/".join(respawn.__file__.split("/")[:-1]) + "/gen.py" - print gen_location + # The pyplates library takes a python script that specifies options + # that is not in scope. As a result, the file cannot be imported, so + # the path of the library is used and gen.py is appended + gen_location = os.path.join(os.path.dirname(respawn.__file__), "gen.py") try: check_call(["cfn_py_generate", gen_location, "-o", args['<yaml>']]) return 0 - except CalledProcessError, e: + except CalledProcessError: return 1
6795e8f5c97ba2f10d05725faf4999cfba785fdd
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): assert host.service("mongod").is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': mongodb_service_name = 'mongodb' else: mongodb_service_name = 'mongod' assert host.service(mongodb_service_name).is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
Fix test in Ubuntu 20.04.
Fix test in Ubuntu 20.04.
Python
apache-2.0
Graylog2/graylog-ansible-role
--- +++ @@ -2,14 +2,18 @@ import testinfra.utils.ansible_runner -testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( - os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') +testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): - assert host.service("mongod").is_running is True + if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': + mongodb_service_name = 'mongodb' + else: + mongodb_service_name = 'mongod' + + assert host.service(mongodb_service_name).is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed
4d406f3e0caf19c8cc935e4ebec4d2df3e41df19
l10n_ch_payment_slip/__manifest__.py
l10n_ch_payment_slip/__manifest__.py
# -*- coding: utf-8 -*- # © 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com', 'license': 'AGPL-3', 'depends': [ 'base', 'account', 'report', 'l10n_ch_base_bank', 'base_transaction_id', # OCA/bank-statement-reconcile ], 'data': [ "views/company.xml", "views/bank.xml", "views/account_invoice.xml", "wizard/bvr_batch_print.xml", "wizard/bvr_import_view.xml", "report/report_declaration.xml", "security/ir.model.access.csv" ], 'demo': [], 'test': [], 'auto_install': False, 'installable': False, 'images': [] }
# -*- coding: utf-8 -*- # © 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', 'version': '11.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com', 'license': 'AGPL-3', 'depends': [ 'base', 'account', 'report', 'l10n_ch_base_bank', 'base_transaction_id', # OCA/bank-statement-reconcile ], 'data': [ "views/company.xml", "views/bank.xml", "views/account_invoice.xml", "wizard/bvr_batch_print.xml", "wizard/bvr_import_view.xml", "report/report_declaration.xml", "security/ir.model.access.csv" ], 'demo': [], 'test': [], 'auto_install': False, 'installable': False, 'images': [] }
Change l10n_ch_payment_slip version to v 11.0
Change l10n_ch_payment_slip version to v 11.0
Python
agpl-3.0
brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland
--- +++ @@ -3,7 +3,7 @@ # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', - 'version': '10.0.1.1.1', + 'version': '11.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com',
c830d67e6b640791e1a8d9117c75ca146ea5d6c8
spyral/core.py
spyral/core.py
import spyral import pygame def init(): spyral.event.init() pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
import spyral import pygame _inited = False def init(): global _inited if _inited: return _inited = True spyral.event.init() pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
Remove poor way of doing default styles
Remove poor way of doing default styles Signed-off-by: Robert Deaton <eb00a885478926d5d594195591fb94a03acb1062@udel.edu>
Python
lgpl-2.1
platipy/spyral
--- +++ @@ -1,12 +1,17 @@ import spyral import pygame +_inited = False + def init(): + global _inited + if _inited: + return + _inited = True spyral.event.init() pygame.init() pygame.font.init() - def quit(): pygame.quit() spyral.director._stack = []
6bfe3ee375847d9a71181d618732d747614aede4
electro/api.py
electro/api.py
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch_all_404s def add_resource(self, resource, *urls, **kw): endpoint = kw.pop('endpoint', None) or resource.__name__.lower() self.endpoints.add(endpoint) if endpoint in self.app.view_functions: previous_view_class = self.app.view_functions[endpoint].__dict__['view_class'] if previous_view_class != resource: raise ResourceDuplicatedDefinedError, "already set" resource.endpoint = endpoint resource_func = resource.as_view(endpoint) for decorator in self.decorators: resource_func = decorator(resource_func) for url in urls: self.app.add_url_rule(url, view_func=resource_func, **kw)
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch_all_404s def add_resource(self, resource, *urls, **kw): endpoint = kw.pop('endpoint', None) or resource.__name__.lower() self.endpoints.add(endpoint) if endpoint in self.app.view_functions: previous_view_class = self.app.view_functions[endpoint].__dict__['view_class'] if previous_view_class != resource: raise ResourceDuplicatedDefinedError(endpoint) resource.endpoint = endpoint resource_func = resource.as_view(endpoint) for decorator in self.decorators: resource_func = decorator(resource_func) for url in urls: self.app.add_url_rule(url, view_func=resource_func, **kw)
Raise with endpoint when duplicated.
Raise with endpoint when duplicated.
Python
mit
soasme/electro
--- +++ @@ -18,7 +18,7 @@ if endpoint in self.app.view_functions: previous_view_class = self.app.view_functions[endpoint].__dict__['view_class'] if previous_view_class != resource: - raise ResourceDuplicatedDefinedError, "already set" + raise ResourceDuplicatedDefinedError(endpoint) resource.endpoint = endpoint resource_func = resource.as_view(endpoint)
9938f0b70e4714fb6e74deb14a751368edd5d48f
pyhn/__init__.py
pyhn/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __title__ = 'pyhn' __version__ = '0.2.7' __author__ = 'Geoffrey Lehée' __license__ = 'AGPL3' __copyright__ = 'Copyright 2014 Geoffrey Lehée'
#!/usr/bin/env python # -*- coding: utf-8 -*- __title__ = 'pyhn' __version__ = '0.2.8' __author__ = 'Geoffrey Lehée' __license__ = 'MIT' __copyright__ = 'Copyright 2015 Geoffrey Lehée'
Update license and bump to 0.2.8
Update license and bump to 0.2.8
Python
mit
toxinu/pyhn,socketubs/pyhn
--- +++ @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- __title__ = 'pyhn' -__version__ = '0.2.7' +__version__ = '0.2.8' __author__ = 'Geoffrey Lehée' -__license__ = 'AGPL3' -__copyright__ = 'Copyright 2014 Geoffrey Lehée' +__license__ = 'MIT' +__copyright__ = 'Copyright 2015 Geoffrey Lehée'
91853432d2e57bd7c01403c943fff4c2dad1cf5a
openquake/__init__.py
openquake/__init__.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake 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. # # OpenQuake 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 OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__)
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake 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. # # OpenQuake 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 OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
Make the openquake namespace compatible with old setuptools
Make the openquake namespace compatible with old setuptools Former-commit-id: b1323f4831645a19d5e927fc342abe4b319a76bb [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc] [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc [formerly e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb]] Former-commit-id: e01df405c03f37a89cdf889c45de410cb1ca9b00 Former-commit-id: f8d3b5d4c1d3d81dee1c22a4e2563e6b8d116c74
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
--- +++ @@ -16,4 +16,9 @@ # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. -__import__('pkg_resources').declare_namespace(__name__) +# Make the namespace compatible with old setuptools, like the one +# provided by QGIS 2.1x on Windows +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + __path__ = __import__('pkgutil').extend_path(__path__, __name__)
4443f6d2493ce6ff9d49cf4049c6a89d2a61eddf
cmt/printers/nc/tests/test_ugrid_read.py
cmt/printers/nc/tests/test_ugrid_read.py
import unittest import os from cmt.printers.nc.read import field_fromfile class DataTestFileMixIn(object): def data_file(self, name): return os.path.join(self.data_dir(), name) def data_dir(self): return os.path.join(os.path.dirname(__file__), 'data') class TestNetcdfRead(unittest.TestCase, DataTestFileMixIn): def test_unstructured_2d(self): field = field_fromfile(self.data_file('unstructured.2d.nc'), format='NETCDF4') def test_rectilinear_1d(self): field = field_fromfile(self.data_file('rectilinear.1d.nc'), format='NETCDF4') def test_rectilinear_2d(self): field = field_fromfile(self.data_file('rectilinear.2d.nc'), format='NETCDF4') def test_rectilinear_3d(self): field = field_fromfile(self.data_file('rectilinear.3d.nc'), format='NETCDF4')
import unittest import os import urllib2 from cmt.printers.nc.read import field_fromfile def fetch_data_file(filename): url = ('http://csdms.colorado.edu/thredds/fileServer/benchmark/ugrid/' + filename) remote_file = urllib2.urlopen(url) with open(filename, 'w') as netcdf_file: netcdf_file.write(remote_file.read()) return os.path.abspath(filename) class DataTestFileMixIn(object): def data_file(self, name): return os.path.join(self.data_dir(), name) def data_dir(self): return os.path.join(os.path.dirname(__file__), 'data') class TestNetcdfRead(unittest.TestCase, DataTestFileMixIn): def test_unstructured_2d(self): field = field_fromfile(fetch_data_file('unstructured.2d.nc'), format='NETCDF4') def test_rectilinear_1d(self): field = field_fromfile(fetch_data_file('rectilinear.1d.nc'), format='NETCDF4') def test_rectilinear_2d(self): field = field_fromfile(fetch_data_file('rectilinear.2d.nc'), format='NETCDF4') def test_rectilinear_3d(self): field = field_fromfile(fetch_data_file('rectilinear.3d.nc'), format='NETCDF4')
Read test data files from a remote URL.
Read test data files from a remote URL. Changed ------- * Instead of reading test netcdf files from a data directory in the repository, fetch them from a URL.
Python
mit
csdms/coupling,csdms/coupling,csdms/pymt
--- +++ @@ -1,7 +1,18 @@ import unittest import os +import urllib2 from cmt.printers.nc.read import field_fromfile + + +def fetch_data_file(filename): + url = ('http://csdms.colorado.edu/thredds/fileServer/benchmark/ugrid/' + + filename) + remote_file = urllib2.urlopen(url) + with open(filename, 'w') as netcdf_file: + netcdf_file.write(remote_file.read()) + + return os.path.abspath(filename) class DataTestFileMixIn(object): @@ -14,17 +25,17 @@ class TestNetcdfRead(unittest.TestCase, DataTestFileMixIn): def test_unstructured_2d(self): - field = field_fromfile(self.data_file('unstructured.2d.nc'), + field = field_fromfile(fetch_data_file('unstructured.2d.nc'), format='NETCDF4') def test_rectilinear_1d(self): - field = field_fromfile(self.data_file('rectilinear.1d.nc'), + field = field_fromfile(fetch_data_file('rectilinear.1d.nc'), format='NETCDF4') def test_rectilinear_2d(self): - field = field_fromfile(self.data_file('rectilinear.2d.nc'), + field = field_fromfile(fetch_data_file('rectilinear.2d.nc'), format='NETCDF4') def test_rectilinear_3d(self): - field = field_fromfile(self.data_file('rectilinear.3d.nc'), + field = field_fromfile(fetch_data_file('rectilinear.3d.nc'), format='NETCDF4')
62d3f84155291bf020870b618cf139d8333a04cd
example-flask-python3.6-index/app/main.py
example-flask-python3.6-index/app/main.py
import os from flask import Flask, send_file app = Flask(__name__) @app.route("/hello") def hello(): return "Hello World from Flask in a uWSGI Nginx Docker container with \ Python 3.6 (from the example template)" @app.route("/") def main(): return send_file('./static/index.html') # Everything not declared before (not a Flask route / API endpoint)... @app.route('/<path:path>') def route_frontend(path): # ...could be a static file needed by the front end that # doesn't use the `static` path (like in `<script src="bundle.js">`) file_path = './static/' + path if os.path.isfile(file_path): return send_file(file_path) # ...or should be handled by the SPA's "router" in front end else: return send_file('./static/index.html') if __name__ == "__main__": # Only for debugging while developing app.run(host='0.0.0.0', debug=True, port=80)
import os from flask import Flask, send_file app = Flask(__name__) @app.route("/hello") def hello(): return "Hello World from Flask in a uWSGI Nginx Docker container with \ Python 3.6 (from the example template)" @app.route("/") def main(): index_path = os.path.join(app.static_folder, 'index.html') return send_file(index_path) # Everything not declared before (not a Flask route / API endpoint)... @app.route('/<path:path>') def route_frontend(path): # ...could be a static file needed by the front end that # doesn't use the `static` path (like in `<script src="bundle.js">`) file_path = os.path.join(app.static_folder, path) if os.path.isfile(file_path): return send_file(file_path) # ...or should be handled by the SPA's "router" in front end else: index_path = os.path.join(app.static_folder, 'index.html') return send_file(index_path) if __name__ == "__main__": # Only for debugging while developing app.run(host='0.0.0.0', debug=True, port=80)
Update view function to keep working even when moved to a package project structure
Update view function to keep working even when moved to a package project structure
Python
apache-2.0
tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker
--- +++ @@ -12,7 +12,8 @@ @app.route("/") def main(): - return send_file('./static/index.html') + index_path = os.path.join(app.static_folder, 'index.html') + return send_file(index_path) # Everything not declared before (not a Flask route / API endpoint)... @@ -20,12 +21,13 @@ def route_frontend(path): # ...could be a static file needed by the front end that # doesn't use the `static` path (like in `<script src="bundle.js">`) - file_path = './static/' + path + file_path = os.path.join(app.static_folder, path) if os.path.isfile(file_path): return send_file(file_path) # ...or should be handled by the SPA's "router" in front end else: - return send_file('./static/index.html') + index_path = os.path.join(app.static_folder, 'index.html') + return send_file(index_path) if __name__ == "__main__":
06e96684b589def7b7adce122005ffebbf0ed7f3
python/tests/test_ambassador.py
python/tests/test_ambassador.py
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect import t_shadow import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul import t_circuitbreaker import t_knative import t_envoy_logs import t_ingress # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting import t_loadbalancer import t_lua_scripts import t_mappingtests import t_optiontests import t_plain import t_ratelimit import t_redirect #import t_shadow #import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul #import t_circuitbreaker import t_knative import t_envoy_logs import t_ingress # pytest will find this because Runner is a toplevel callable object in a file # that pytest is willing to look inside. # # Also note: # - Runner(cls) will look for variants of _every subclass_ of cls. # - Any class you pass to Runner needs to be standalone (it must have its # own manifests and be able to set up its own world). main = Runner(AmbassadorTest)
Comment out t_shadow, t_stats, and t_circuitbreaker, at Flynn's behest
Comment out t_shadow, t_stats, and t_circuitbreaker, at Flynn's behest
Python
apache-2.0
datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador
--- +++ @@ -19,14 +19,14 @@ import t_plain import t_ratelimit import t_redirect -import t_shadow -import t_stats +#import t_shadow +#import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul -import t_circuitbreaker +#import t_circuitbreaker import t_knative import t_envoy_logs import t_ingress
70458f45f3419927271f51872252834f08ef13f2
workshopvenues/venues/tests.py
workshopvenues/venues/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from .models import Address class ModelsTest(TestCase): def test_create_address(self): a = Address() a.street = '23, Test Street' a.town = 'London' a.postcode = 'xxxxx' a.country = 'UK' a.save() self.assertTrue(a.id >= 0)
Add Address model creation test case
Add Address model creation test case
Python
bsd-3-clause
andreagrandi/workshopvenues
--- +++ @@ -6,11 +6,15 @@ """ from django.test import TestCase +from .models import Address -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.assertEqual(1 + 1, 2) +class ModelsTest(TestCase): + def test_create_address(self): + a = Address() + a.street = '23, Test Street' + a.town = 'London' + a.postcode = 'xxxxx' + a.country = 'UK' + a.save() + self.assertTrue(a.id >= 0)
f267b56b46a824fa5b519a22b3026d2b3c6ee106
source/hostel_huptainer/system.py
source/hostel_huptainer/system.py
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exits program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sys.stderr)
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exit program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sys.stderr)
Make abnormal_exit docstring be in the imperative mood - pydocstyle
Make abnormal_exit docstring be in the imperative mood - pydocstyle
Python
apache-2.0
Jitsusama/hostel-huptainer
--- +++ @@ -5,7 +5,7 @@ def abnormal_exit(): - """Exits program under abnormal conditions.""" + """Exit program under abnormal conditions.""" sys.exit(1)
8dc6e5632ecbab6143e25f403022ae068fbb24a2
backend/unpp_api/settings/staging.py
backend/unpp_api/settings/staging.py
from __future__ import absolute_import from .base import * # noqa: ignore=F403 # dev overrides DEBUG = False IS_STAGING = True MEDIA_ROOT = os.path.join(BASE_DIR, '%s' % UPLOADS_DIR_NAME) STATIC_ROOT = '%s/staticserve' % BASE_DIR COMPRESS_ENABLED = True COMPRESS_OFFLINE = True
from __future__ import absolute_import from .base import * # noqa: ignore=F403 # dev overrides DEBUG = False IS_STAGING = True
Revert "trying to fix statics issue" - id didnt work
Revert "trying to fix statics issue" - id didnt work This reverts commit c1a0d920491358716315a8c6aeaa6ec475b37709.
Python
apache-2.0
unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal
--- +++ @@ -5,9 +5,3 @@ # dev overrides DEBUG = False IS_STAGING = True - -MEDIA_ROOT = os.path.join(BASE_DIR, '%s' % UPLOADS_DIR_NAME) -STATIC_ROOT = '%s/staticserve' % BASE_DIR - -COMPRESS_ENABLED = True -COMPRESS_OFFLINE = True
0d2525de51edd99b821f32b3bfd962f3d673a6e1
Instanssi/admin_store/forms.py
Instanssi/admin_store/forms.py
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'delivery_type', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',)
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',)
Remove deprecated fields from form
admin_store: Remove deprecated fields from form
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -4,7 +4,6 @@ from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem - class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): @@ -21,7 +20,6 @@ 'max', 'available', 'max_per_order', - 'delivery_type', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna')
00fc915c09e0052289fa28d7da174e44f838c15b
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console account_sid = "AC6062f793ce5918fef56b1681e6446e87" auth_token = "your_auth_token" client = Client(account_sid, auth_token) call = client.calls.create( to="+15558675310", from_="+15017122661", url="http://demo.twilio.com/docs/voice.xml" ) print(call.sid)
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) call = client.calls.create( to="+15558675310", from_="+15017122661", url="http://demo.twilio.com/docs/voice.xml" ) print(call.sid)
Use placeholder for account sid :facepalm:
Use placeholder for account sid :facepalm:
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
--- +++ @@ -2,7 +2,7 @@ from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console -account_sid = "AC6062f793ce5918fef56b1681e6446e87" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token)
2307942c6e29ae24d6d4fdc42a646e4f6843fca8
echo_client.py
echo_client.py
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) # receives and prints incoming echo response, then closes connection response = client_socket.recv(16) print response client_socket.close() if __name__ == '__main__': client(sys.argv[1])
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) buffer = 16 # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) response = client_socket.recv(16) while len(response) >= buffer: # receives and prints incoming echo response, then closes connection response += client_socket.recv(16) print response client_socket.close() if __name__ == '__main__': client(sys.argv[1])
Update client to receive packets larger than buffer
Update client to receive packets larger than buffer
Python
mit
jwarren116/network-tools,jwarren116/network-tools
--- +++ @@ -8,13 +8,16 @@ socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) + buffer = 16 # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) - # receives and prints incoming echo response, then closes connection response = client_socket.recv(16) + while len(response) >= buffer: + # receives and prints incoming echo response, then closes connection + response += client_socket.recv(16) print response client_socket.close()
ce963503cea617cb552739b49caeba450e5fb55e
backslash/api_object.py
backslash/api_object.py
class APIObject(object): def __init__(self, client, json_data): super(APIObject, self).__init__() self.client = client self._data = json_data def __eq__(self, other): if not isinstance(other, APIObject): return NotImplemented return self.client is other.client and self._data == other._data def __ne__(self, other): return not (self == other) def __getattr__(self, name): try: return self.__dict__['_data'][name] except KeyError: raise AttributeError(name) def refresh(self): prev_id = self.id self._data = self._fetch() assert self.id == prev_id return self def _fetch(self): return self.client.api.get(self.api_path, raw=True)[self._data['type']] def __repr__(self): return '<API:{data[type]}:{data[id]}>'.format(data=self._data)
class APIObject(object): def __init__(self, client, json_data): super(APIObject, self).__init__() self.client = client self._data = json_data def __eq__(self, other): if not isinstance(other, APIObject): return NotImplemented return self.client is other.client and self._data == other._data def __ne__(self, other): return not (self == other) def __getattr__(self, name): try: return self.__dict__['_data'][name] except KeyError: raise AttributeError(name) def refresh(self): prev_id = self.id self._data = self._fetch() assert self.id == prev_id return self def _fetch(self): return self.client.api.get(self.api_path, raw=True)[self._data['type']] def __repr__(self): return '<API:{data[type]}:{data[id]}>'.format(data=self._data) def without_fields(self, field_names): new_data = dict((field_name, field_value) for field_name, field_value in self._data.items() if field_name not in field_names) return type(self)(self.client, new_data)
Add without_fields method to API objects
Add without_fields method to API objects Helps with unit-testing Backslash - allowing more percise comparisons
Python
bsd-3-clause
slash-testing/backslash-python,vmalloc/backslash-python
--- +++ @@ -31,3 +31,9 @@ def __repr__(self): return '<API:{data[type]}:{data[id]}>'.format(data=self._data) + + def without_fields(self, field_names): + new_data = dict((field_name, field_value) + for field_name, field_value in self._data.items() + if field_name not in field_names) + return type(self)(self.client, new_data)
7bc736b9a31d532930e9824842f7adb84436a7b8
django_filters/rest_framework/filters.py
django_filters/rest_framework/filters.py
from ..filters import * from ..widgets import BooleanWidget class BooleanFilter(BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget) super().__init__(*args, **kwargs)
from ..filters import BooleanFilter as _BooleanFilter from ..filters import * from ..widgets import BooleanWidget class BooleanFilter(_BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget) super().__init__(*args, **kwargs)
Fix mypy error: circular inheritance
Fix mypy error: circular inheritance Closes #832, #833
Python
bsd-3-clause
alex/django-filter,alex/django-filter
--- +++ @@ -1,9 +1,10 @@ +from ..filters import BooleanFilter as _BooleanFilter from ..filters import * from ..widgets import BooleanWidget -class BooleanFilter(BooleanFilter): +class BooleanFilter(_BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget)
8d789a822a34f59d79f0e1129ab7ce5fa945a746
OctaHomeAppInterface/models.py
OctaHomeAppInterface/models.py
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import string import random import hashlib import time from authy.api import AuthyApiClient ################# # Account Model # ################# class DeviceUser(OctaBaseModel): User = models.ForeignKey('OctaHomeCore.CustomUser') Secret = models.CharField(max_length=30) def createDeviceSetupToken(self, host): self.Secret = ''.join(random.choice(string.ascii_uppercase) for i in range(30)) self.save() return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): salt = time.strftime("%H:%M-%d/%m/%Y") hashpassword = hashlib.sha512(self.Secret.encode('utf-8') + salt.encode('utf-8')).hexdigest().upper() if (hashpassword == token): return True else: return False class Meta: db_table = u'DeviceUser'
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import datetime import string import random import hashlib import time from authy.api import AuthyApiClient ################# # Account Model # ################# class DeviceUser(OctaBaseModel): User = models.ForeignKey('OctaHomeCore.CustomUser') Secret = models.CharField(max_length=30) def createDeviceSetupToken(self, host): self.Secret = ''.join(random.choice(string.ascii_uppercase) for i in range(30)) self.save() return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): salt = datetime.datetime.utcnow().strftime("%H:%M-%d/%m/%Y") hashpassword = hashlib.sha512(self.Secret.encode('utf-8') + salt.encode('utf-8')).hexdigest().upper() if (hashpassword == token): return True else: return False class Meta: db_table = u'DeviceUser'
Update to make sure the auth date is on utc for time zone support on devices
Update to make sure the auth date is on utc for time zone support on devices
Python
mit
Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation
--- +++ @@ -4,6 +4,7 @@ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * +import datetime import string import random import hashlib @@ -24,7 +25,7 @@ return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): - salt = time.strftime("%H:%M-%d/%m/%Y") + salt = datetime.datetime.utcnow().strftime("%H:%M-%d/%m/%Y") hashpassword = hashlib.sha512(self.Secret.encode('utf-8') + salt.encode('utf-8')).hexdigest().upper() if (hashpassword == token): return True
6e4daa3745cf51443550d559493a0cf8c2dbd8f1
grid_map_demos/scripts/image_publisher.py
grid_map_demos/scripts/image_publisher.py
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ img = cv2.imread(IMAGE_PATH) rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] rosimage.height = img.shape[0] rosimage.step = img.strides[0] rosimage.data = img.tostring() # rosimage.data = img.flatten().tolist() publisher.publish(rosimage) #Main function initializes node and subscribers and starts the ROS loop def main_program(): global publisher rospy.init_node('image_publisher') publisher = rospy.Publisher(IMAGE_MESSAGE_TOPIC, sensor_msgs.msg.Image, queue_size=10) rospy.Timer(rospy.Duration(0.5), callback) rospy.spin() if __name__ == '__main__': try: main_program() except rospy.ROSInterruptException: pass
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ img = cv2.imread(IMAGE_PATH, -1) rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] rosimage.height = img.shape[0] rosimage.step = img.strides[0] rosimage.data = img.tostring() # rosimage.data = img.flatten().tolist() publisher.publish(rosimage) #Main function initializes node and subscribers and starts the ROS loop def main_program(): global publisher rospy.init_node('image_publisher') publisher = rospy.Publisher(IMAGE_MESSAGE_TOPIC, sensor_msgs.msg.Image, queue_size=10) rospy.Timer(rospy.Duration(0.5), callback) rospy.spin() if __name__ == '__main__': try: main_program() except rospy.ROSInterruptException: pass
Read gray scale image with alpha channel
Read gray scale image with alpha channel
Python
bsd-3-clause
uzh-rpg/grid_map,chen0510566/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ethz-asl/grid_map,ethz-asl/grid_map,uzh-rpg/grid_map,chen0510566/grid_map
--- +++ @@ -12,8 +12,8 @@ """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ - img = cv2.imread(IMAGE_PATH) - + img = cv2.imread(IMAGE_PATH, -1) + rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] @@ -21,7 +21,7 @@ rosimage.step = img.strides[0] rosimage.data = img.tostring() # rosimage.data = img.flatten().tolist() - + publisher.publish(rosimage) @@ -32,7 +32,7 @@ publisher = rospy.Publisher(IMAGE_MESSAGE_TOPIC, sensor_msgs.msg.Image, queue_size=10) rospy.Timer(rospy.Duration(0.5), callback) rospy.spin() - + if __name__ == '__main__': try: main_program()
3c87312aa5605e2705257052d38a4c8fae705da3
rnacentral/sequence_search/settings.py
rnacentral/sequence_search/settings.py
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute 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. """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally # SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' # minimum query sequence length MIN_LENGTH = 10 # maximum query sequence length MAX_LENGTH = 10000
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute 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. """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' # minimum query sequence length MIN_LENGTH = 10 # maximum query sequence length MAX_LENGTH = 10000
Use search.rnacentral.org as the sequence search endpoint
Use search.rnacentral.org as the sequence search endpoint
Python
apache-2.0
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
--- +++ @@ -12,10 +12,10 @@ """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy -SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy +# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy # SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally -# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' +SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org' # minimum query sequence length MIN_LENGTH = 10
a8070975c31aef61d722de93b7104b09f853e02d
robotars/templatetags/robotars_tags.py
robotars/templatetags/robotars_tags.py
# http://robohash.org/ from django import template from md5 import md5 register = template.Library() @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): url = "http://robohash.org/" if gravatar_fallback: if hashed: url += "%s?gravatar=hashed&" % md5(user.email).hexdigest() else: url += "%s?gravatar=yes&" % user.email else: url += "%s?" % user if size is not None: url += 'size=%s' % size return {"robotar_url": url, "robotar_user": user}
# http://robohash.org/ from django import template from md5 import md5 register = template.Library() @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): url = "//robohash.org/" if gravatar_fallback: if hashed: url += "%s?gravatar=hashed&" % md5(user.email).hexdigest() else: url += "%s?gravatar=yes&" % user.email else: url += "%s?" % user if size is not None: url += 'size=%s' % size return {"robotar_url": url, "robotar_user": user}
Use agnostic protocol urls to support both http/https.
Use agnostic protocol urls to support both http/https.
Python
bsd-3-clause
eldarion/robotars
--- +++ @@ -9,7 +9,7 @@ @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): - url = "http://robohash.org/" + url = "//robohash.org/" if gravatar_fallback: if hashed: url += "%s?gravatar=hashed&" % md5(user.email).hexdigest()
4d4b412bf67b782fc35d12531a9263c38230a96b
cloud_browser_project/urls.py
cloud_browser_project/urls.py
# pylint: disable=no-value-for-parameter from django.conf import settings from django.conf.urls import patterns, url, include from django.contrib import admin from django.views.generic import RedirectView # Enable admin. admin.autodiscover() ADMIN_URLS = False urlpatterns = patterns('') # pylint: disable=C0103 if ADMIN_URLS: urlpatterns += patterns( '', # Admin URLs. Note: Include ``urls_admin`` **before** admin. url(r'^$', RedirectView.as_view(url='/admin/'), name='index'), url(r'^admin/cb/', include('cloud_browser.urls_admin')), ) else: urlpatterns += patterns( '', # Normal URLs. url(r'^$', RedirectView.as_view(url='/cb/'), name='index'), url(r'^cb/', include('cloud_browser.urls')), ) urlpatterns += patterns( '', # Hack in the bare minimum to get accounts support. url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/$', RedirectView.as_view(url='/login/')), url(r'^accounts/profile', RedirectView.as_view(url='/')), ) if settings.DEBUG: # Serve up static media. urlpatterns += patterns( '', url(r'^' + settings.MEDIA_URL.strip('/') + '/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
# pylint: disable=no-value-for-parameter from django.conf import settings from django.conf.urls import patterns, url, include from django.contrib import admin from django.views.generic import RedirectView # Enable admin. admin.autodiscover() ADMIN_URLS = False urlpatterns = patterns('') # pylint: disable=C0103 if ADMIN_URLS: urlpatterns += [ # Admin URLs. Note: Include ``urls_admin`` **before** admin. url(r'^$', RedirectView.as_view(url='/admin/'), name='index'), url(r'^admin/cb/', include('cloud_browser.urls_admin')), ] else: urlpatterns += [ # Normal URLs. url(r'^$', RedirectView.as_view(url='/cb/'), name='index'), url(r'^cb/', include('cloud_browser.urls')), ] urlpatterns += [ # Hack in the bare minimum to get accounts support. url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/$', RedirectView.as_view(url='/login/')), url(r'^accounts/profile', RedirectView.as_view(url='/')), ] if settings.DEBUG: # Serve up static media. urlpatterns += [ url(r'^' + settings.MEDIA_URL.strip('/') + '/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ]
Update URL patterns for Django >= 1.8
Update URL patterns for Django >= 1.8
Python
mit
ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
--- +++ @@ -12,35 +12,31 @@ urlpatterns = patterns('') # pylint: disable=C0103 if ADMIN_URLS: - urlpatterns += patterns( - '', + urlpatterns += [ # Admin URLs. Note: Include ``urls_admin`` **before** admin. url(r'^$', RedirectView.as_view(url='/admin/'), name='index'), url(r'^admin/cb/', include('cloud_browser.urls_admin')), - ) + ] else: - urlpatterns += patterns( - '', + urlpatterns += [ # Normal URLs. url(r'^$', RedirectView.as_view(url='/cb/'), name='index'), url(r'^cb/', include('cloud_browser.urls')), - ) + ] -urlpatterns += patterns( - '', +urlpatterns += [ # Hack in the bare minimum to get accounts support. url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^accounts/$', RedirectView.as_view(url='/login/')), url(r'^accounts/profile', RedirectView.as_view(url='/')), -) +] if settings.DEBUG: # Serve up static media. - urlpatterns += patterns( - '', + urlpatterns += [ url(r'^' + settings.MEDIA_URL.strip('/') + '/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), - ) + ]
455b77877e2a3ee7f795ab969ed70ddc3dd8c531
hello.py
hello.py
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) config = {} def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_code == 0) def http_handler(address, **kwargs): try: r = requests.get(address) except requests.exceptions.RequestException: return json.dumps(False) return json.dumps(r.status_code == 200) get_handler = { 'http': http_handler, 'shell': shell_handler, } @app.route('/') def index(): data = { 'tasks': config['tasks'], 'title': config['title'], } return render_template('index.html', **data) @app.route('/<task_id>') def status(task_id): try: task = filter(lambda t: t['id'] == task_id, config['tasks'])[0] except IndexError: return 'This task does not exist', 404 return get_handler[task['type']](**task) if __name__ == '__main__': with open('config.json') as f: config = json.loads(f.read()) app.run(debug=True, host='0.0.0.0')
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) with open('config.json') as f: config = json.loads(f.read()) def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_code == 0) def http_handler(address, **kwargs): try: r = requests.get(address) except requests.exceptions.RequestException: return json.dumps(False) return json.dumps(r.status_code == 200) get_handler = { 'http': http_handler, 'shell': shell_handler, } @app.route('/') def index(): data = { 'tasks': config['tasks'], 'title': config['title'], } return render_template('index.html', **data) @app.route('/<task_id>') def status(task_id): try: task = filter(lambda t: t['id'] == task_id, config['tasks'])[0] except IndexError: return 'This task does not exist', 404 return get_handler[task['type']](**task) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Fix an error in production.
Fix an error in production.
Python
mit
xhacker/miracle-board,huangtao728/miracle-board,matthewbaggett/miracle-board,xhacker/miracle-board,matthewbaggett/miracle-board,huangtao728/miracle-board,forblackking/miracle-board,forblackking/miracle-board
--- +++ @@ -6,7 +6,8 @@ from flask import render_template app = Flask(__name__) -config = {} +with open('config.json') as f: + config = json.loads(f.read()) def shell_handler(command, **kwargs): @@ -47,6 +48,4 @@ if __name__ == '__main__': - with open('config.json') as f: - config = json.loads(f.read()) app.run(debug=True, host='0.0.0.0')
1ccf85b257d0774f6383a5e9dc6fdb43a20400ea
guild/commands/download_impl.py
guild/commands/download_impl.py
# Copyright 2017-2018 TensorHub, Inc. # # 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 __future__ import absolute_import from __future__ import division from guild import pip_util from guild import resolver from guild import resourcedef from guild import util def main(args): resdef = resourcedef.ResourceDef("download", {}) source = resourcedef.ResourceSource(resdef, args.url) download_dir = resolver.url_source_download_dir(source) util.ensure_dir(download_dir) source_path = pip_util.download_url(source.uri, download_dir) sha256 = util.file_sha256(source_path, use_cache=False) print("{} {}".format(sha256, source_path))
# Copyright 2017-2018 TensorHub, Inc. # # 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 __future__ import absolute_import from __future__ import division import logging from guild import cli from guild import pip_util from guild import resolver from guild import resourcedef from guild import util log = logging.getLogger("guild") def main(args): resdef = resourcedef.ResourceDef("download", {}) source = resourcedef.ResourceSource(resdef, args.url) download_dir = resolver.url_source_download_dir(source) util.ensure_dir(download_dir) try: source_path = pip_util.download_url(source.uri, download_dir) except Exception as e: _handle_download_error(e, source) else: sha256 = util.file_sha256(source_path, use_cache=False) print("{} {}".format(sha256, source_path)) def _handle_download_error(e, source): if log.getEffectiveLevel() <= logging.DEBUG: log.exception("downloading %s", source) cli.error("error downloading %s: %s" % (source, e))
Handle error on download command
Handle error on download command
Python
apache-2.0
guildai/guild,guildai/guild,guildai/guild,guildai/guild
--- +++ @@ -15,16 +15,30 @@ from __future__ import absolute_import from __future__ import division +import logging + +from guild import cli from guild import pip_util from guild import resolver from guild import resourcedef from guild import util + +log = logging.getLogger("guild") def main(args): resdef = resourcedef.ResourceDef("download", {}) source = resourcedef.ResourceSource(resdef, args.url) download_dir = resolver.url_source_download_dir(source) util.ensure_dir(download_dir) - source_path = pip_util.download_url(source.uri, download_dir) - sha256 = util.file_sha256(source_path, use_cache=False) - print("{} {}".format(sha256, source_path)) + try: + source_path = pip_util.download_url(source.uri, download_dir) + except Exception as e: + _handle_download_error(e, source) + else: + sha256 = util.file_sha256(source_path, use_cache=False) + print("{} {}".format(sha256, source_path)) + +def _handle_download_error(e, source): + if log.getEffectiveLevel() <= logging.DEBUG: + log.exception("downloading %s", source) + cli.error("error downloading %s: %s" % (source, e))
0a1056bd1629cc5c2423b83cf1d667ba46274fc9
scikits/image/io/__init__.py
scikits/image/io/__init__.py
"""Utilities to read and write images in various formats.""" from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import available as plugins # Add this plugin so that we can read images by default load_plugin('pil') from sift import * from collection import * from io import *
__doc__ = """Utilities to read and write images in various formats. The following plug-ins are available: """ from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import available as plugins from _plugins import info as plugin_info # Add this plugin so that we can read images by default load_plugin('pil') from sift import * from collection import * from io import * def _update_doc(doc): """Add a list of plugins to the module docstring, formatted as a ReStructuredText table. """ from textwrap import wrap info = [(p, plugin_info(p)) for p in plugins() if not p == 'test'] col_1_len = max([len(n) for (n, _) in info]) wrap_len = 73 col_2_len = wrap_len - 1 - col_1_len # Insert table header info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len})) info.insert(1, ('Plugin', {'description': 'Description'})) info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len})) info.append( ('=' * col_1_len, {'description': '=' * col_2_len})) for (name, meta_data) in info: wrapped_descr = wrap(meta_data.get('description', ''), col_2_len) doc += "%s %s\n" % (name.ljust(col_1_len), '\n'.join(wrapped_descr)) doc = doc.strip() return doc __doc__ = _update_doc(__doc__)
Add table of available plugins to module docstring.
io: Add table of available plugins to module docstring.
Python
bsd-3-clause
oew1v07/scikit-image,oew1v07/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,almarklein/scikit-image,robintw/scikit-image,GaelVaroquaux/scikits.image,keflavich/scikit-image,SamHames/scikit-image,almarklein/scikit-image,WarrenWeckesser/scikits-image,emmanuelle/scikits.image,almarklein/scikit-image,Britefury/scikit-image,bsipocz/scikit-image,michaelaye/scikit-image,emmanuelle/scikits.image,Midafi/scikit-image,paalge/scikit-image,Britefury/scikit-image,juliusbierk/scikit-image,chintak/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,rjeli/scikit-image,almarklein/scikit-image,newville/scikit-image,ajaybhat/scikit-image,chintak/scikit-image,rjeli/scikit-image,newville/scikit-image,SamHames/scikit-image,chintak/scikit-image,emon10005/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,SamHames/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,chriscrosscutler/scikit-image,emmanuelle/scikits.image,Hiyorimi/scikit-image,chriscrosscutler/scikit-image,keflavich/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,michaelaye/scikit-image,juliusbierk/scikit-image,jwiggins/scikit-image,Hiyorimi/scikit-image,blink1073/scikit-image,dpshelio/scikit-image,paalge/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,chintak/scikit-image,robintw/scikit-image,ClinicalGraphics/scikit-image,warmspringwinds/scikit-image,ofgulban/scikit-image,emmanuelle/scikits.image,pratapvardhan/scikit-image,dpshelio/scikit-image,GaelVaroquaux/scikits.image,ofgulban/scikit-image,youprofit/scikit-image,youprofit/scikit-image,warmspringwinds/scikit-image,emon10005/scikit-image,michaelpacer/scikit-image,michaelpacer/scikit-image,bennlich/scikit-image
--- +++ @@ -1,8 +1,13 @@ -"""Utilities to read and write images in various formats.""" +__doc__ = """Utilities to read and write images in various formats. + +The following plug-ins are available: + +""" from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import available as plugins +from _plugins import info as plugin_info # Add this plugin so that we can read images by default load_plugin('pil') @@ -11,3 +16,33 @@ from collection import * from io import * + +def _update_doc(doc): + """Add a list of plugins to the module docstring, formatted as + a ReStructuredText table. + + """ + from textwrap import wrap + + info = [(p, plugin_info(p)) for p in plugins() if not p == 'test'] + col_1_len = max([len(n) for (n, _) in info]) + + wrap_len = 73 + col_2_len = wrap_len - 1 - col_1_len + + # Insert table header + info.insert(0, ('=' * col_1_len, {'description': '=' * col_2_len})) + info.insert(1, ('Plugin', {'description': 'Description'})) + info.insert(2, ('-' * col_1_len, {'description': '-' * col_2_len})) + info.append( ('=' * col_1_len, {'description': '=' * col_2_len})) + + for (name, meta_data) in info: + wrapped_descr = wrap(meta_data.get('description', ''), + col_2_len) + doc += "%s %s\n" % (name.ljust(col_1_len), + '\n'.join(wrapped_descr)) + doc = doc.strip() + + return doc + +__doc__ = _update_doc(__doc__)
fd5742bf48691897640d117330d3c1f89276e907
fft/convert.py
fft/convert.py
from scikits.audiolab import Sndfile import matplotlib.pyplot as plt import os dt = 0.05 Fs = int(1.0/dt) current_dir = os.path.dirname(__file__) for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + filename) print (path) fname, extension = os.path.splitext(path) print (extension) if extension == '.flac': soundfile = Sndfile(path, "r") signal = soundfile.read_frames(soundfile.nframes) plt.specgram(signal, NFFT=512, Fs=Fs) outputfile = path.replace(extension, '.png') print (outputfile) plt.savefig(outputfile)
from scikits.audiolab import Sndfile import matplotlib.pyplot as plt import os dt = 0.05 Fs = int(1.0/dt) print 'started...' current_dir = os.path.dirname(__file__) print current_dir for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + filename) print (path) fname, extension = os.path.splitext(path) print (extension) if extension == '.flac': soundfile = Sndfile(path, "r") signal = soundfile.read_frames(soundfile.nframes) plt.specgram(signal, NFFT=512, Fs=Fs) outputfile = path.replace(extension, '.png') print (outputfile) fig = plt.gcf() defaultSize = [6.4, 4.8] # modify height_ratio to change the height of the generated graph file width_ratio = 1.58 height_ratio = 3.26 fig.set_size_inches( (defaultSize[0]*width_ratio, defaultSize[1]/height_ratio) ) print fig.get_size_inches() fig.savefig(outputfile, bbox_inches='tight', pad_inches=0)
Update spectrogram plot file size
Update spectrogram plot file size
Python
mit
ritazh/EchoML,ritazh/EchoML,ritazh/EchoML
--- +++ @@ -5,8 +5,9 @@ dt = 0.05 Fs = int(1.0/dt) +print 'started...' current_dir = os.path.dirname(__file__) - +print current_dir for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + filename) @@ -20,4 +21,12 @@ outputfile = path.replace(extension, '.png') print (outputfile) - plt.savefig(outputfile) + + fig = plt.gcf() + defaultSize = [6.4, 4.8] + # modify height_ratio to change the height of the generated graph file + width_ratio = 1.58 + height_ratio = 3.26 + fig.set_size_inches( (defaultSize[0]*width_ratio, defaultSize[1]/height_ratio) ) + print fig.get_size_inches() + fig.savefig(outputfile, bbox_inches='tight', pad_inches=0)
d7ce69c7b07782902970a9b21713295f6b1f59ad
audiorename/__init__.py
audiorename/__init__.py
"""Rename audio files from metadata tags.""" import sys from .args import fields, parse_args from .batch import Batch from .job import Job from .message import job_info, stats fields __version__: str = '0.0.0' def execute(*argv: str): """Main function :param list argv: The command line arguments specified as a list: e. g :code:`['--dry-run', '.']` """ job = None try: args = parse_args(argv) job = Job(args) job.stats.counter.reset() job.stats.timer.start() if job.cli_output.job_info: job_info(job) if job.rename.dry_run: job.msg.output('Dry run') batch = Batch(job) batch.execute() job.stats.timer.stop() if job.cli_output.stats: stats(job) except KeyboardInterrupt: if job: job.stats.timer.stop() if job.cli_output.stats: stats(job) sys.exit(0)
"""Rename audio files from metadata tags.""" import sys from importlib import metadata from .args import fields, parse_args from .batch import Batch from .job import Job from .message import job_info, stats fields __version__: str = metadata.version('audiorename') def execute(*argv: str): """Main function :param list argv: The command line arguments specified as a list: e. g :code:`['--dry-run', '.']` """ job = None try: args = parse_args(argv) job = Job(args) job.stats.counter.reset() job.stats.timer.start() if job.cli_output.job_info: job_info(job) if job.rename.dry_run: job.msg.output('Dry run') batch = Batch(job) batch.execute() job.stats.timer.stop() if job.cli_output.stats: stats(job) except KeyboardInterrupt: if job: job.stats.timer.stop() if job.cli_output.stats: stats(job) sys.exit(0)
Use the version number in pyproject.toml as the single source of truth
Use the version number in pyproject.toml as the single source of truth From Python 3.8 on we can use importlib.metadata.version('package_name') to get the current version.
Python
mit
Josef-Friedrich/audiorename
--- +++ @@ -1,6 +1,7 @@ """Rename audio files from metadata tags.""" import sys +from importlib import metadata from .args import fields, parse_args from .batch import Batch @@ -9,7 +10,7 @@ fields -__version__: str = '0.0.0' +__version__: str = metadata.version('audiorename') def execute(*argv: str):
dd27eea0ea43447dad321b4b9ec88f24e5ada268
asv/__init__.py
asv/__init__.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys if sys.version_info >= (3, 3): # OS X framework builds of Python 3.3 can not call other 3.3 # virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is # inherited. if os.environ.get('__PYVENV_LAUNCHER__'): os.unsetenv('__PYVENV_LAUNCHER__')
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys if sys.version_info >= (3, 3): # OS X framework builds of Python 3.3 can not call other 3.3 # virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is # inherited. if os.environ.get('__PYVENV_LAUNCHER__'): os.unsetenv('__PYVENV_LAUNCHER__') def check_version_compatibility(): """ Performs a number of compatibility checks with third-party libraries. """ from distutils.version import LooseVersion if sys.version_info[0] == 3: import virtualenv if LooseVersion(virtualenv.__version__) == LooseVersion('1.11'): raise RuntimeError("asv is not compatible with Python 3.x and virtualenv 1.11") check_version_compatibility()
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
Python
bsd-3-clause
pv/asv,mdboom/asv,airspeed-velocity/asv,waylonflinn/asv,airspeed-velocity/asv,giltis/asv,cpcloud/asv,spacetelescope/asv,mdboom/asv,giltis/asv,edisongustavo/asv,qwhelan/asv,airspeed-velocity/asv,pv/asv,cpcloud/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,ericdill/asv,ericdill/asv,pv/asv,cpcloud/asv,mdboom/asv,edisongustavo/asv,qwhelan/asv,pv/asv,qwhelan/asv,spacetelescope/asv,edisongustavo/asv,ericdill/asv,spacetelescope/asv,ericdill/asv,qwhelan/asv,waylonflinn/asv,giltis/asv,waylonflinn/asv
--- +++ @@ -13,3 +13,19 @@ # inherited. if os.environ.get('__PYVENV_LAUNCHER__'): os.unsetenv('__PYVENV_LAUNCHER__') + + +def check_version_compatibility(): + """ + Performs a number of compatibility checks with third-party + libraries. + """ + from distutils.version import LooseVersion + + if sys.version_info[0] == 3: + import virtualenv + if LooseVersion(virtualenv.__version__) == LooseVersion('1.11'): + raise RuntimeError("asv is not compatible with Python 3.x and virtualenv 1.11") + + +check_version_compatibility()
16c567f27e1e4979321d319ddb334c263b43443f
gitcv/gitcv.py
gitcv/gitcv.py
import os import yaml from git import Repo class GitCv: def __init__(self, cv_path, repo_path): self._cv = self._load_cv(cv_path) self._repo_path = os.path.join(repo_path, 'cv') def _load_cv(self, cv_path): with open(cv_path, "r") as f: cv = yaml.load(f) return cv def _create_repo(self): self._repo = Repo.init(self._repo_path) def _create_branches(self): for stream in self._cv: for entry in stream: self._create_branch(entry) def _create_branch(self, branch_name): self._repo.create_head(branch_name) def _create_file_and_commit(self, file_name): open(os.path.join(self._repo_path, file_name), 'w').close() self._repo.index.add([file_name]) self._repo.index.commit('Add {0}'.format(file_name)) def create(self): self._create_repo() self._create_file_and_commit('dummy.txt') self._create_branches() if __name__ == '__main__': GitCv('../cv.yaml', '../target').create()
import os import yaml from git import Repo class GitCv: def __init__(self, cv_path, repo_path): self._repo_path = os.path.join(repo_path, 'cv') self._cv_path = cv_path self._load_cv() def _load_cv(self): with open(self._cv_path, "r") as f: self._cv = yaml.load(f) def _create_repo(self): self._repo = Repo.init(self._repo_path) def _create_branches(self): for stream in self._cv: for entry in stream: self._create_branch(entry) def _create_branch(self, branch_name): self._repo.create_head(branch_name) def _create_file_and_commit(self, file_name): open(os.path.join(self._repo_path, file_name), 'w').close() self._repo.index.add([file_name]) self._repo.index.commit('Add {0}'.format(file_name)) def create(self): self._create_repo() self._create_file_and_commit('dummy.txt') self._create_branches() if __name__ == '__main__': GitCv('../cv.yaml', '../target').create()
Make cv path class attribute
Make cv path class attribute
Python
mit
jangroth/git-cv,jangroth/git-cv
--- +++ @@ -6,13 +6,13 @@ class GitCv: def __init__(self, cv_path, repo_path): - self._cv = self._load_cv(cv_path) self._repo_path = os.path.join(repo_path, 'cv') + self._cv_path = cv_path + self._load_cv() - def _load_cv(self, cv_path): - with open(cv_path, "r") as f: - cv = yaml.load(f) - return cv + def _load_cv(self): + with open(self._cv_path, "r") as f: + self._cv = yaml.load(f) def _create_repo(self): self._repo = Repo.init(self._repo_path)
0f42038436fae01e248bbf86c5d52f7cdfe97fdc
ironicclient/tests/functional/utils.py
ironicclient/tests/functional/utils.py
# Copyright (c) 2015 Mirantis, Inc. # # 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. import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj def get_object(object_list, object_value): """"Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get """ for obj in object_list: if object_value in obj.values(): return obj
# Copyright (c) 2015 Mirantis, Inc. # # 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. import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj def get_object(object_list, object_value): """Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get """ for obj in object_list: if object_value in obj.values(): return obj
Fix quotation mark in docstring
Fix quotation mark in docstring Change-Id: Ie9501a0bce8c43e0316d1b8bda7296e859b0c8fb
Python
apache-2.0
openstack/python-ironicclient,NaohiroTamura/python-ironicclient,NaohiroTamura/python-ironicclient,openstack/python-ironicclient
--- +++ @@ -27,7 +27,7 @@ def get_object(object_list, object_value): - """"Get Ironic object by value from list of Ironic objects. + """Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get
ff4c49b9d89d4f92804ce1d827015072b6b60b7b
addons/sale_margin/__init__.py
addons/sale_margin/__init__.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import openerp from openerp import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): db_registry = openerp.modules.registry.Registry.new(dbname) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) if 'sale.report' in env: env['sale.report'].init() cr.after("commit", partial(recreate_view, cr.dbname))
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import odoo from odoo import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): db_registry = odoo.modules.registry.Registry.new(dbname) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) if 'sale.report' in env: env['sale.report'].init() cr.after("commit", partial(recreate_view, cr.dbname))
Use odoo instead of openerp
[IMP] sale_margin: Use odoo instead of openerp Closes #23451
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
--- +++ @@ -2,8 +2,8 @@ # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial -import openerp -from openerp import api, SUPERUSER_ID +import odoo +from odoo import api, SUPERUSER_ID from . import models # noqa from . import report # noqa @@ -11,7 +11,7 @@ def uninstall_hook(cr, registry): def recreate_view(dbname): - db_registry = openerp.modules.registry.Registry.new(dbname) + db_registry = odoo.modules.registry.Registry.new(dbname) with api.Environment.manage(), db_registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) if 'sale.report' in env:
84e9995668d8c34993b9fdf1a95f187897328750
ex6.py
ex6.py
# left out assignment for types_of_people mentioned in intro types_of_people = 10 # change variable from 10 to types_of_people x = f"There are {types_of_people} types of people." binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." print(x) print(y) # left out f in front of string and omit extra period print(f"I said: {x}") # left out f in front of string and omit extra period print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_evaluation.format(hilarious)) w = "This is the left side of..." e = "a string with a right side." print(w + e) # change "What You Should See" snapshot to reflect changes
types_of_people = 10 x = f"There are {types_of_people} types of people." binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." print(x) print(y) print(f"I said: {x}") print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_evaluation.format(hilarious)) w = "This is the left side of..." e = "a string with a right side." print(w + e)
Remove unnesessary comments for learners
Remove unnesessary comments for learners
Python
mit
zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code
--- +++ @@ -1,6 +1,4 @@ -# left out assignment for types_of_people mentioned in intro types_of_people = 10 -# change variable from 10 to types_of_people x = f"There are {types_of_people} types of people." binary = "binary" @@ -10,9 +8,7 @@ print(x) print(y) -# left out f in front of string and omit extra period print(f"I said: {x}") -# left out f in front of string and omit extra period print(f"I also said: '{y}'") hilarious = False @@ -24,5 +20,3 @@ e = "a string with a right side." print(w + e) - -# change "What You Should See" snapshot to reflect changes
ed10111f92b1f75d852647fe55e260974fab5eb4
apps/approval/api/serializers.py
apps/approval/api/serializers.py
from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority class CommitteeSerializer(serializers.ModelSerializer): group_name = serializers.SerializerMethodField(source='group') class Meta(object): model = CommitteePriority fields = ('group', 'group_name', 'priority') def get_group_name(self, instance): return instance.group.name class CommitteeApplicationSerializer(serializers.ModelSerializer): committees = CommitteeSerializer(many=True, source='committeepriority_set') class Meta(object): model = CommitteeApplication fields = ('name', 'email', 'application_text', 'prioritized', 'committees') def create(self, validated_data): committees = validated_data.pop('committeepriority_set') application = CommitteeApplication.objects.create(**validated_data) for committee in committees: CommitteePriority.objects.create(committee_application=application, **committee) return CommitteeApplication.objects.get(pk=application.pk)
from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority class CommitteeSerializer(serializers.ModelSerializer): group_name = serializers.SerializerMethodField(source='group') class Meta(object): model = CommitteePriority fields = ('group', 'group_name', 'priority') def get_group_name(self, instance): return instance.group.name class CommitteeApplicationSerializer(serializers.ModelSerializer): committees = CommitteeSerializer(many=True, source='committeepriority_set') class Meta(object): model = CommitteeApplication fields = ('name', 'email', 'application_text', 'prioritized', 'committees') def create(self, validated_data): committees = validated_data.pop('committeepriority_set') application = CommitteeApplication(**validated_data) try: application.clean() except DjangoValidationError as django_error: raise serializers.ValidationError(django_error.message) application.save() for committee in committees: CommitteePriority.objects.create(committee_application=application, **committee) return CommitteeApplication.objects.get(pk=application.pk)
Raise DRF ValidationError to get APIException base
Raise DRF ValidationError to get APIException base
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -1,3 +1,4 @@ +from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority @@ -23,7 +24,12 @@ def create(self, validated_data): committees = validated_data.pop('committeepriority_set') - application = CommitteeApplication.objects.create(**validated_data) + application = CommitteeApplication(**validated_data) + try: + application.clean() + except DjangoValidationError as django_error: + raise serializers.ValidationError(django_error.message) + application.save() for committee in committees: CommitteePriority.objects.create(committee_application=application, **committee)
e081c1944506330a3c01cfe90dcf8deb242bd63b
bin/migrate-tips.py
bin/migrate-tips.py
from gratipay.wireup import db, env from gratipay.models.team import migrate_all_tips db = db(env()) if __name__ == '__main__': migrate_all_tips(db)
from gratipay.wireup import db, env from gratipay.models.team.mixins.tip_migration import migrate_all_tips db = db(env()) if __name__ == '__main__': migrate_all_tips(db)
Fix imports in tip migration script
Fix imports in tip migration script
Python
mit
gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com
--- +++ @@ -1,5 +1,5 @@ from gratipay.wireup import db, env -from gratipay.models.team import migrate_all_tips +from gratipay.models.team.mixins.tip_migration import migrate_all_tips db = db(env())
a2d90e92a0686578cc354b5979af1945233f03f6
sitetools/venv_hook/sitecustomize.py
sitetools/venv_hook/sitecustomize.py
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sys import warnings try: try: import sitetools._startup except ImportError: # Pull in the sitetools that goes with this sitecustomize. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Let this ImportError raise. import sitetools._startup except Exception as e: warnings.warn("Error while importing sitetools._startup: %e" % e) # Be a good citizen and find the next sitecustomize module. my_path = os.path.dirname(os.path.abspath(__file__)) clean_path = [x for x in sys.path if os.path.abspath(x) != my_path] try: args = imp.find_module('sitecustomize', clean_path) except ImportError: pass else: imp.load_module('sitecustomize', *args)
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sys import warnings try: try: import sitetools._startup except ImportError: # Pull in the sitetools that goes with this sitecustomize. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Let this ImportError raise. import sitetools._startup except Exception as e: warnings.warn("Error while importing sitetools._startup: %s" % e) # Be a good citizen and find the next sitecustomize module. my_path = os.path.dirname(os.path.abspath(__file__)) clean_path = [x for x in sys.path if os.path.abspath(x) != my_path] try: args = imp.find_module('sitecustomize', clean_path) except ImportError: pass else: imp.load_module('sitecustomize', *args)
Fix formatting of error in venv_hook
Fix formatting of error in venv_hook
Python
bsd-3-clause
mikeboers/sitetools,westernx/sitetools,westernx/sitetools
--- +++ @@ -28,7 +28,7 @@ import sitetools._startup except Exception as e: - warnings.warn("Error while importing sitetools._startup: %e" % e) + warnings.warn("Error while importing sitetools._startup: %s" % e) # Be a good citizen and find the next sitecustomize module.
c2da36340d372deb3ebfc16f395bb32a60a9da12
rps.py
rps.py
from random import choice class RPSGame: shapes = ['rock', 'paper', 'scissors'] draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')] first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')] def _evaluate(self, player_move, computer_move): if (player_move, computer_move) in RPSGame.draws: return "Draw!" elif (player_move, computer_move) in RPSGame.first_wins: return "Player wins!" else: return "Computer wins!" def play(self, rounds=1): for i in range(rounds): player_move = input("[rock,paper,scissors]: ") computer_move = choice(RPSGame.shapes) winner = self._evaluate(player_move, computer_move) print(20 * "-") print("You played: %s" % player_move) print("Computer played: %s" % computer_move) print(winner) print(20 * "-") if __name__ == '__main__': game = RPSGame() game.play(rounds=10)
from random import choice import unittest class RPSGame: shapes = ['rock', 'paper', 'scissors'] draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')] first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')] def _evaluate(self, player_move, computer_move): if (player_move, computer_move) in RPSGame.draws: return "Draw!" elif (player_move, computer_move) in RPSGame.first_wins: return "Player wins!" else: return "Computer wins!" def _computer_move(self): return choice(RPSGame.shapes) def play(self, rounds=1): for i in range(rounds): player_move = input("[rock,paper,scissors]: ") computer_move = self._computer_move() winner = self._evaluate(player_move, computer_move) print(20 * "-") print("You played: %s" % player_move) print("Computer played: %s" % computer_move) print(winner) print(20 * "-") class RPSGameTests(unittest.TestCase): def setUp(self): self.rps = RPSGame() def test_computer_move(self): moves = {'rock': 0, 'paper': 0, 'scissors': 0} n = 100000 for i in range(n): cp = self.rps._computer_move() moves[cp] += 1 for shape in moves: # self.assertEquals(moves[shape] / n, 1/3) self.assertAlmostEqual(moves[shape] / n, 1/3, 2) if __name__ == '__main__': unittest.main()
Add simple unittest to test computer's strategy.
Add simple unittest to test computer's strategy.
Python
mit
kubkon/ee106-additional-material
--- +++ @@ -1,4 +1,5 @@ from random import choice +import unittest class RPSGame: shapes = ['rock', 'paper', 'scissors'] @@ -13,10 +14,13 @@ else: return "Computer wins!" + def _computer_move(self): + return choice(RPSGame.shapes) + def play(self, rounds=1): for i in range(rounds): player_move = input("[rock,paper,scissors]: ") - computer_move = choice(RPSGame.shapes) + computer_move = self._computer_move() winner = self._evaluate(player_move, computer_move) print(20 * "-") print("You played: %s" % player_move) @@ -24,7 +28,20 @@ print(winner) print(20 * "-") + +class RPSGameTests(unittest.TestCase): + def setUp(self): + self.rps = RPSGame() + + def test_computer_move(self): + moves = {'rock': 0, 'paper': 0, 'scissors': 0} + n = 100000 + for i in range(n): + cp = self.rps._computer_move() + moves[cp] += 1 + for shape in moves: + # self.assertEquals(moves[shape] / n, 1/3) + self.assertAlmostEqual(moves[shape] / n, 1/3, 2) + if __name__ == '__main__': - game = RPSGame() - game.play(rounds=10) - + unittest.main()
7c05eb09dc5ff83ef45f3f84b9603ec6e43f58c7
run.py
run.py
import argparse from app import app parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False) parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=int) params = parser.parse_args() app.run(debug=params.debug, port=params.port, host='0.0.0.0')
import argparse import os from app import app if os.geteuid() != 0: raise OSError("Must be run as root") parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False) parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=int) params = parser.parse_args() app.run(debug=params.debug, port=params.port, host='0.0.0.0')
Add error if missing root
Add error if missing root
Python
mit
njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote
--- +++ @@ -1,6 +1,11 @@ import argparse +import os from app import app + + +if os.geteuid() != 0: + raise OSError("Must be run as root") parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False)
858a68a66e40ecc5d1a592503166e7096544b8c3
leetcode/ds_hash_contains_duplicate.py
leetcode/ds_hash_contains_duplicate.py
# @file Contains Duplicate # @brief Given array of integers, find if array contains duplicates # https://leetcode.com/problems/contains-duplicate/ ''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. ''' #Use a dictionary to store all numbers. If a number is seen 2nd time return immediately #Time Complexity = O(n) since we have a single for-loop to look at all numbers def containsDuplicate(self, nums): dict = {} for val in nums: if val not in dict: dict[val] = 1 elif val in dict: return True return False
# @file Contains Duplicate # @brief Given array of integers, find if array contains duplicates # https://leetcode.com/problems/contains-duplicate/ ''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. ''' #Use a dictionary to store all numbers. If a number is seen 2nd time return immediately #Time Complexity = O(n) since we have a single for-loop to look at all numbers def containsDuplicate(self, nums): dict = {} for num in nums: if num not in dict: dict[num] = 1 elif num in dict: return True return False
Change keyword val to num
Change keyword val to num
Python
mit
ngovindaraj/Python
--- +++ @@ -13,8 +13,8 @@ #Time Complexity = O(n) since we have a single for-loop to look at all numbers def containsDuplicate(self, nums): dict = {} - for val in nums: - if val not in dict: dict[val] = 1 - elif val in dict: return True + for num in nums: + if num not in dict: dict[num] = 1 + elif num in dict: return True return False
c3f5212dbb7452db48420d717c1815ad4e536c40
cgen_wrapper.py
cgen_wrapper.py
from cgen import * from codeprinter import ccode import ctypes class Ternary(Generable): def __init__(self, condition, true_statement, false_statement): self.condition = ccode(condition) self.true_statement = ccode(true_statement) self.false_statement = ccode(false_statement) def generate(self): yield "(("+str(self.condition)+")?"+str(self.true_statement)+":"+str(self.false_statement)+")" def convert_dtype_to_ctype(dtype): conversion_dict = {'int64': ctypes.c_int64, 'float64': ctypes.c_float} return conversion_dict[str(dtype)]
from cgen import * import ctypes def convert_dtype_to_ctype(dtype): conversion_dict = {'int64': ctypes.c_int64, 'float64': ctypes.c_float} return conversion_dict[str(dtype)]
Remove the Ternary class from cgen wrapper
Remove the Ternary class from cgen wrapper This is no longer required since we are not using preprocessor macros any more
Python
mit
opesci/devito,opesci/devito
--- +++ @@ -1,16 +1,5 @@ from cgen import * -from codeprinter import ccode import ctypes - - -class Ternary(Generable): - def __init__(self, condition, true_statement, false_statement): - self.condition = ccode(condition) - self.true_statement = ccode(true_statement) - self.false_statement = ccode(false_statement) - - def generate(self): - yield "(("+str(self.condition)+")?"+str(self.true_statement)+":"+str(self.false_statement)+")" def convert_dtype_to_ctype(dtype):
01949a1f5d8278ab1d577e2d56b1c9fd2f79724c
metpy/plots/tests/test_skewt.py
metpy/plots/tests/test_skewt.py
import tempfile import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from metpy.plots.skewt import * # noqa # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): def test_api(self): 'Test the SkewT api' fig = Figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot p = np.linspace(1000, 100, 10) t = np.linspace(20, -20, 10) u = np.linspace(-10, 10, 10) skew.plot(p, t, 'r') skew.plot_barbs(p, u, u) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name) def test_no_figure(self): 'Test the SkewT api' skew = SkewT() with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(skew.ax.figure).print_png(f.name)
import tempfile import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from metpy.plots.skewt import * # noqa # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): def test_api(self): 'Test the SkewT api' fig = Figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot p = np.linspace(1000, 100, 10) t = np.linspace(20, -20, 10) u = np.linspace(-10, 10, 10) skew.plot(p, t, 'r') skew.plot_barbs(p, u, u) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name)
Remove test for not passing figure.
Remove test for not passing figure. This will trigger matplotlib's backend detection, which won't work well for us on Travis.
Python
bsd-3-clause
dopplershift/MetPy,ahaberlie/MetPy,Unidata/MetPy,ShawnMurd/MetPy,Unidata/MetPy,jrleeman/MetPy,ahaberlie/MetPy,ahill818/MetPy,deeplycloudy/MetPy,jrleeman/MetPy,dopplershift/MetPy
--- +++ @@ -28,9 +28,3 @@ with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name) - - def test_no_figure(self): - 'Test the SkewT api' - skew = SkewT() - with tempfile.NamedTemporaryFile() as f: - FigureCanvasAgg(skew.ax.figure).print_png(f.name)
f3f7cc59cfc79420a2f1fa00e3e8631250f4e9cf
cloaca/stack.py
cloaca/stack.py
class Stack(object): def __init__(self, stack=None): self.stack = stack if stack else [] def push_frame(self, function_name, *args): self.stack.append(Frame(function_name, *args)) def remove(self, item): self.stack.remove(item) def __str__(self): return str(self.stack) def __repr__(self): return 'Stack({0!r})'.format(self.stack) class Frame(object): def __init__(self, function_name, *args, **kwargs): self.function_name = function_name self.args = kwargs.get('args', args) self.executed = kwargs.get('executed', False) def __str__(self): return 'Frame({0})'.format(self.function_name) def __repr__(self): return 'Frame({0}, {1})'.format(self.function_name, self.args)
class Stack(object): def __init__(self, stack=None): self.stack = stack if stack else [] def push_frame(self, function_name, *args): self.stack.append(Frame(function_name, *args)) def remove(self, item): self.stack.remove(item) def __str__(self): return str(self.stack) def __repr__(self): return 'Stack({0!r})'.format(self.stack) class Frame(object): def __init__(self, function_name, *args, **kwargs): self.function_name = function_name self.args = kwargs.get('args', args) self.executed = kwargs.get('executed', False) def __str__(self): return 'Frame({0})'.format(self.function_name) def __repr__(self): return 'Frame({0}, args={1})'.format(self.function_name, self.args)
Fix repr to include args as kwargs.
Fix repr to include args as kwargs. It's a weird signature.
Python
mit
mhmurray/cloaca,mhmurray/cloaca,mhmurray/cloaca,mhmurray/cloaca
--- +++ @@ -25,4 +25,4 @@ return 'Frame({0})'.format(self.function_name) def __repr__(self): - return 'Frame({0}, {1})'.format(self.function_name, self.args) + return 'Frame({0}, args={1})'.format(self.function_name, self.args)
5a67bff672e0a74419cadbdcaf9f6bd7b9336499
config/fuzzer_params.py
config/fuzzer_params.py
switch_failure_rate = 0.0 switch_recovery_rate = 0.0 dataplane_drop_rate = 0.3 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 ofp_message_send_rate = 1.0 ofp_cmd_passthrough_rate = 0.0 link_failure_rate = 0.0 link_recovery_rate = 1.0 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 traffic_generation_rate = 0.3 host_migration_rate = 0.05 intracontroller_block_rate = 0.0 intracontroller_unblock_rate = 0.0
switch_failure_rate = 0.02 switch_recovery_rate = 0.0 dataplane_drop_rate = 0.005 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 ofp_message_send_rate = 1.0 ofp_cmd_passthrough_rate = 0.0 link_failure_rate = 0.0 link_recovery_rate = 1.0 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 traffic_generation_rate = 0.1 host_migration_rate = 0.04 intracontroller_block_rate = 0.0 intracontroller_unblock_rate = 0.0
Make fuzzer params somewhat more realistic (not so high)
Make fuzzer params somewhat more realistic (not so high)
Python
apache-2.0
jmiserez/sts,ucb-sts/sts,jmiserez/sts,ucb-sts/sts
--- +++ @@ -1,6 +1,6 @@ -switch_failure_rate = 0.0 +switch_failure_rate = 0.02 switch_recovery_rate = 0.0 -dataplane_drop_rate = 0.3 +dataplane_drop_rate = 0.005 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 @@ -10,7 +10,7 @@ link_recovery_rate = 1.0 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 -traffic_generation_rate = 0.3 -host_migration_rate = 0.05 +traffic_generation_rate = 0.1 +host_migration_rate = 0.04 intracontroller_block_rate = 0.0 intracontroller_unblock_rate = 0.0
a9da17d7edb443bbdee7406875717d30dc4e4bf5
src/scripts/write_hosts.py
src/scripts/write_hosts.py
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hostname + '\n') f.write('\n') f.write('# The following lines are desirable for IPv6 capable hosts\n') f.write('::1 ip6-localhost ip6-loopback\n') f.write('fe00::0 ip6-localnet\n') f.write('ff00::0 ip6-mcastprefix\n') f.write('ff02::1 ip6-allnodes\n') f.write('ff02::2 ip6-allrouters\n') f.write('ff02::3 ip6-allhosts\n') with open('/etc/hosts', 'w') as f: write_hosts(hostnames, addresses, f)
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hostname + '\n') f.write('\n') f.write('# The following lines are desirable for IPv6 capable hosts\n') f.write('::1 ip6-localhost ip6-loopback\n') f.write('fe00::0 ip6-localnet\n') f.write('ff00::0 ip6-mcastprefix\n') f.write('ff02::1 ip6-allnodes\n') f.write('ff02::2 ip6-allrouters\n') f.write('ff02::3 ip6-allhosts\n') with open('/etc/hosts', 'w') as f: write_hosts(hostnames, addresses, f)
Add own hostname to /etc/hosts
Add own hostname to /etc/hosts
Python
mit
evoila/heat-common,evoila/heat-common
--- +++ @@ -6,7 +6,7 @@ def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') - f.write('127.0.0.1 localhost\n\n') + f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hostname + '\n')
fe3db3aca1d6166c3c3d739971346205591d8d9e
roamer/python_edit.py
roamer/python_edit.py
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".tmp") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND: call([EDITOR, EXTRA_EDITOR_COMMAND, temp.name]) else: call([EDITOR, temp.name]) temp.seek(0) return temp.read()
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".roamer") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND: call([EDITOR, EXTRA_EDITOR_COMMAND, temp.name]) else: call([EDITOR, temp.name]) temp.seek(0) return temp.read()
Change file type to .roamer
Change file type to .roamer
Python
mit
abaldwin88/roamer
--- +++ @@ -15,7 +15,7 @@ def file_editor(content): - with tempfile.NamedTemporaryFile(suffix=".tmp") as temp: + with tempfile.NamedTemporaryFile(suffix=".roamer") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND:
367be3298ac72f6d3e369a592e7a3f1d37b042e1
bin/ext_service/reset_all_habitica_users.py
bin/ext_service/reset_all_habitica_users.py
import argparse import sys import logging import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", "/api/v3/user/reset", {}) logging.debug("reset result for %s = %s" % (reset_em_uuid, del_result)) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) for creds in edb.get_habitica_db().find(): reset_uuid = creds["user_id"] logging.debug("Processing emission user id %s" % reset_uuid) reset_user(reset_uuid)
import argparse import sys import logging import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy import emission.net.ext_service.habitica.sync_habitica as autocheck def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", "/api/v3/user/reset", {}) update_result = edb.get_habitica_db().update({"user_id": reset_em_uuid}, {"$set": {'metrics_data': {'last_timestamp': 0, 'bike_count': 0, 'walk_count': 0}}}) logging.debug("reset result for %s = %s, %s" % (reset_em_uuid, del_result, update_result)) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("-r", "--restore", help="re-run pipeline and restore values", action="store_true") args = parser.parse_args() for creds in edb.get_habitica_db().find(): reset_uuid = creds["user_id"] logging.debug("Processing emission user id %s" % reset_uuid) reset_user(reset_uuid) if args.restore: autocheck.reward_active_transportation(reset_uuid)
Enhance the habitica reset pipeline to reset all users
Enhance the habitica reset pipeline to reset all users Also reset the last timestamp since we have deleted all points so we need to restore all points. Also restore their points with an optional argument. This is useful when the trips/sections are correct but the habitica set is screwed up.
Python
bsd-3-clause
shankari/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server
--- +++ @@ -4,17 +4,29 @@ import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy +import emission.net.ext_service.habitica.sync_habitica as autocheck def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", "/api/v3/user/reset", {}) - logging.debug("reset result for %s = %s" % (reset_em_uuid, del_result)) + update_result = edb.get_habitica_db().update({"user_id": reset_em_uuid}, + {"$set": {'metrics_data': + {'last_timestamp': 0, 'bike_count': 0, 'walk_count': 0}}}) + logging.debug("reset result for %s = %s, %s" % (reset_em_uuid, del_result, update_result)) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) + + parser = argparse.ArgumentParser() + parser.add_argument("-r", "--restore", + help="re-run pipeline and restore values", action="store_true") + args = parser.parse_args() for creds in edb.get_habitica_db().find(): reset_uuid = creds["user_id"] logging.debug("Processing emission user id %s" % reset_uuid) reset_user(reset_uuid) + if args.restore: + autocheck.reward_active_transportation(reset_uuid) +
d20f04d65437138559445bf557be52a87690c7f2
test/checker/test_checker_ipaddress.py
test/checker/test_checker_ipaddress.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals from ipaddress import ip_address import itertools import pytest import six from typepy import ( Typecode, StrictLevel, ) from typepy.type import IpAddress nan = float("nan") inf = float("inf") class Test_IpAddress_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product( ["", " ", six.MAXSIZE, str(six.MAXSIZE), inf, nan, None], [StrictLevel.MIN, StrictLevel.MAX], [False] )) + list(itertools.product( [ "127.0.0.1", "::1", ip_address("127.0.0.1"), ip_address("::1"), ], [StrictLevel.MIN, StrictLevel.MAX], [True], ))) def test_normal(self, value, strict_level, expected): type_checker = IpAddress(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.IP_ADDRESS
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals from ipaddress import ip_address import itertools import pytest import six from typepy import ( Typecode, StrictLevel, ) from typepy.type import IpAddress nan = float("nan") inf = float("inf") class Test_IpAddress_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"], list(itertools.product( ["", " ", six.MAXSIZE, str(six.MAXSIZE), inf, nan, None], [StrictLevel.MIN, StrictLevel.MAX], [False] )) + list(itertools.product( [ "127.0.0.1", "::1", ip_address("127.0.0.1"), ip_address("::1"), ], [StrictLevel.MIN, StrictLevel.MAX], [True], ))) def test_normal(self, value, strict_level, expected): type_checker = IpAddress(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.IP_ADDRESS
Change class definitions from old style to new style
Change class definitions from old style to new style
Python
mit
thombashi/typepy
--- +++ @@ -23,7 +23,7 @@ inf = float("inf") -class Test_IpAddress_is_type: +class Test_IpAddress_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"],
3e374aa6714b677bd9d9225b155adc5b1ffd680d
stubilous/builder.py
stubilous/builder.py
from functools import partial def response(callback, method, url, body, status=200): from stubilous.config import Route callback(Route(method=method, path=url, body=body, status=status, desc="")) class Builder(object): def __init__(self): self.host = None self.port = None self.routes = [] def server(self, host, port): self.host = host self.port = port return self def route(self, method, url): def callback(route): self.routes.append(route) return self return partial(response, callback, method, url) def build(self): from stubilous.config import Config return Config(host=self.host, port=self.port, routes=self.routes)
from functools import partial from stubilous.config import Route def response(callback, method, url, body, status=200, headers=None, cookies=None): callback(Route(method=method, path=url, body=body, status=status, desc="", headers=headers, cookies=cookies)) class Builder(object): def __init__(self): self.host = None self.port = None self.routes = [] def server(self, host, port): self.host = host self.port = port return self def route(self, method, url): def callback(route): self.routes.append(route) return self return partial(response, callback, method, url) def build(self): from stubilous.config import Config return Config(host=self.host, port=self.port, routes=self.routes)
Allow cookies and headers in response
Allow cookies and headers in response
Python
mit
CodersOfTheNight/stubilous
--- +++ @@ -1,9 +1,22 @@ from functools import partial +from stubilous.config import Route -def response(callback, method, url, body, status=200): - from stubilous.config import Route - callback(Route(method=method, path=url, body=body, status=status, desc="")) +def response(callback, + method, + url, + body, + status=200, + headers=None, + cookies=None): + + callback(Route(method=method, + path=url, + body=body, + status=status, + desc="", + headers=headers, + cookies=cookies)) class Builder(object):
9728d59217e2fd8bcaaf7586a9a3b99c61764630
tests/changes/api/test_plan_details.py
tests/changes/api/test_plan_details.py
from changes.testutils import APITestCase class PlanIndexTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) path = '/api/0/plans/{0}/'.format(plan1.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == plan1.id.hex assert len(data['projects']) == 2 assert data['projects'][0]['id'] == project1.id.hex assert data['projects'][1]['id'] == project2.id.hex
from changes.testutils import APITestCase class PlanDetailsTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) path = '/api/0/plans/{0}/'.format(plan1.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert data['id'] == plan1.id.hex assert len(data['projects']) == 2 assert data['projects'][0]['id'] == project1.id.hex assert data['projects'][1]['id'] == project2.id.hex
Fix plan details test name
Fix plan details test name
Python
apache-2.0
dropbox/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes
--- +++ @@ -1,7 +1,7 @@ from changes.testutils import APITestCase -class PlanIndexTest(APITestCase): +class PlanDetailsTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project()
5a3ed191cb29d328976b33a3bc4a2fa68b0be2e4
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields class Course(models.Model): _name = 'openacademy.course' name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string='Responsible', index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
from openerp import api, models, fields class Course(models.Model): _name = 'openacademy.course' name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string='Responsible', index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send default params: cr, uid, id context def copy(self, default=None): default = dict(default or {}) copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
arogel/openacademy-project
--- +++ @@ -1,4 +1,4 @@ -from openerp import models, fields +from openerp import api, models, fields class Course(models.Model): @@ -20,3 +20,17 @@ 'UNIQUE(name)', "The course title must be unique"), ] + + @api.one # api.one send default params: cr, uid, id context + def copy(self, default=None): + default = dict(default or {}) + + copied_count = self.search_count( + [('name', '=like', u"Copy of {}%".format(self.name))]) + if not copied_count: + new_name = u"Copy of {}".format(self.name) + else: + new_name = u"Copy of {} ({})".format(self.name, copied_count) + + default['name'] = new_name + return super(Course, self).copy(default)
fed8d1d85b929dc21cd49cd2cd0ac660f19e7a36
comics/crawlers/bizarro.py
comics/crawlers/bizarro.py
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' url = 'http://www.start.no/tegneserier/bizarro/' start_date = '1985-01-01' end_date = '2009-06-24' # No longer hosted at start.no history_capable_days = 30 schedule = 'Mo,Tu,We,Th,Fr,Sa,Su' time_zone = 1 rights = 'Dan Piraro' class ComicCrawler(BaseComicCrawler): def _get_url(self): self.url = 'http://g2.start.no/tegneserier/striper/bizarro/biz-striper/biz%(date)s.gif' % { 'date': self.pub_date.strftime('%Y%m%d'), }
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' url = 'http://underholdning.no.msn.com/tegneserier/bizarro/' start_date = '1985-01-01' history_capable_days = 12 schedule = 'Mo,Tu,We,Th,Fr,Sa,Su' time_zone = 1 rights = 'Dan Piraro' class ComicCrawler(BaseComicCrawler): def _get_url(self): self.parse_feed('http://underholdning.no.msn.com/rss/bizarro.aspx') for entry in self.feed.entries: if self.timestamp_to_date(entry.updated_parsed) == self.pub_date: self.url = entry.enclosures[0].href return
Update 'Bizarro' crawler to use msn.no instead of start.no
Update 'Bizarro' crawler to use msn.no instead of start.no
Python
agpl-3.0
klette/comics,datagutten/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,jodal/comics
--- +++ @@ -4,16 +4,18 @@ class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' - url = 'http://www.start.no/tegneserier/bizarro/' + url = 'http://underholdning.no.msn.com/tegneserier/bizarro/' start_date = '1985-01-01' - end_date = '2009-06-24' # No longer hosted at start.no - history_capable_days = 30 + history_capable_days = 12 schedule = 'Mo,Tu,We,Th,Fr,Sa,Su' time_zone = 1 rights = 'Dan Piraro' class ComicCrawler(BaseComicCrawler): def _get_url(self): - self.url = 'http://g2.start.no/tegneserier/striper/bizarro/biz-striper/biz%(date)s.gif' % { - 'date': self.pub_date.strftime('%Y%m%d'), - } + self.parse_feed('http://underholdning.no.msn.com/rss/bizarro.aspx') + + for entry in self.feed.entries: + if self.timestamp_to_date(entry.updated_parsed) == self.pub_date: + self.url = entry.enclosures[0].href + return
51aca89cfcac99ffb0fa9304e55fad34a911bdc9
sconsole/manager.py
sconsole/manager.py
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.jidtree = sconsole.jidtree.JIDView() self.body_frame = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body_frame, header=self.header, footer=self.footer) def body(self): return urwid.Frame(self.jidtree.listbox, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.run()
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.jidtree = sconsole.jidtree.JIDView() self.body_frame = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body_frame, header=self.header, footer=self.footer) def body(self): return urwid.Frame(self.jidtree.listbox, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.set_alarm_in(1, self.jidtree.update) loop.run()
Call an update method to manage incoming jobs
Call an update method to manage incoming jobs
Python
apache-2.0
saltstack/salt-console
--- +++ @@ -40,4 +40,5 @@ self.view, palette=palette, unhandled_input=self.unhandled_input) + loop.set_alarm_in(1, self.jidtree.update) loop.run()
8cc66b50f3b4b7708ccf46e263cffba8e69dc1a2
climlab/__init__.py
climlab/__init__.py
__version__ = '0.2.3' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
__version__ = '0.2.4' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
Increment version number to 0.2.4 with performance improvements in transmissivity code.
Increment version number to 0.2.4 with performance improvements in transmissivity code.
Python
mit
cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab
--- +++ @@ -1,4 +1,4 @@ -__version__ = '0.2.3' +__version__ = '0.2.4' # This list defines all the modules that will be loaded if a user invokes # from climLab import *
2510e85a0b09c3b8a8909d74a25b444072c740a8
test/test_integration.py
test/test_integration.py
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/google") response = connRouter.getresponse() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection("localhost", 8888) connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com/&ttl=10") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection("localhost", 8666) connRouter.request("GET", "/google") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 302) connRouter.close() connConfig2 = http.client.HTTPConnection("localhost", 8888) connConfig2.request("DELETE","/configure?location=/google") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main()
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/httpbin") response = connRouter.getresponse() data = response.read() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection("localhost", 8888) connConfig.request("GET","/configure?location=/httpbin&upstream=http://httpbin.org/anything&ttl=10") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection("localhost", 8666) connRouter.request("GET", "/httpbin") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 200) connRouter.close() connConfig2 = http.client.HTTPConnection("localhost", 8888) connConfig2.request("DELETE","/configure?location=/httpbin") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main()
Fix tests to use httpbin.org, return always 200
Fix tests to use httpbin.org, return always 200
Python
apache-2.0
dhiaayachi/dynx,dhiaayachi/dynx
--- +++ @@ -7,28 +7,29 @@ def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) - connRouter.request("GET", "/google") + connRouter.request("GET", "/httpbin") response = connRouter.getresponse() + data = response.read() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection("localhost", 8888) - connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com/&ttl=10") + connConfig.request("GET","/configure?location=/httpbin&upstream=http://httpbin.org/anything&ttl=10") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection("localhost", 8666) - connRouter.request("GET", "/google") + connRouter.request("GET", "/httpbin") response = connRouter.getresponse() data = response.read() - self.assertEqual(response.status, 302) + self.assertEqual(response.status, 200) connRouter.close() connConfig2 = http.client.HTTPConnection("localhost", 8888) - connConfig2.request("DELETE","/configure?location=/google") + connConfig2.request("DELETE","/configure?location=/httpbin") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200)
765dd18fb05c0cef21b9dce7cbddda3c079f0b7d
logtoday/tests.py
logtoday/tests.py
from django.test import TestCase from django.urls import resolve class HomePageTest(TestCase): fixtures = ['tests/functional/auth_dump.json'] def test_root_url_resolves_to_index_page_view(self): found = resolve("/") self.assertEqual(found.view_name, "index") def test_uses_login_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'login.html') def test_redirects_login_and_logout(self): response = self.client.post('/login/', {'username': 'admin', 'password': 'administration'}) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/dashboard/') response = self.client.get('/logout/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/')
from django.test import TestCase from django.urls import resolve class HomePageTest(TestCase): fixtures = ['tests/functional/auth_dump.json'] def test_root_url_resolves_to_index_page_view(self): found = resolve("/") self.assertEqual(found.view_name, "index") def test_uses_login_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'login.html') def test_redirects_login_and_logout(self): response = self.client.post('/login/', {'username': 'admin', 'password': 'administration'}) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/dashboard/') response = self.client.get('/logout/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') def test_uses_dashboard_landing_page(self): # login is required to access /dashboard url. self.client.post('/login/', {'username': 'admin', 'password': 'administration'}) response = self.client.get('/dashboard', follow=True) self.assertTemplateUsed(response, 'dashboard/landing_page.html')
Add unittest for dashboard redirection and template
Add unittest for dashboard redirection and template Test that checks template rendered by /dashboard endpoint.
Python
mit
sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily
--- +++ @@ -22,3 +22,10 @@ response = self.client.get('/logout/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') + + def test_uses_dashboard_landing_page(self): + # login is required to access /dashboard url. + self.client.post('/login/', {'username': 'admin', + 'password': 'administration'}) + response = self.client.get('/dashboard', follow=True) + self.assertTemplateUsed(response, 'dashboard/landing_page.html')
2c95054842db106883a400e5d040aafc31b123dd
comics/meta/base.py
comics/meta/base.py
import datetime as dt from comics.core.models import Comic class MetaBase(object): # Required values name = None language = None url = None # Default values start_date = None end_date = None rights = '' @property def slug(self): return self.__module__.split('.')[-1] def create_comic(self): if Comic.objects.filter(slug=self.slug).count(): comic = Comic.objects.get(slug=self.slug) comic.name = self.name comic.language = self.language comic.url = self.url else: comic = Comic( name=self.name, slug=self.slug, language=self.language, url=self.url) comic.start_date = self._get_date(self.start_date) comic.end_date = self._get_date(self.end_date) comic.rights = self.rights comic.save() def _get_date(self, date): if date is None: return None return dt.datetime.strptime(date, '%Y-%m-%d').date()
import datetime as dt from comics.core.models import Comic class MetaBase(object): # Required values name = None language = None url = None # Default values active = True start_date = None end_date = None rights = '' @property def slug(self): return self.__module__.split('.')[-1] def create_comic(self): if Comic.objects.filter(slug=self.slug).count(): comic = Comic.objects.get(slug=self.slug) comic.name = self.name comic.language = self.language comic.url = self.url else: comic = Comic( name=self.name, slug=self.slug, language=self.language, url=self.url) comic.active = self.active comic.start_date = self._get_date(self.start_date) comic.end_date = self._get_date(self.end_date) comic.rights = self.rights comic.save() def _get_date(self, date): if date is None: return None return dt.datetime.strptime(date, '%Y-%m-%d').date()
Add new boolean field MetaBase.active
Add new boolean field MetaBase.active
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics
--- +++ @@ -9,6 +9,7 @@ url = None # Default values + active = True start_date = None end_date = None rights = '' @@ -29,6 +30,7 @@ slug=self.slug, language=self.language, url=self.url) + comic.active = self.active comic.start_date = self._get_date(self.start_date) comic.end_date = self._get_date(self.end_date) comic.rights = self.rights
7c9b93106d741568e64917ddb4c989a9fecdea17
typesetter/typesetter.py
typesetter/typesetter.py
from flask import Flask, render_template, jsonify app = Flask(__name__) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] for word in WORDS: if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return jsonify(results) def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
from functools import lru_cache from flask import Flask, render_template, jsonify app = Flask(__name__) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = find_matches(fragment) return jsonify(results) @lru_cache() def find_matches(fragment): results = [] for word in WORDS: if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return results def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
Use LRU cache to further improve search response times
Use LRU cache to further improve search response times
Python
mit
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
--- +++ @@ -1,3 +1,5 @@ +from functools import lru_cache + from flask import Flask, render_template, jsonify @@ -16,6 +18,13 @@ @app.route('/api/search/<fragment>') def search(fragment): + results = find_matches(fragment) + + return jsonify(results) + + +@lru_cache() +def find_matches(fragment): results = [] for word in WORDS: @@ -25,7 +34,7 @@ 'category': classify(word), }) - return jsonify(results) + return results def classify(word):
ec30ac35feb0708414cfa70e8c42425fa25f74c2
components/utilities.py
components/utilities.py
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") else: return unicode(str(obj), "utf-8") def Unescape(ch): if ch == "0": return chr(0) elif ch == "\'": return "\'" elif ch == "\"": return "\"" elif ch == "b": return "\b" elif ch == "n": return "\n" elif ch == "r": return "\r" elif ch == "t": return "\t" elif ch == "Z": return chr(26) elif ch == "\\": return "\\" elif ch == "%": # keep escape: like <literal string> return "\\%" elif ch == "_": return "\\_"
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") else: return unicode(str(obj), "utf-8") def Unescape(ch): if ch == "0": return chr(0) elif ch == "\'": return "\'" elif ch == "\"": return "\"" elif ch == "b": return "\b" elif ch == "n": return "\n" elif ch == "r": return "\r" elif ch == "t": return "\t" elif ch == "Z": return chr(26) elif ch == "\\": return "\\" elif ch == "%": # keep escape: like <literal string> return "\\%" elif ch == "_": return "\\_" def EscapeHtml(ch): mapping = {u"&": u"&amp;", u"<": u"&lt;", u">": u"&gt;", u"\"": u"&quot;", u"\'": u"&#39;"} return mapping[ch] if mapping.has_key(ch) else ch
Add EscapeHtml function (need to change it to a class)
Add EscapeHtml function (need to change it to a class)
Python
mit
lnishan/SQLGitHub
--- +++ @@ -40,3 +40,11 @@ return "\\%" elif ch == "_": return "\\_" + +def EscapeHtml(ch): + mapping = {u"&": u"&amp;", + u"<": u"&lt;", + u">": u"&gt;", + u"\"": u"&quot;", + u"\'": u"&#39;"} + return mapping[ch] if mapping.has_key(ch) else ch
a1acbcfc41a3f55e58e0f240eedcdf6568de4850
test/contrib/test_securetransport.py
test/contrib/test_securetransport.py
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import ( WrappedSocket, inject_into_urllib3, extract_from_urllib3 ) except ImportError as e: pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def setup_module(): inject_into_urllib3() def teardown_module(): extract_from_urllib3() def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
Fix skip logic in SecureTransport tests
Fix skip logic in SecureTransport tests
Python
mit
urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3
--- +++ @@ -6,11 +6,26 @@ import pytest try: - from urllib3.contrib.securetransport import ( - WrappedSocket, inject_into_urllib3, extract_from_urllib3 - ) -except ImportError as e: - pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) + from urllib3.contrib.securetransport import WrappedSocket +except ImportError: + pass + + +def setup_module(): + try: + from urllib3.contrib.securetransport import inject_into_urllib3 + inject_into_urllib3() + except ImportError as e: + pytest.skip('Could not import SecureTransport: %r' % e) + + +def teardown_module(): + try: + from urllib3.contrib.securetransport import extract_from_urllib3 + extract_from_urllib3() + except ImportError: + pass + from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 @@ -18,16 +33,8 @@ ) -def setup_module(): - inject_into_urllib3() - - -def teardown_module(): - extract_from_urllib3() - - def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): - ws._custom_validate(True, b"") +ws._custom_validate(True, b"")
e2234d41831d513b4da17d1031e2856785d23089
ui/__init__.py
ui/__init__.py
import multiprocessing as mp class UI: def __init__(self, game): parent_conn, child_conn = mp.Pipe(duplex=False) self.ui_event_pipe = parent_conn self.game = game def get_move(self): raise Exception("Method 'get_move' not implemented.") def update(self): raise Exception("Method 'update' not implemented.") def run(self, mainloop): return mainloop()
class UI: def __init__(self, game): self.game = game def get_move(self): raise Exception("Method 'get_move' not implemented.") def update(self): raise Exception("Method 'update' not implemented.") def run(self, mainloop): return mainloop()
Remove unused UI event pipe
Remove unused UI event pipe
Python
mit
ethanal/othello,ethanal/othello
--- +++ @@ -1,11 +1,6 @@ -import multiprocessing as mp - - class UI: def __init__(self, game): - parent_conn, child_conn = mp.Pipe(duplex=False) - self.ui_event_pipe = parent_conn self.game = game def get_move(self):
f61ba51f92ff47716128bb9d607b4cb46e7bfa4b
gblinks/cli.py
gblinks/cli.py
# -*- coding: utf-8 -*- import click import json import sys from gblinks import Gblinks def check_broken_links(gblinks): broken_links = gblinks.check_broken_links() if broken_links: print_links(broken_links) click.echo( click.style( '%d broken links found in the given path' % len(broken_links) , fg='red' ) ) sys.exit(-1) else: click.echo('No broken links found in the given path') def list_links(gblinks): links = gblinks.get_links() print_links(links) click.echo('%d links found in the given path' % len(links)) def print_links(links): for link in links: click.echo(json.dumps(link, sort_keys=True, indent=4)) @click.command() @click.argument('path') @click.option('--check/--no-check', default=False) @click.option('--list/--no-list', default=False) def main(path, check, list): gblinks = Gblinks(path) if check: check_broken_links(gblinks) if list: list_links(gblinks) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- import click import json import sys from gblinks import Gblinks def check_broken_links(gblinks): broken_links = gblinks.check_broken_links() if broken_links: print_links(broken_links) click.echo( click.style( '%d broken links found in the given path' % len(broken_links) , fg='red' ) ) sys.exit(-2) else: click.echo('No broken links found in the given path') def list_links(gblinks): links = gblinks.get_links() print_links(links) click.echo('%d links found in the given path' % len(links)) def print_links(links): for link in links: click.echo(json.dumps(link, sort_keys=True, indent=4)) @click.command() @click.argument('path') @click.option('--check/--no-check', default=False) @click.option('--list/--no-list', default=False) def main(path, check, list): try: gblinks = Gblinks(path) if check: check_broken_links(gblinks) if list: list_links(gblinks) except ValueError, e: click.echo(click.style(str(e), fg='red')) sys.exit(-1) if __name__ == "__main__": main()
Add code to handle exception
Add code to handle exception
Python
mit
davidmogar/gblinks
--- +++ @@ -19,7 +19,7 @@ ) ) - sys.exit(-1) + sys.exit(-2) else: click.echo('No broken links found in the given path') @@ -37,13 +37,17 @@ @click.option('--check/--no-check', default=False) @click.option('--list/--no-list', default=False) def main(path, check, list): - gblinks = Gblinks(path) + try: + gblinks = Gblinks(path) - if check: - check_broken_links(gblinks) + if check: + check_broken_links(gblinks) - if list: - list_links(gblinks) + if list: + list_links(gblinks) + except ValueError, e: + click.echo(click.style(str(e), fg='red')) + sys.exit(-1) if __name__ == "__main__": main()
c24f497bb3595e3034a8c641a88527092e27c450
testdoc/tests/test_formatter.py
testdoc/tests/test_formatter.py
import StringIO import unittest from testdoc.formatter import WikiFormatter class WikiFormatterTest(unittest.TestCase): def setUp(self): self.stream = StringIO.StringIO() self.formatter = WikiFormatter(self.stream) def test_title(self): self.formatter.title('foo') self.assertEqual(self.stream.getvalue(), '= foo =\n\n') def test_section(self): self.formatter.section('foo') self.assertEqual(self.stream.getvalue(), '== foo ==\n\n') def test_subsection(self): self.formatter.subsection('foo') self.assertEqual(self.stream.getvalue(), '=== foo ===\n\n') def test_paragraph(self): self.formatter.paragraph('\nfoo\nbar\n') self.assertEqual(self.stream.getvalue(), 'foo\nbar\n\n')
import StringIO import unittest from testdoc.formatter import WikiFormatter class WikiFormatterTest(unittest.TestCase): def setUp(self): self.stream = StringIO.StringIO() self.formatter = WikiFormatter(self.stream) def test_title(self): self.formatter.title('foo') self.assertEqual(self.stream.getvalue(), '= foo =\n\n') def test_section(self): self.formatter.section('foo') self.assertEqual(self.stream.getvalue(), '\n== foo ==\n\n') def test_subsection(self): self.formatter.subsection('foo') self.assertEqual(self.stream.getvalue(), '=== foo ===\n\n') def test_paragraph(self): self.formatter.paragraph('\nfoo\nbar\n') self.assertEqual(self.stream.getvalue(), 'foo\nbar\n\n')
Fix a bug in the tests.
Fix a bug in the tests.
Python
mit
testing-cabal/testdoc
--- +++ @@ -15,7 +15,7 @@ def test_section(self): self.formatter.section('foo') - self.assertEqual(self.stream.getvalue(), '== foo ==\n\n') + self.assertEqual(self.stream.getvalue(), '\n== foo ==\n\n') def test_subsection(self): self.formatter.subsection('foo')
045192dd0a69dfe581075e76bbb7ca4676d321b8
test_project/urls.py
test_project/urls.py
from django.conf.urls import url from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda request, *args, **kwargs: HttpResponse()), url(r'^admin/', admin.site.urls), ]
from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), re_path(r'^admin/', admin.site.urls), ]
Replace url() with re_path() available in newer Django
Replace url() with re_path() available in newer Django
Python
bsd-3-clause
ecometrica/django-vinaigrette
--- +++ @@ -1,9 +1,9 @@ -from django.conf.urls import url +from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ - url(r'^$', lambda request, *args, **kwargs: HttpResponse()), - url(r'^admin/', admin.site.urls), + re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), + re_path(r'^admin/', admin.site.urls), ]
c30347f34967ee7634676e0e4e27164910f9e52b
regparser/tree/xml_parser/note_processor.py
regparser/tree/xml_parser/note_processor.py
from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor) class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes:" headers""" def matches(self, xml): return xml.tag == 'HD' and xml.text.lower().startswith('note') def derive_nodes(self, xml, processor=None): return [] class NoteProcessor(paragraph_processor.ParagraphProcessor): MATCHERS = [simple_hierarchy_processor.DepthParagraphMatcher(), IgnoreNotesHeader(), paragraph_processor.IgnoreTagMatcher('PRTPAGE')] def additional_constraints(self): return [optional_rules.limit_paragraph_types( mtypes.lower, mtypes.ints, mtypes.roman, mtypes.markerless)] class NoteMatcher(paragraph_processor.BaseMatcher): """Processes the contents of NOTE and NOTES tags using a NoteProcessor""" def matches(self, xml): return xml.tag in ('NOTE', 'NOTES') def derive_nodes(self, xml, processor=None): processor = NoteProcessor() node = Node(label=[mtypes.MARKERLESS], source_xml=xml, node_type=Node.NOTE) return [processor.process(xml, node)]
import re from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor) class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes:" headers""" REGEX = re.compile('notes?:?\s*$', re.IGNORECASE) def matches(self, xml): return xml.tag == 'HD' and self.REGEX.match(xml.text or '') def derive_nodes(self, xml, processor=None): return [] class NoteProcessor(paragraph_processor.ParagraphProcessor): MATCHERS = [simple_hierarchy_processor.DepthParagraphMatcher(), IgnoreNotesHeader(), paragraph_processor.IgnoreTagMatcher('PRTPAGE')] def additional_constraints(self): return [optional_rules.limit_paragraph_types( mtypes.lower, mtypes.ints, mtypes.roman, mtypes.markerless)] class NoteMatcher(paragraph_processor.BaseMatcher): """Processes the contents of NOTE and NOTES tags using a NoteProcessor""" def matches(self, xml): return xml.tag in ('NOTE', 'NOTES') def derive_nodes(self, xml, processor=None): processor = NoteProcessor() node = Node(label=[mtypes.MARKERLESS], source_xml=xml, node_type=Node.NOTE) return [processor.process(xml, node)]
Use regex rather than string match for Note:
Use regex rather than string match for Note: Per suggestion from @tadhg-ohiggins
Python
cc0-1.0
eregs/regulations-parser,tadhg-ohiggins/regulations-parser,tadhg-ohiggins/regulations-parser,cmc333333/regulations-parser,cmc333333/regulations-parser,eregs/regulations-parser
--- +++ @@ -1,3 +1,5 @@ +import re + from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( @@ -6,8 +8,10 @@ class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes:" headers""" + REGEX = re.compile('notes?:?\s*$', re.IGNORECASE) + def matches(self, xml): - return xml.tag == 'HD' and xml.text.lower().startswith('note') + return xml.tag == 'HD' and self.REGEX.match(xml.text or '') def derive_nodes(self, xml, processor=None): return []
49d67984d318d64528244ff525062210f94bd033
tests/helpers.py
tests/helpers.py
import numpy as np import glfw def step_env(env, max_path_length=100, iterations=1): """Step env helper.""" for _ in range(iterations): env.reset() for _ in range(max_path_length): _, _, done, _ = env.step(env.action_space.sample()) env.render() if done: break def close_env(env): """Close env helper.""" if env.viewer is not None: glfw.destroy_window(env.viewer.window) env.viewer = None
import numpy as np import glfw def step_env(env, max_path_length=100, iterations=1): """Step env helper.""" for _ in range(iterations): env.reset() for _ in range(max_path_length): _, _, done, _ = env.step(env.action_space.sample()) env.render() if done: break def close_env(env): """Close env helper.""" if env.viewer is not None: glfw.destroy_window(env.viewer.window) env.viewer = None
Fix indentation to pass the tests
Fix indentation to pass the tests
Python
mit
rlworkgroup/metaworld,rlworkgroup/metaworld
--- +++ @@ -13,6 +13,6 @@ def close_env(env): """Close env helper.""" - if env.viewer is not None: - glfw.destroy_window(env.viewer.window) - env.viewer = None + if env.viewer is not None: + glfw.destroy_window(env.viewer.window) + env.viewer = None
e159465d4495ed2ebcbd1515d82f4f85fc28c8f7
corral/views/private.py
corral/views/private.py
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Blueprint(__name__, 'private') private.before_request(enforce_auth) @handle_errors(private) def json_error(e): """Return an error response like {"msg":"Method not allowed"}.""" return jsonify({'msg': e.name}), e.code @private.route('/download/<site_id>/<int:param>', methods=['POST']) def home(site_id, param): """Attempt to download the file.""" if site_id in current_app.config['SITES']: site = current_app.config['SITES'][site_id] g.site = site url = site['url'].format(param) filename = site['filename'].format(param) path = join(site['path'], filename) download(url, path) return jsonify({}) raise NotFound @private.after_request def cors(response): """Handle browser cross-origin requests.""" if 'origin' in request.headers: site = g.get('site') if site: allowed_origin = site['origin'] response.headers['Access-Control-Allow-Origin'] = allowed_origin return response
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Blueprint(__name__, 'private') private.before_request(enforce_auth) @handle_errors(private) def json_error(e): """Return an error response like {"msg":"Not Found"}.""" return jsonify({'msg': e.name}), e.code @private.route('/download/<site_id>/<int:param>', methods=['POST']) def home(site_id, param): """Attempt to download the file.""" if site_id in current_app.config['SITES']: site = current_app.config['SITES'][site_id] g.site = site url = site['url'].format(param) filename = site['filename'].format(param) path = join(site['path'], filename) download(url, path) return jsonify({}) raise NotFound @private.after_request def cors(response): """Handle browser cross-origin requests.""" if 'origin' in request.headers: site = g.get('site') if site: allowed_origin = site['origin'] response.headers['Access-Control-Allow-Origin'] = allowed_origin return response
Use a better example error message
Use a better example error message
Python
mit
nickfrostatx/corral,nickfrostatx/corral,nickfrostatx/corral
--- +++ @@ -14,7 +14,7 @@ @handle_errors(private) def json_error(e): - """Return an error response like {"msg":"Method not allowed"}.""" + """Return an error response like {"msg":"Not Found"}.""" return jsonify({'msg': e.name}), e.code
592be8dc73b4da45c948eac133ceb018c60c3be7
src/pysme/matrix_form.py
src/pysme/matrix_form.py
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' return A @ B - B @ A def D(c, rho): '''Calculate the application of the diffusion superoperator D[c] to rho ''' c_dag = c.conjugate().T return c @ rho @ c_dag - (c_dag @ c @ rho + rho @ c_dag @ c) / 2 def euler_integrate(rho_0, rho_dot_fn, times): rhos = [rho_0] dts = np.diff(times) for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) return np.array(rhos)
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' return A @ B - B @ A def D(c, rho): '''Calculate the application of the diffusion superoperator D[c] to rho ''' c_dag = c.conjugate().T return c @ rho @ c_dag - (c_dag @ c @ rho + rho @ c_dag @ c) / 2 def euler_integrate(rho_0, rho_dot_fn, times): rhos = [rho_0] dts = np.diff(times) for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) return rhos
Change euler integrator to return list, not array
Change euler integrator to return list, not array The state of the system is a heterogeneous data type for some applications, so the array isn't appropriate.
Python
mit
CQuIC/pysme
--- +++ @@ -27,4 +27,4 @@ for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) - return np.array(rhos) + return rhos
763077f355386b8a5fdb4bda44f5d2856563f674
sklearn_porter/estimator/EstimatorApiABC.py
sklearn_porter/estimator/EstimatorApiABC.py
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template. kwargs Returns ------- The ported estimator. """ pass @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. kwargs Returns ------- The paths to the dumped files. """ pass
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- language : Language The required language. template : Template The required template. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The ported estimator. """ @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- language : Language The required language. template : Template The required template directory : str or Path The destination directory. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """
Remove unused imports and `pass` keywords
feature/oop-api-refactoring: Remove unused imports and `pass` keywords
Python
bsd-3-clause
nok/sklearn-porter
--- +++ @@ -4,7 +4,7 @@ from pathlib import Path from abc import ABC, abstractmethod -from sklearn_porter.enums import Method, Language, Template +from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): @@ -27,19 +27,18 @@ Parameters ---------- - method : Method - The required method. language : Language The required language. template : Template The required template. + to_json : bool (default: False) + Return the result as JSON string. kwargs Returns ------- The ported estimator. """ - pass @abstractmethod def dump( @@ -55,18 +54,17 @@ Parameters ---------- - method : Method - The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. + to_json : bool (default: False) + Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """ - pass
605202c7be63f2676b24b5f2202bfa0aa09c9e08
javelin/ase.py
javelin/ase.py
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): f = open(filename) lines = f.readlines() f.close() a = b = c = alpha = beta = gamma = 0 reading_atom_list = False symbols = [] positions = [] for l in lines: line = l.replace(',', ' ').split() if not reading_atom_list: # Wait for 'atoms' line before reading atoms if line[0] == 'cell': a, b, c, alpha, beta, gamma = [float(x) for x in line[1:7]] cell = unit_cell_to_vectors(a, b, c, alpha, beta, gamma) if line[0] == 'atoms': if a == 0: print("Cell not found") cell = None reading_atom_list = True else: symbol, x, y, z = line[:4] symbol = symbol.capitalize() symbols.append(symbol) positions.append([float(x), float(y), float(z)]) # Return ASE Atoms object return Atoms(symbols=symbols, scaled_positions=positions, cell=cell)
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): with open(filename) as f: lines = f.readlines() a = b = c = alpha = beta = gamma = 0 reading_atom_list = False symbols = [] positions = [] for l in lines: line = l.replace(',', ' ').split() if not reading_atom_list: # Wait for 'atoms' line before reading atoms if line[0] == 'cell': a, b, c, alpha, beta, gamma = [float(x) for x in line[1:7]] cell = unit_cell_to_vectors(a, b, c, alpha, beta, gamma) if line[0] == 'atoms': if a == 0: print("Cell not found") cell = None reading_atom_list = True else: symbol, x, y, z = line[:4] symbol = symbol.capitalize() symbols.append(symbol) positions.append([float(x), float(y), float(z)]) # Return ASE Atoms object return Atoms(symbols=symbols, scaled_positions=positions, cell=cell)
Use with to open file in read_stru
Use with to open file in read_stru
Python
mit
rosswhitfield/javelin
--- +++ @@ -6,9 +6,8 @@ def read_stru(filename): - f = open(filename) - lines = f.readlines() - f.close() + with open(filename) as f: + lines = f.readlines() a = b = c = alpha = beta = gamma = 0
503d3efd882466be4c846f74bd8eac9b90807dc2
services/myspace.py
services/myspace.py
import foauth.providers class MySpace(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.myspace.com/' docs_url = 'http://developerwiki.myspace.com/index.php?title=RESTful_API_Overview' category = 'Social' # URLs to interact with the API request_token_url = 'http://api.myspace.com/request_token' authorize_url = 'http://api.myspace.com/authorize' access_token_url = 'http://api.myspace.com/access_token' api_domain = 'api.myspace.com' available_permissions = [ (None, 'read and write your social information'), ]
import foauth.providers class MySpace(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.myspace.com/' docs_url = 'http://developerwiki.myspace.com/index.php?title=RESTful_API_Overview' category = 'Social' # URLs to interact with the API request_token_url = 'http://api.myspace.com/request_token' authorize_url = 'http://api.myspace.com/authorize' access_token_url = 'http://api.myspace.com/access_token' api_domain = 'api.myspace.com' available_permissions = [ (None, 'read and write your social information'), ]
Remove an unnecessary blank line
Remove an unnecessary blank line
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
--- +++ @@ -16,4 +16,3 @@ available_permissions = [ (None, 'read and write your social information'), ] -
8c5dba68915bb1cdba3c56eff15fdf67c5feed00
tests/test_global.py
tests/test_global.py
import unittest import cbs class MySettings(cbs.GlobalSettings): PROJECT_NAME = 'tests' @property def TEMPLATE_LOADERS(self): return super(MySettings, self).TEMPLATE_LOADERS + ('test',) class GlobalSettingsTest(unittest.TestCase): def test_precedence(self): g = {} cbs.apply(MySettings, g) self.assertTrue(len(g['TEMPLATE_LOADERS']), 3)
import unittest import cbs class MySettings(cbs.GlobalSettings): PROJECT_NAME = 'tests' @property def INSTALLED_APPS(self): return super(MySettings, self).INSTALLED_APPS + ('test',) class GlobalSettingsTest(unittest.TestCase): def test_precedence(self): g = {} cbs.apply(MySettings, g) self.assertTrue('INSTALLED_APPS']), 1)
Update tests for new default globals
Update tests for new default globals
Python
bsd-2-clause
funkybob/django-classy-settings
--- +++ @@ -7,8 +7,8 @@ PROJECT_NAME = 'tests' @property - def TEMPLATE_LOADERS(self): - return super(MySettings, self).TEMPLATE_LOADERS + ('test',) + def INSTALLED_APPS(self): + return super(MySettings, self).INSTALLED_APPS + ('test',) class GlobalSettingsTest(unittest.TestCase): @@ -17,4 +17,4 @@ g = {} cbs.apply(MySettings, g) - self.assertTrue(len(g['TEMPLATE_LOADERS']), 3) + self.assertTrue('INSTALLED_APPS']), 1)
8fb574900a6680f8342487e32979829efa33a11a
spacy/about.py
spacy/about.py
# fmt: off __title__ = "spacy" __version__ = "3.0.0.dev14" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" __shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json" __projects__ = "https://github.com/explosion/spacy-boilerplates"
# fmt: off __title__ = "spacy_nightly" __version__ = "3.0.0a0" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" __shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json" __projects__ = "https://github.com/explosion/spacy-boilerplates"
Update parent package and version
Update parent package and version
Python
mit
explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
--- +++ @@ -1,6 +1,6 @@ # fmt: off -__title__ = "spacy" -__version__ = "3.0.0.dev14" +__title__ = "spacy_nightly" +__version__ = "3.0.0a0" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
5fe4351ea52c8cb11af1cb61d65cb5f765638fd1
tap/tests/test_runner.py
tap/tests/test_runner.py
# Copyright (c) 2014, Matt Layman import tempfile import unittest from tap import TAPTestRunner from tap.runner import TAPTestResult class TestTAPTestRunner(unittest.TestCase): def test_has_tap_test_result(self): runner = TAPTestRunner() self.assertEqual(runner.resultclass, TAPTestResult) def test_runner_uses_outdir(self): """Test that the test runner sets the TAPTestResult OUTDIR so that TAP files will be written to that location. Setting class attributes to get the right behavior is a dirty hack, but the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. previous_outdir = TAPTestResult outdir = tempfile.mkdtemp() TAPTestRunner.set_outdir(outdir) self.assertEqual(outdir, TAPTestResult.OUTDIR) TAPTestResult.OUTDIR = previous_outdir
# Copyright (c) 2014, Matt Layman import tempfile import unittest from tap import TAPTestRunner from tap.runner import TAPTestResult class TestTAPTestRunner(unittest.TestCase): def test_has_tap_test_result(self): runner = TAPTestRunner() self.assertEqual(runner.resultclass, TAPTestResult) def test_runner_uses_outdir(self): """Test that the test runner sets the TAPTestResult OUTDIR so that TAP files will be written to that location. Setting class attributes to get the right behavior is a dirty hack, but the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. previous_outdir = TAPTestResult.OUTDIR outdir = tempfile.mkdtemp() TAPTestRunner.set_outdir(outdir) self.assertEqual(outdir, TAPTestResult.OUTDIR) TAPTestResult.OUTDIR = previous_outdir
Fix the runner test where it wasn't setting outdir.
Fix the runner test where it wasn't setting outdir.
Python
bsd-2-clause
blakev/tappy,python-tap/tappy,Mark-E-Hamilton/tappy,mblayman/tappy
--- +++ @@ -21,7 +21,7 @@ the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. - previous_outdir = TAPTestResult + previous_outdir = TAPTestResult.OUTDIR outdir = tempfile.mkdtemp() TAPTestRunner.set_outdir(outdir)