commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
8762ae185d3febe06f6ef5acfa082b26063358a2
example_migration.py
example_migration.py
from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} dest_config = {'directory': 'some_directory'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start))
from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} dest_config = {'directory': 'some_directory', 'timezone': 'US/Eastern'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start))
Add timezone to example to keep Broker happy.
Add timezone to example to keep Broker happy.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} - dest_config = {'directory': 'some_directory'} + dest_config = {'directory': 'some_directory', + 'timezone': 'US/Eastern'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start))
Add timezone to example to keep Broker happy.
## Code Before: from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} dest_config = {'directory': 'some_directory'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start)) ## Instruction: Add timezone to example to keep Broker happy. ## Code After: from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} dest_config = {'directory': 'some_directory', 'timezone': 'US/Eastern'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start))
from metadatastore.mds import MDSRO from portable_mds.mongoquery.mds import MDS source_config = {'host': 'localhost', 'port': 27017, 'database': 'metadatastore_production_v1', 'timezone': 'US/Eastern'} - dest_config = {'directory': 'some_directory'} ? ^ + dest_config = {'directory': 'some_directory', ? ^ + 'timezone': 'US/Eastern'} source = MDSRO(source_config) dest = MDS(dest_config) for run_start in source.find_run_starts(): dest.insert_run_start(**run_start) for desc in source.find_descriptors(run_start=run_start): events = source.get_events_generator(descriptor=desc) dest.insert_descriptor(**desc) dest.bulk_insert_events(desc, events) dest.insert_run_stop(**source.stop_by_start(run_start))
8858cf1f0b87026ce913a19c4e5df415409cfd79
streak-podium/read.py
streak-podium/read.py
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ if org_name is None: org_name = 'pulseenergy' url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Handle None for org or file with default org name
Handle None for org or file with default org name
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ + if org_name is None: + org_name = 'pulseenergy' + url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Handle None for org or file with default org name
## Code Before: import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text ## Instruction: Handle None for org or file with default org name ## Code After: import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ if org_name is None: org_name = 'pulseenergy' url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ + if org_name is None: + org_name = 'pulseenergy' + url = 'https://github.com/orgs/{}/members'.format(org_name) headers = {'Accept': 'application/vnd.github.ironman-preview+json'} try: r = requests.get(url, headers=headers) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get org members: [{}]'.format(url)) return [] if r.status_code == 404: print('Got 404') print(r.status_code) return [] print('response') print(r.text) return r.text def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
244da6a4ffa5ff8de80d18baceedcf947ef6b68e
tensorflow/python/tf2.py
tensorflow/python/tf2.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR") is not None
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR", "0") != "0"
Make TF2_BEHAVIOR=0 disable TF2 behavior.
Make TF2_BEHAVIOR=0 disable TF2 behavior. Prior to this change, the mere presence of a TF2_BEHAVIOR environment variable would enable TF2 behavior. With this, setting that environment variable to "0" will disable it. PiperOrigin-RevId: 223804383
Python
apache-2.0
freedomtan/tensorflow,kevin-coder/tensorflow-fork,aldian/tensorflow,davidzchen/tensorflow,alsrgv/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,hfp/tensorflow-xsmm,alsrgv/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,theflofly/tensorflow,renyi533/tensorflow,aam-at/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,asimshankar/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,arborh/tensorflow,gautam1858/tensorflow,kevin-coder/tensorflow-fork,sarvex/tensorflow,ageron/tensorflow,ageron/tensorflow,kevin-coder/tensorflow-fork,chemelnucfin/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,xzturn/tensorflow,chemelnucfin/tensorflow,arborh/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,cxxgtxy/tensorflow,frreiss/tensorflow-fred,jbedorf/tensorflow,xzturn/tensorflow,xzturn/tensorflow,yongtang/tensorflow,jhseu/tensorflow,hfp/tensorflow-xsmm,apark263/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,asimshankar/tensorflow,Intel-Corporation/tensorflow,ageron/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,chemelnucfin/tensorflow,xzturn/tensorflow,annarev/tensorflow,sarvex/tensorflow,annarev/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,theflofly/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,asimshankar/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,asimshankar/tensorflow,renyi533/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ghchinoy/tensorflow,renyi533/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,chemelnucfin/tensorflow,Bismarrck/tensorflow,ppwwyyxx/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,yongtang/tensorflow,renyi533/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,hfp/tensorflow-xsmm,adit-chandra/tensorflow,DavidNorman/tensorflow,gunan/tensorflow,paolodedios/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,paolodedios/tensorflow,jbedorf/tensorflow,kevin-coder/tensorflow-fork,cxxgtxy/tensorflow,alsrgv/tensorflow,aam-at/tensorflow,theflofly/tensorflow,xzturn/tensorflow,jendap/tensorflow,gunan/tensorflow,annarev/tensorflow,jhseu/tensorflow,hfp/tensorflow-xsmm,paolodedios/tensorflow,freedomtan/tensorflow,arborh/tensorflow,hfp/tensorflow-xsmm,Intel-Corporation/tensorflow,ageron/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,theflofly/tensorflow,xzturn/tensorflow,Intel-Corporation/tensorflow,alsrgv/tensorflow,DavidNorman/tensorflow,chemelnucfin/tensorflow,aldian/tensorflow,DavidNorman/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,arborh/tensorflow,aam-at/tensorflow,aam-at/tensorflow,jendap/tensorflow,jhseu/tensorflow,jbedorf/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,apark263/tensorflow,alsrgv/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,freedomtan/tensorflow,Bismarrck/tensorflow,gautam1858/tensorflow,arborh/tensorflow,hfp/tensorflow-xsmm,gautam1858/tensorflow,arborh/tensorflow,theflofly/tensorflow,gautam1858/tensorflow,chemelnucfin/tensorflow,arborh/tensorflow,aam-at/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,apark263/tensorflow,Intel-tensorflow/tensorflow,apark263/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,asimshankar/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,yongtang/tensorflow,ageron/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,petewarden/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alsrgv/tensorflow,renyi533/tensorflow,jbedorf/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,Bismarrck/tensorflow,aam-at/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ghchinoy/tensorflow,jendap/tensorflow,ppwwyyxx/tensorflow,hfp/tensorflow-xsmm,Intel-Corporation/tensorflow,aldian/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,ageron/tensorflow,Bismarrck/tensorflow,Bismarrck/tensorflow,kevin-coder/tensorflow-fork,Intel-Corporation/tensorflow,tensorflow/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,hfp/tensorflow-xsmm,Bismarrck/tensorflow,theflofly/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gunan/tensorflow,gunan/tensorflow,asimshankar/tensorflow,jendap/tensorflow,aldian/tensorflow,Bismarrck/tensorflow,ghchinoy/tensorflow,alsrgv/tensorflow,jendap/tensorflow,ageron/tensorflow,gautam1858/tensorflow,ghchinoy/tensorflow,alsrgv/tensorflow,renyi533/tensorflow,adit-chandra/tensorflow,asimshankar/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Bismarrck/tensorflow,chemelnucfin/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,petewarden/tensorflow,jendap/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ageron/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,chemelnucfin/tensorflow,apark263/tensorflow,ppwwyyxx/tensorflow,theflofly/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,renyi533/tensorflow,jhseu/tensorflow,yongtang/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,jendap/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,ghchinoy/tensorflow,adit-chandra/tensorflow,Intel-Corporation/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,DavidNorman/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,karllessard/tensorflow,jbedorf/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow-pywrap_saved_model,kevin-coder/tensorflow-fork,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jendap/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,jbedorf/tensorflow,jhseu/tensorflow,ghchinoy/tensorflow,jbedorf/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,hfp/tensorflow-xsmm,davidzchen/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,aam-at/tensorflow,annarev/tensorflow,jhseu/tensorflow,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,apark263/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,aldian/tensorflow,apark263/tensorflow,ghchinoy/tensorflow,gunan/tensorflow,asimshankar/tensorflow,chemelnucfin/tensorflow,renyi533/tensorflow,karllessard/tensorflow,sarvex/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,theflofly/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,apark263/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,jbedorf/tensorflow,gunan/tensorflow,jbedorf/tensorflow,hfp/tensorflow-xsmm,Bismarrck/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,kevin-coder/tensorflow-fork,Intel-tensorflow/tensorflow,jbedorf/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,apark263/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,asimshankar/tensorflow,arborh/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,renyi533/tensorflow,arborh/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ageron/tensorflow,annarev/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,apark263/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,apark263/tensorflow,theflofly/tensorflow,kevin-coder/tensorflow-fork,Intel-tensorflow/tensorflow,paolodedios/tensorflow,jendap/tensorflow,Intel-tensorflow/tensorflow,ageron/tensorflow,aldian/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,jendap/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,adit-chandra/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,asimshankar/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,kevin-coder/tensorflow-fork,alsrgv/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,ghchinoy/tensorflow,paolodedios/tensorflow,asimshankar/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,kevin-coder/tensorflow-fork,ageron/tensorflow,ghchinoy/tensorflow,DavidNorman/tensorflow,annarev/tensorflow,karllessard/tensorflow,ageron/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,Bismarrck/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,theflofly/tensorflow,alsrgv/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,theflofly/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,DavidNorman/tensorflow,theflofly/tensorflow,arborh/tensorflow
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" - return _force_enable or os.getenv("TF2_BEHAVIOR") is not None + return _force_enable or os.getenv("TF2_BEHAVIOR", "0") != "0"
Make TF2_BEHAVIOR=0 disable TF2 behavior.
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR") is not None ## Instruction: Make TF2_BEHAVIOR=0 disable TF2 behavior. ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" return _force_enable or os.getenv("TF2_BEHAVIOR", "0") != "0"
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os _force_enable = False def enable(): """Enables v2 behaviors.""" global _force_enable _force_enable = True def disable(): """Disables v2 behaviors (TF2_BEHAVIOR env variable is still respected).""" global _force_enable _force_enable = False def enabled(): """Returns True iff TensorFlow 2.0 behavior should be enabled.""" - return _force_enable or os.getenv("TF2_BEHAVIOR") is not None ? ^^ ^^^^^^^^ + return _force_enable or os.getenv("TF2_BEHAVIOR", "0") != "0" ? +++++ ^^ ^^^
8f0502d618a35b2b63ee280caee91c508482dbf4
services/api/app.py
services/api/app.py
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: nodes = redis.smembers(IID_INDEX) feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: # nodes = redis.smembers(IID_INDEX) # all nodes are namespaced with iid nodes = redis.keys('iid:*') feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
Update fetching nodes to manually get all keys with iid prefix instead of using an index
Update fetching nodes to manually get all keys with iid prefix instead of using an index
Python
mit
pnw/Chch-openhack,pnw/Chch-openhack
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: - nodes = redis.smembers(IID_INDEX) + # nodes = redis.smembers(IID_INDEX) - + # all nodes are namespaced with iid + nodes = redis.keys('iid:*') feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
Update fetching nodes to manually get all keys with iid prefix instead of using an index
## Code Before: import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: nodes = redis.smembers(IID_INDEX) feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run() ## Instruction: Update fetching nodes to manually get all keys with iid prefix instead of using an index ## Code After: import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: # nodes = redis.smembers(IID_INDEX) # all nodes are namespaced with iid nodes = redis.keys('iid:*') feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
import json import itertools import logging __author__ = 'patrickwalsh' from flask import Flask from redis import Redis app = Flask(__name__) logger = logging.getLogger(__name__) redis = Redis() IID_INDEX = 'index' @app.route('/intersections') def get_all_intersections(): try: - nodes = redis.smembers(IID_INDEX) + # nodes = redis.smembers(IID_INDEX) ? ++ - + # all nodes are namespaced with iid + nodes = redis.keys('iid:*') feed = itertools.imap(redis.hgetall, nodes) dehydrated = itertools.imap(dehydrate, feed) return json.dumps(dict( objects=list(dehydrated) )) except Exception as e: logger.exception(e) def dehydrate(node): keys = ['sid', 'id', 'updated_at', 'lat', 'lon', 'osm_id', 'min_cong', 'max_cong', 'avg_cong'] data = {key: node.get(key, None) for key in keys} return data if __name__ == '__main__': app.run()
6d848c4b86913d71b986ef032348a8fa8720cfc7
src/idea/utility/state_helper.py
src/idea/utility/state_helper.py
from idea.models import State def get_first_state(): """ Get the first state for an idea. """ return State.objects.get(previous__isnull=True)
from idea.models import State def get_first_state(): """ Get the first state for an idea. """ #return State.objects.get(previous__isnull=True) # previous__isnull breaks functionality if someone creates a new state # without a previous state set. since we know the initial state # is id=1 per fixtures/state.json, use that instead. return State.objects.get(id=1)
Fix add_idea when multiple States have no previous
Fix add_idea when multiple States have no previous
Python
cc0-1.0
CapeSepias/idea-box,m3brown/idea-box,geomapdev/idea-box,cmc333333/idea-box,18F/idea-box,CapeSepias/idea-box,18F/idea-box,geomapdev/idea-box,18F/idea-box,cmc333333/idea-box,CapeSepias/idea-box,m3brown/idea-box,cmc333333/idea-box,geomapdev/idea-box
from idea.models import State def get_first_state(): """ Get the first state for an idea. """ - return State.objects.get(previous__isnull=True) + #return State.objects.get(previous__isnull=True) + # previous__isnull breaks functionality if someone creates a new state + # without a previous state set. since we know the initial state + # is id=1 per fixtures/state.json, use that instead. + return State.objects.get(id=1)
Fix add_idea when multiple States have no previous
## Code Before: from idea.models import State def get_first_state(): """ Get the first state for an idea. """ return State.objects.get(previous__isnull=True) ## Instruction: Fix add_idea when multiple States have no previous ## Code After: from idea.models import State def get_first_state(): """ Get the first state for an idea. """ #return State.objects.get(previous__isnull=True) # previous__isnull breaks functionality if someone creates a new state # without a previous state set. since we know the initial state # is id=1 per fixtures/state.json, use that instead. return State.objects.get(id=1)
from idea.models import State def get_first_state(): """ Get the first state for an idea. """ - return State.objects.get(previous__isnull=True) + #return State.objects.get(previous__isnull=True) ? + + # previous__isnull breaks functionality if someone creates a new state + # without a previous state set. since we know the initial state + # is id=1 per fixtures/state.json, use that instead. + return State.objects.get(id=1)
237faf53129e575faafad6cfeecf96c707d50c4b
examples/common.py
examples/common.py
def print_devices(b): for device in sorted(b.devices, key=lambda d: len(d.ancestors)): print(device) # this is a blivet.devices.StorageDevice instance print()
def print_devices(b): print(b.devicetree)
Use DeviceTree.__str__ when printing devices in examples.
Use DeviceTree.__str__ when printing devices in examples.
Python
lgpl-2.1
AdamWill/blivet,vojtechtrefny/blivet,rhinstaller/blivet,vpodzime/blivet,vojtechtrefny/blivet,AdamWill/blivet,rvykydal/blivet,rvykydal/blivet,jkonecny12/blivet,rhinstaller/blivet,jkonecny12/blivet,vpodzime/blivet
def print_devices(b): + print(b.devicetree) - for device in sorted(b.devices, key=lambda d: len(d.ancestors)): - print(device) # this is a blivet.devices.StorageDevice instance - print() -
Use DeviceTree.__str__ when printing devices in examples.
## Code Before: def print_devices(b): for device in sorted(b.devices, key=lambda d: len(d.ancestors)): print(device) # this is a blivet.devices.StorageDevice instance print() ## Instruction: Use DeviceTree.__str__ when printing devices in examples. ## Code After: def print_devices(b): print(b.devicetree)
def print_devices(b): + print(b.devicetree) - for device in sorted(b.devices, key=lambda d: len(d.ancestors)): - print(device) # this is a blivet.devices.StorageDevice instance - - print()
ef2c1115fdebfacea76d19b3fac6bbde7f0cbbf2
gitlab_tests/test_v91/test_tags.py
gitlab_tests/test_v91/test_tags.py
import responses from gitlab.exceptions import HttpError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.assertRaises(HttpError, self.gitlab.delete_repository_tag, 5, 'test')
import responses from requests.exceptions import HTTPError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.gitlab.suppress_http_error = False self.assertRaises(HTTPError, self.gitlab.delete_repository_tag, 5, 'test') self.gitlab.suppress_http_error = True
Update Tags cases for new behaviour
tests: Update Tags cases for new behaviour See also: #193
Python
apache-2.0
pyapi-gitlab/pyapi-gitlab,Itxaka/pyapi-gitlab,Itxaka/pyapi-gitlab,pyapi-gitlab/pyapi-gitlab
import responses + from requests.exceptions import HTTPError - from gitlab.exceptions import HttpError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') + self.gitlab.suppress_http_error = False - self.assertRaises(HttpError, self.gitlab.delete_repository_tag, 5, 'test') + self.assertRaises(HTTPError, self.gitlab.delete_repository_tag, 5, 'test') + self.gitlab.suppress_http_error = True
Update Tags cases for new behaviour
## Code Before: import responses from gitlab.exceptions import HttpError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.assertRaises(HttpError, self.gitlab.delete_repository_tag, 5, 'test') ## Instruction: Update Tags cases for new behaviour ## Code After: import responses from requests.exceptions import HTTPError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.gitlab.suppress_http_error = False self.assertRaises(HTTPError, self.gitlab.delete_repository_tag, 5, 'test') self.gitlab.suppress_http_error = True
import responses + from requests.exceptions import HTTPError - from gitlab.exceptions import HttpError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') + self.gitlab.suppress_http_error = False - self.assertRaises(HttpError, self.gitlab.delete_repository_tag, 5, 'test') ? ^^^ + self.assertRaises(HTTPError, self.gitlab.delete_repository_tag, 5, 'test') ? ^^^ + self.gitlab.suppress_http_error = True
3bc0876e7bae2cfb62724f1e5dce1a93f71b7252
docstring_parser/parser/__init__.py
docstring_parser/parser/__init__.py
"""Docstring parsing.""" from . import rest from .common import ParseError _styles = {"rest": rest.parse} def parse(text: str, style: str = "auto"): """ Parse the docstring into its components. :param str text: docstring text to parse :param text style: docstring style, choose from: 'rest', 'auto' :returns: parsed docstring """ if style == "auto": rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=lambda ret: len(ret.meta), reverse=True)[0] else: return _styles[style]
"""Docstring parsing.""" from . import rest from .common import ParseError, Docstring _styles = {"rest": rest.parse} def _parse_score(docstring: Docstring) -> int: """ Produce a score for the parsing. :param Docstring docstring: parsed docstring representation :returns int: parse score, higher is better """ score = 0 if docstring.short_description: score += 1 if docstring.long_description: score += docstring.long_description.count('\n') score += len(docstring.params) score += len(docstring.raises) if docstring.returns: score += 2 return score def parse(text: str, style: str = 'auto') -> Docstring: """ Parse the docstring into its components. :param str text: docstring text to parse :param str style: docstring style, choose from: 'rest', 'auto' :returns Docstring: parsed docstring representation """ if style == 'auto': rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=_parse_score, reverse=True)[0] else: return _styles[style](text)
Fix parsing when style specified, add 'auto' score
Fix parsing when style specified, add 'auto' score
Python
mit
rr-/docstring_parser
"""Docstring parsing.""" from . import rest - from .common import ParseError + from .common import ParseError, Docstring _styles = {"rest": rest.parse} + def _parse_score(docstring: Docstring) -> int: + """ + Produce a score for the parsing. + + :param Docstring docstring: parsed docstring representation + :returns int: parse score, higher is better + """ + + score = 0 + if docstring.short_description: + score += 1 + if docstring.long_description: + score += docstring.long_description.count('\n') + score += len(docstring.params) + score += len(docstring.raises) + if docstring.returns: + score += 2 + return score + + - def parse(text: str, style: str = "auto"): + def parse(text: str, style: str = 'auto') -> Docstring: """ Parse the docstring into its components. :param str text: docstring text to parse - :param text style: docstring style, choose from: 'rest', 'auto' + :param str style: docstring style, choose from: 'rest', 'auto' - :returns: parsed docstring + :returns Docstring: parsed docstring representation """ - if style == "auto": + if style == 'auto': rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc - return sorted(rets, key=lambda ret: len(ret.meta), reverse=True)[0] + return sorted(rets, key=_parse_score, reverse=True)[0] else: - return _styles[style] + return _styles[style](text)
Fix parsing when style specified, add 'auto' score
## Code Before: """Docstring parsing.""" from . import rest from .common import ParseError _styles = {"rest": rest.parse} def parse(text: str, style: str = "auto"): """ Parse the docstring into its components. :param str text: docstring text to parse :param text style: docstring style, choose from: 'rest', 'auto' :returns: parsed docstring """ if style == "auto": rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=lambda ret: len(ret.meta), reverse=True)[0] else: return _styles[style] ## Instruction: Fix parsing when style specified, add 'auto' score ## Code After: """Docstring parsing.""" from . import rest from .common import ParseError, Docstring _styles = {"rest": rest.parse} def _parse_score(docstring: Docstring) -> int: """ Produce a score for the parsing. :param Docstring docstring: parsed docstring representation :returns int: parse score, higher is better """ score = 0 if docstring.short_description: score += 1 if docstring.long_description: score += docstring.long_description.count('\n') score += len(docstring.params) score += len(docstring.raises) if docstring.returns: score += 2 return score def parse(text: str, style: str = 'auto') -> Docstring: """ Parse the docstring into its components. :param str text: docstring text to parse :param str style: docstring style, choose from: 'rest', 'auto' :returns Docstring: parsed docstring representation """ if style == 'auto': rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc return sorted(rets, key=_parse_score, reverse=True)[0] else: return _styles[style](text)
"""Docstring parsing.""" from . import rest - from .common import ParseError + from .common import ParseError, Docstring ? +++++++++++ _styles = {"rest": rest.parse} + def _parse_score(docstring: Docstring) -> int: + """ + Produce a score for the parsing. + + :param Docstring docstring: parsed docstring representation + :returns int: parse score, higher is better + """ + + score = 0 + if docstring.short_description: + score += 1 + if docstring.long_description: + score += docstring.long_description.count('\n') + score += len(docstring.params) + score += len(docstring.raises) + if docstring.returns: + score += 2 + return score + + - def parse(text: str, style: str = "auto"): ? ^ ^ + def parse(text: str, style: str = 'auto') -> Docstring: ? ^ ^ +++++++++++++ """ Parse the docstring into its components. :param str text: docstring text to parse - :param text style: docstring style, choose from: 'rest', 'auto' ? ^^^ + :param str style: docstring style, choose from: 'rest', 'auto' ? + ^ - :returns: parsed docstring + :returns Docstring: parsed docstring representation """ - if style == "auto": ? ^ ^ + if style == 'auto': ? ^ ^ rets = [] for _parse in _styles.values(): try: rets.append(_parse(text)) except ParseError as e: exc = e if not rets: raise exc - return sorted(rets, key=lambda ret: len(ret.meta), reverse=True)[0] ? ^ ^^^^^ ---------------- + return sorted(rets, key=_parse_score, reverse=True)[0] ? ^^ ^^^^^^^ else: - return _styles[style] + return _styles[style](text) ? ++++++
c89e30d1a33df2d9d8c5ceb03df98d29b3b08724
spacy/tests/en/test_exceptions.py
spacy/tests/en/test_exceptions.py
"""Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e."
"""Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e." @pytest.mark.parametrize('text', ["1am", "12a.m.", "11p.m.", "4pm"]) def test_tokenizer_handles_times(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 2 assert tokens[1].lemma_ in ["a.m.", "p.m."]
Add test for English time exceptions ("1a.m." etc.)
Add test for English time exceptions ("1a.m." etc.)
Python
mit
honnibal/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,recognai/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,explosion/spaCy,raphael0202/spaCy,spacy-io/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,raphael0202/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,Gregory-Howard/spaCy,explosion/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,aikramer2/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,Gregory-Howard/spaCy
"""Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e." + + @pytest.mark.parametrize('text', ["1am", "12a.m.", "11p.m.", "4pm"]) + def test_tokenizer_handles_times(en_tokenizer, text): + tokens = en_tokenizer(text) + assert len(tokens) == 2 + assert tokens[1].lemma_ in ["a.m.", "p.m."] +
Add test for English time exceptions ("1a.m." etc.)
## Code Before: """Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e." ## Instruction: Add test for English time exceptions ("1a.m." etc.) ## Code After: """Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e." @pytest.mark.parametrize('text', ["1am", "12a.m.", "11p.m.", "4pm"]) def test_tokenizer_handles_times(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 2 assert tokens[1].lemma_ in ["a.m.", "p.m."]
"""Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) == 1 def test_tokenizer_handles_exc_in_text(en_tokenizer): text = "It's mediocre i.e. bad." tokens = en_tokenizer(text) assert len(tokens) == 6 assert tokens[3].text == "i.e." + + + @pytest.mark.parametrize('text', ["1am", "12a.m.", "11p.m.", "4pm"]) + def test_tokenizer_handles_times(en_tokenizer, text): + tokens = en_tokenizer(text) + assert len(tokens) == 2 + assert tokens[1].lemma_ in ["a.m.", "p.m."]
075b11aa830c9a5961e9ee63e42484192990f7d3
tools/misc/python/test-data-in-out.py
tools/misc/python/test-data-in-out.py
import shutil shutil.copyfile('input', 'output')
import shutil import time time.sleep(delay) shutil.copyfile('input', 'output')
Add delay to input-output test
Add delay to input-output test
Python
mit
chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools
import shutil + import time + time.sleep(delay) shutil.copyfile('input', 'output')
Add delay to input-output test
## Code Before: import shutil shutil.copyfile('input', 'output') ## Instruction: Add delay to input-output test ## Code After: import shutil import time time.sleep(delay) shutil.copyfile('input', 'output')
import shutil + import time + time.sleep(delay) shutil.copyfile('input', 'output')
8280b9d2f9a88e3b52e76405a6a978e85da2b680
oscar/apps/customer/auth_backends.py
oscar/apps/customer/auth_backends.py
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
Correct bug in auth where username=None
Correct bug in auth where username=None
Python
bsd-3-clause
kapt/django-oscar,bschuon/django-oscar,lijoantony/django-oscar,bnprk/django-oscar,pdonadeo/django-oscar,jinnykoo/wuyisj.com,jinnykoo/christmas,monikasulik/django-oscar,machtfit/django-oscar,sonofatailor/django-oscar,marcoantoniooliveira/labweb,spartonia/django-oscar,spartonia/django-oscar,Jannes123/django-oscar,bschuon/django-oscar,taedori81/django-oscar,manevant/django-oscar,elliotthill/django-oscar,dongguangming/django-oscar,saadatqadri/django-oscar,pasqualguerrero/django-oscar,mexeniz/django-oscar,thechampanurag/django-oscar,jinnykoo/wuyisj,saadatqadri/django-oscar,eddiep1101/django-oscar,Jannes123/django-oscar,QLGu/django-oscar,bschuon/django-oscar,sasha0/django-oscar,itbabu/django-oscar,Idematica/django-oscar,taedori81/django-oscar,itbabu/django-oscar,ahmetdaglarbas/e-commerce,Bogh/django-oscar,WillisXChen/django-oscar,mexeniz/django-oscar,amirrpp/django-oscar,ahmetdaglarbas/e-commerce,jinnykoo/wuyisj,ahmetdaglarbas/e-commerce,spartonia/django-oscar,Idematica/django-oscar,WillisXChen/django-oscar,django-oscar/django-oscar,monikasulik/django-oscar,makielab/django-oscar,nickpack/django-oscar,vovanbo/django-oscar,nickpack/django-oscar,django-oscar/django-oscar,binarydud/django-oscar,okfish/django-oscar,solarissmoke/django-oscar,binarydud/django-oscar,dongguangming/django-oscar,bnprk/django-oscar,john-parton/django-oscar,rocopartners/django-oscar,DrOctogon/unwash_ecom,jinnykoo/christmas,thechampanurag/django-oscar,jinnykoo/christmas,Idematica/django-oscar,jinnykoo/wuyisj.com,bschuon/django-oscar,Jannes123/django-oscar,MatthewWilkes/django-oscar,django-oscar/django-oscar,okfish/django-oscar,sasha0/django-oscar,josesanch/django-oscar,nfletton/django-oscar,machtfit/django-oscar,faratro/django-oscar,Jannes123/django-oscar,makielab/django-oscar,manevant/django-oscar,jmt4/django-oscar,spartonia/django-oscar,kapari/django-oscar,QLGu/django-oscar,okfish/django-oscar,kapt/django-oscar,anentropic/django-oscar,WadeYuChen/django-oscar,jlmadurga/django-oscar,eddiep1101/django-oscar,kapt/django-oscar,jinnykoo/wuyisj.com,sasha0/django-oscar,pdonadeo/django-oscar,josesanch/django-oscar,QLGu/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,Bogh/django-oscar,faratro/django-oscar,anentropic/django-oscar,josesanch/django-oscar,sasha0/django-oscar,Bogh/django-oscar,taedori81/django-oscar,machtfit/django-oscar,pdonadeo/django-oscar,vovanbo/django-oscar,lijoantony/django-oscar,rocopartners/django-oscar,binarydud/django-oscar,Bogh/django-oscar,adamend/django-oscar,solarissmoke/django-oscar,lijoantony/django-oscar,makielab/django-oscar,makielab/django-oscar,thechampanurag/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,kapari/django-oscar,itbabu/django-oscar,lijoantony/django-oscar,adamend/django-oscar,pasqualguerrero/django-oscar,elliotthill/django-oscar,itbabu/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,kapari/django-oscar,marcoantoniooliveira/labweb,sonofatailor/django-oscar,MatthewWilkes/django-oscar,amirrpp/django-oscar,faratro/django-oscar,jmt4/django-oscar,pasqualguerrero/django-oscar,DrOctogon/unwash_ecom,thechampanurag/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,michaelkuty/django-oscar,jinnykoo/wuyisj,bnprk/django-oscar,pdonadeo/django-oscar,michaelkuty/django-oscar,nfletton/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj,WadeYuChen/django-oscar,adamend/django-oscar,ka7eh/django-oscar,ka7eh/django-oscar,monikasulik/django-oscar,saadatqadri/django-oscar,WadeYuChen/django-oscar,adamend/django-oscar,michaelkuty/django-oscar,jmt4/django-oscar,manevant/django-oscar,rocopartners/django-oscar,MatthewWilkes/django-oscar,john-parton/django-oscar,nickpack/django-oscar,dongguangming/django-oscar,marcoantoniooliveira/labweb,vovanbo/django-oscar,ka7eh/django-oscar,ademuk/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,anentropic/django-oscar,mexeniz/django-oscar,ademuk/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,bnprk/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,WillisXChen/django-oscar,john-parton/django-oscar,rocopartners/django-oscar,faratro/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,solarissmoke/django-oscar,dongguangming/django-oscar,ka7eh/django-oscar,jlmadurga/django-oscar,amirrpp/django-oscar,jlmadurga/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sonofatailor/django-oscar,saadatqadri/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,michaelkuty/django-oscar,jmt4/django-oscar,WillisXChen/django-oscar,kapari/django-oscar,john-parton/django-oscar,taedori81/django-oscar,nfletton/django-oscar,eddiep1101/django-oscar,manevant/django-oscar,nickpack/django-oscar,marcoantoniooliveira/labweb,WillisXChen/django-oscar,ahmetdaglarbas/e-commerce,pasqualguerrero/django-oscar,binarydud/django-oscar
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): - if not email: - if not 'username' in kwargs: + if email is None: + if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
Correct bug in auth where username=None
## Code Before: from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user ## Instruction: Correct bug in auth where username=None ## Code After: from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): - if not email: - if not 'username' in kwargs: + if email is None: + if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
a3cce9e4840cc687f6dcdd0b88577d2f13f3258e
onlineweb4/settings/raven.py
onlineweb4/settings/raven.py
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), }
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), 'tags': { 'app': config('OW4_RAVEN_APP_NAME', default='') }, }
Make it possible to specify which app to represent in sentry
Make it possible to specify which app to represent in sentry
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), + 'tags': { 'app': config('OW4_RAVEN_APP_NAME', default='') }, }
Make it possible to specify which app to represent in sentry
## Code Before: import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), } ## Instruction: Make it possible to specify which app to represent in sentry ## Code After: import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), 'tags': { 'app': config('OW4_RAVEN_APP_NAME', default='') }, }
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:[email protected]/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), + 'tags': { 'app': config('OW4_RAVEN_APP_NAME', default='') }, }
5abea2d21c62228eb9a7270a1e10f9f7ec4316af
source/services/rotten_tomatoes_service.py
source/services/rotten_tomatoes_service.py
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
Remove comma for RT search
Remove comma for RT search
Python
mit
jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') + formatted_title = formatted_title.replace(',', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
Remove comma for RT search
## Code Before: import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items) ## Instruction: Remove comma for RT search ## Code After: import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') + formatted_title = formatted_title.replace(',', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
5227ef25d9944c5e33b4a4f7e58259e3646ae52a
interactive.py
interactive.py
import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"
import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
Update interacitve.py - Add a method to run predefined commands.
Update interacitve.py - Add a method to run predefined commands.
Python
mit
VictorLoren/pyRecipeBook
import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) + #Method to run commands + def runCommand(command): + if command.strip() == 'exit': + return False + else: + return True # pre = '# ' on = True #Keep asking for inpyt while(on): + #Enter a command - command = input(pre) + command = raw_input(pre) #Run command + on = runCommand(command) - #Exiting commands + #Exiting commands - "Thank you for choosing to use pyRecipeBook" + exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" + print(exitMessage)
Update interacitve.py - Add a method to run predefined commands.
## Code Before: import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook" ## Instruction: Update interacitve.py - Add a method to run predefined commands. ## Code After: import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) + #Method to run commands + def runCommand(command): + if command.strip() == 'exit': + return False + else: + return True # pre = '# ' on = True #Keep asking for inpyt while(on): + #Enter a command - command = input(pre) + command = raw_input(pre) ? ++++ #Run command + on = runCommand(command) - #Exiting commands ? - + #Exiting commands - "Thank you for choosing to use pyRecipeBook" + exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" ? ++++++++++++++ ++ +++ + + print(exitMessage)
56ca0dce01ad76934ae850ea20ab25adbcc751d1
conf_site/proposals/admin.py
conf_site/proposals/admin.py
from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', 'speaker_email', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created"
from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created"
Remove speaker email field from proposal listing.
Remove speaker email field from proposal listing. Save space in admin proposal listing by removing the speaker email field.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', - 'speaker_email', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created"
Remove speaker email field from proposal listing.
## Code Before: from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', 'speaker_email', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created" ## Instruction: Remove speaker email field from proposal listing. ## Code After: from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created"
from django.contrib import admin from .models import Proposal, ProposalKeyword @admin.register(ProposalKeyword) class KeywordAdmin(admin.ModelAdmin): list_display = ("name", "slug", "official",) list_filter = ("official",) @admin.register(Proposal) class ProposalAdmin(admin.ModelAdmin): exclude = ( "under_represented_population", "under_represented_details", "under_represented_other", ) list_display = ( 'number', 'title', - 'speaker_email', 'speaker', 'kind', 'audience_level', 'cancelled', "date_created", "date_last_modified", ) list_display_links = ("title",) list_filter = ( 'kind', 'audience_level', 'cancelled', 'recording_release', ) search_fields = ("title", "speaker__name") date_hierarchy = "date_created"
b68576d307474eaf6bd8a8853bee767c391d28b9
conjure/connection.py
conjure/connection.py
from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] if username and password: db.authenticate(username, password) return db
from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] return db
Remove authenticate call to fix issues with pymongo 3.7
Remove authenticate call to fix issues with pymongo 3.7
Python
mit
GGOutfitters/conjure
from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] - if username and password: - db.authenticate(username, password) - return db
Remove authenticate call to fix issues with pymongo 3.7
## Code Before: from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] if username and password: db.authenticate(username, password) return db ## Instruction: Remove authenticate call to fix issues with pymongo 3.7 ## Code After: from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] return db
from .exceptions import ConnectionError from pymongo import MongoClient from pymongo.uri_parser import parse_uri _connections = {} try: import gevent except ImportError: gevent = None def _get_connection(uri): global _connections parsed_uri = parse_uri(uri) hosts = parsed_uri['nodelist'] hosts = ['%s:%d' % host for host in hosts] key = ','.join(hosts) connection = _connections.get(key) if connection is None: try: connection = _connections[key] = MongoClient(uri) except Exception as e: raise ConnectionError(e.message) return connection def connect(uri): parsed_uri = parse_uri(uri) username = parsed_uri['username'] password = parsed_uri['password'] database = parsed_uri['database'] db = _get_connection(uri)[database] - if username and password: - db.authenticate(username, password) - return db
50519406ac64766874ce9edf5cea69233461ffb2
tests/test_config.py
tests/test_config.py
import pytest import uuid from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') @pytest.fixture def dummyvalue(): return str(uuid.uuid4()) def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' def test_write_config(config, dummyparam, dummyvalue): config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue
import pytest import uuid import tempfile import os from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') @pytest.yield_fixture def dummy_config_file(): filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4())) yield filename if os.path.isfile(filename): os.remove(filename) @pytest.fixture def custom_config_file(dummy_config_file, scope='module'): return S3Keyring(profile_name='test', config_file=dummy_config_file).config def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' def test_write_config(config, dummyparam): dummyvalue = str(uuid.uuid4()) config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue def test_read_custom_config_file(custom_config_file, dummy_config_file): """Reads a parameter from a custom config file""" profile_name = custom_config_file.get('default', 'profile') assert profile_name == 'default' assert custom_config_file.config_file == dummy_config_file assert os.path.isfile(dummy_config_file) def test_write_config_in_custom_config_file(custom_config_file, dummyparam, config): dummyvalue = str(uuid.uuid4()) custom_config_file.set('default', dummyparam, dummyvalue) custom_config_file.save() custom_config_file.load() assert custom_config_file.get('default', dummyparam) == dummyvalue assert config.config_file != custom_config_file.config_file config.load() assert config.get('default', dummyparam) != dummyvalue
Test custom configuration file feature
Test custom configuration file feature
Python
mit
InnovativeTravel/s3-keyring
import pytest import uuid + import tempfile + import os from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') + @pytest.yield_fixture + def dummy_config_file(): + filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4())) + yield filename + if os.path.isfile(filename): + os.remove(filename) + + @pytest.fixture - def dummyvalue(): - return str(uuid.uuid4()) + def custom_config_file(dummy_config_file, scope='module'): + return S3Keyring(profile_name='test', config_file=dummy_config_file).config def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' - def test_write_config(config, dummyparam, dummyvalue): + def test_write_config(config, dummyparam): + dummyvalue = str(uuid.uuid4()) config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue + + def test_read_custom_config_file(custom_config_file, dummy_config_file): + """Reads a parameter from a custom config file""" + profile_name = custom_config_file.get('default', 'profile') + assert profile_name == 'default' + assert custom_config_file.config_file == dummy_config_file + assert os.path.isfile(dummy_config_file) + + + def test_write_config_in_custom_config_file(custom_config_file, dummyparam, + config): + dummyvalue = str(uuid.uuid4()) + custom_config_file.set('default', dummyparam, dummyvalue) + custom_config_file.save() + custom_config_file.load() + assert custom_config_file.get('default', dummyparam) == dummyvalue + assert config.config_file != custom_config_file.config_file + config.load() + assert config.get('default', dummyparam) != dummyvalue +
Test custom configuration file feature
## Code Before: import pytest import uuid from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') @pytest.fixture def dummyvalue(): return str(uuid.uuid4()) def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' def test_write_config(config, dummyparam, dummyvalue): config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue ## Instruction: Test custom configuration file feature ## Code After: import pytest import uuid import tempfile import os from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') @pytest.yield_fixture def dummy_config_file(): filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4())) yield filename if os.path.isfile(filename): os.remove(filename) @pytest.fixture def custom_config_file(dummy_config_file, scope='module'): return S3Keyring(profile_name='test', config_file=dummy_config_file).config def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' def test_write_config(config, dummyparam): dummyvalue = str(uuid.uuid4()) config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue def test_read_custom_config_file(custom_config_file, dummy_config_file): """Reads a parameter from a custom config file""" profile_name = custom_config_file.get('default', 'profile') assert profile_name == 'default' assert custom_config_file.config_file == dummy_config_file assert os.path.isfile(dummy_config_file) def test_write_config_in_custom_config_file(custom_config_file, dummyparam, config): dummyvalue = str(uuid.uuid4()) custom_config_file.set('default', dummyparam, dummyvalue) custom_config_file.save() custom_config_file.load() assert custom_config_file.get('default', dummyparam) == dummyvalue assert config.config_file != custom_config_file.config_file config.load() assert config.get('default', dummyparam) != dummyvalue
import pytest import uuid + import tempfile + import os from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummyparam') + @pytest.yield_fixture + def dummy_config_file(): + filename = os.path.join(tempfile.gettempdir(), str(uuid.uuid4())) + yield filename + if os.path.isfile(filename): + os.remove(filename) + + @pytest.fixture - def dummyvalue(): - return str(uuid.uuid4()) + def custom_config_file(dummy_config_file, scope='module'): + return S3Keyring(profile_name='test', config_file=dummy_config_file).config def test_read_config(config): """Sets value for an existing configuration option""" profile_name = config.get('default', 'profile') assert profile_name == 'default' - def test_write_config(config, dummyparam, dummyvalue): ? ------------ + def test_write_config(config, dummyparam): + dummyvalue = str(uuid.uuid4()) config.set('default', dummyparam, dummyvalue) config.save() config.load() assert config.get('default', dummyparam) == dummyvalue + + + def test_read_custom_config_file(custom_config_file, dummy_config_file): + """Reads a parameter from a custom config file""" + profile_name = custom_config_file.get('default', 'profile') + assert profile_name == 'default' + assert custom_config_file.config_file == dummy_config_file + assert os.path.isfile(dummy_config_file) + + + def test_write_config_in_custom_config_file(custom_config_file, dummyparam, + config): + dummyvalue = str(uuid.uuid4()) + custom_config_file.set('default', dummyparam, dummyvalue) + custom_config_file.save() + custom_config_file.load() + assert custom_config_file.get('default', dummyparam) == dummyvalue + assert config.config_file != custom_config_file.config_file + config.load() + assert config.get('default', dummyparam) != dummyvalue
5d448435477ce94273051b8351275d8c18838b8b
icekit/utils/fluent_contents.py
icekit/utils/fluent_contents.py
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
Change argument name to stop probable name clash.
Change argument name to stop probable name clash.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# - def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs): + def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. - :param page: The fluent_page instance to create the content + :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. - placeholders = page.get_placeholder_by_slot(placeholder_name) + placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: - placeholder = page.create_placeholder(placeholder_name) + placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. - ct = ContentType.objects.get_for_model(type(page)) + ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, - parent_id=page.id, + parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
Change argument name to stop probable name clash.
## Code Before: from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions ############################################################# ## Instruction: Change argument name to stop probable name clash. ## Code After: from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# - def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs): + def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): ? +++++ """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. - :param page: The fluent_page instance to create the content + :param test_page: The fluent_page instance to create the content ? +++++ instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. - placeholders = page.get_placeholder_by_slot(placeholder_name) + placeholders = test_page.get_placeholder_by_slot(placeholder_name) ? +++++ # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: - placeholder = page.create_placeholder(placeholder_name) + placeholder = test_page.create_placeholder(placeholder_name) ? +++++ # Obtain the content type for the page instance class. - ct = ContentType.objects.get_for_model(type(page)) + ct = ContentType.objects.get_for_model(type(test_page)) ? +++++ # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, - parent_id=page.id, + parent_id=test_page.id, ? +++++ placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
0cc89fe31729a485a0e055b343acfde3d71745d7
apps/metricsmanager/api.py
apps/metricsmanager/api.py
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response("No formula provided") try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
Fix error format of check formula endpoint
Fix error format of check formula endpoint
Python
agpl-3.0
mmilaprat/policycompass-services,almey/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services,almey/policycompass-services,policycompass/policycompass-services,almey/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: - return Response("No formula provided") + return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
Fix error format of check formula endpoint
## Code Before: from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response("No formula provided") try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer ## Instruction: Fix error format of check formula endpoint ## Code After: from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: - return Response("No formula provided") + return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
1fce663e37823d985d00d1700aba5e067157b789
profiles/tests.py
profiles/tests.py
from django.contrib.auth.models import User from django.test import TestCase import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
from django.contrib.auth.models import User import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
Add password handling to default factory.
Add password handling to default factory.
Python
bsd-2-clause
incuna/django-extensible-profiles
from django.contrib.auth.models import User - from django.test import TestCase + import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) + + @classmethod + def _prepare(cls, create, **kwargs): + password = kwargs.pop('password', 'password') + user = super(UserFactory, cls)._prepare(create=False, **kwargs) + user.set_password(password) + user.raw_password = password + if create: + user.save() + return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
Add password handling to default factory.
## Code Before: from django.contrib.auth.models import User from django.test import TestCase import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password) ## Instruction: Add password handling to default factory. ## Code After: from django.contrib.auth.models import User import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
from django.contrib.auth.models import User - from django.test import TestCase + import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) + + @classmethod + def _prepare(cls, create, **kwargs): + password = kwargs.pop('password', 'password') + user = super(UserFactory, cls)._prepare(create=False, **kwargs) + user.set_password(password) + user.raw_password = password + if create: + user.save() + return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
150aa84158bab89e3700114038fab78504bed960
zou/app/blueprints/export/csv/persons.py
zou/app/blueprints/export/csv/persons.py
from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): return ["Last Name", "First Name", "Email", "Phone", "Role"] def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): return [ person.last_name, person.first_name, person.email, person.phone, person.role, ]
from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): return ["Last Name", "First Name", "Email", "Phone", "Role", "Active"] def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): active = "yes" if not person.active: active = "no" return [ person.last_name, person.first_name, person.email, person.phone, person.role, active ]
Add active column to person csv export
Add active column to person csv export
Python
agpl-3.0
cgwire/zou
from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): - return ["Last Name", "First Name", "Email", "Phone", "Role"] + return ["Last Name", "First Name", "Email", "Phone", "Role", "Active"] def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): + active = "yes" + if not person.active: + active = "no" return [ person.last_name, person.first_name, person.email, person.phone, person.role, + active ]
Add active column to person csv export
## Code Before: from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): return ["Last Name", "First Name", "Email", "Phone", "Role"] def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): return [ person.last_name, person.first_name, person.email, person.phone, person.role, ] ## Instruction: Add active column to person csv export ## Code After: from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): return ["Last Name", "First Name", "Email", "Phone", "Role", "Active"] def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): active = "yes" if not person.active: active = "no" return [ person.last_name, person.first_name, person.email, person.phone, person.role, active ]
from zou.app.blueprints.export.csv.base import BaseCsvExport from zou.app.models.person import Person class PersonsCsvExport(BaseCsvExport): def __init__(self): BaseCsvExport.__init__(self, Person) self.file_name = "people_export" def build_headers(self): - return ["Last Name", "First Name", "Email", "Phone", "Role"] + return ["Last Name", "First Name", "Email", "Phone", "Role", "Active"] ? ++++++++++ def build_query(self): return self.model.query.order_by(Person.last_name, Person.first_name) def build_row(self, person): + active = "yes" + if not person.active: + active = "no" return [ person.last_name, person.first_name, person.email, person.phone, person.role, + active ]
4696efdee643bb3d86995fea4c35f7947535111d
foundation/offices/tests/factories.py
foundation/offices/tests/factories.py
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) class Meta: model = models.Email
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') class Meta: model = models.Email
Fix EmailFactory by missing created_by
Fix EmailFactory by missing created_by
Python
bsd-3-clause
ad-m/foundation-manager,ad-m/foundation-manager,pilnujemy/pytamy,pilnujemy/pytamy,ad-m/foundation-manager,ad-m/foundation-manager,pilnujemy/pytamy,pilnujemy/pytamy
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) + created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') class Meta: model = models.Email
Fix EmailFactory by missing created_by
## Code Before: from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) class Meta: model = models.Email ## Instruction: Fix EmailFactory by missing created_by ## Code After: from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') class Meta: model = models.Email
from __future__ import absolute_import from .. import models import factory class OfficeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'office-/{0}/'.format(n)) jst = factory.SubFactory('foundation.teryt.tests.factories.JSTFactory') created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') verified = True state = 'created' class Meta: model = models.Office class EmailFactory(factory.django.DjangoModelFactory): email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) office = factory.SubFactory(OfficeFactory) + created_by = factory.SubFactory('foundation.users.tests.factories.UserFactory') class Meta: model = models.Email
521b4fbec142306fad2347a5dd3a56aeec2f9498
events/search_indexes.py
events/search_indexes.py
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place def index_queryset(self, using=None): return self.get_model().objects.filter(deleted=False)
Remove deleted places from place index
Remove deleted places from place index
Python
mit
aapris/linkedevents,aapris/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,aapris/linkedevents
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place + def index_queryset(self, using=None): + return self.get_model().objects.filter(deleted=False) +
Remove deleted places from place index
## Code Before: from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place ## Instruction: Remove deleted places from place index ## Code After: from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place def index_queryset(self, using=None): return self.get_model().objects.filter(deleted=False)
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place + + def index_queryset(self, using=None): + return self.get_model().objects.filter(deleted=False)
1d555c184a10ae4fd84d758105e19b10828543c2
q2_feature_classifier/tests/__init__.py
q2_feature_classifier/tests/__init__.py
import tempfile import shutil from q2_types.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
import tempfile import shutil from qiime.plugin.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
Update import location of TestPluginBase
TST: Update import location of TestPluginBase
Python
bsd-3-clause
BenKaehler/q2-feature-classifier
import tempfile import shutil - from q2_types.testing import TestPluginBase + from qiime.plugin.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
Update import location of TestPluginBase
## Code Before: import tempfile import shutil from q2_types.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r') ## Instruction: Update import location of TestPluginBase ## Code After: import tempfile import shutil from qiime.plugin.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
import tempfile import shutil - from q2_types.testing import TestPluginBase ? ^^^^ ^^ + from qiime.plugin.testing import TestPluginBase ? ^^^^^ ^^^^^ class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
7dc34b159f837d4fdc71666233f66d340cfd3419
src/info_retrieval/info_retrieval.py
src/info_retrieval/info_retrieval.py
from pymur import * from general_classes import * class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages
from pymur import * from general_classes import * import sys class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) sys.stderr.write(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages
Add debugging statement to retrieve_passages function
Add debugging statement to retrieve_passages function
Python
mit
amkahn/question-answering,amkahn/question-answering
from pymur import * from general_classes import * + import sys class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) + sys.stderr.write(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages
Add debugging statement to retrieve_passages function
## Code Before: from pymur import * from general_classes import * class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages ## Instruction: Add debugging statement to retrieve_passages function ## Code After: from pymur import * from general_classes import * import sys class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) sys.stderr.write(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages
from pymur import * from general_classes import * + import sys class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def __init__(self, index_path): # how to get this to link up to the doc collection? self.path_to_idx = index_path self.index = Index(self.path_to_idx) self.query_env = QueryEnvironment() self.query_env.addIndex(self.path_to_idx) # creates a list of all the passages returned by all the queries generated by # the query-processing module def retrieve_passages(self, queries): passages = [] for query in queries: query = " ".join(query) + sys.stderr.write(query) # second argument is the number of documents desired docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20) for doc in docs: doc_num = doc.document begin = doc.begin end = doc.end doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output passage = Passage(self.index.document(doc_num, True)[begin:end], doc.score, doc_id) passages.append(passage) return passages
afd6b5b29b60c59689e0a1be38a0483a7e4db312
miniraf/__init__.py
miniraf/__init__.py
import argparse import astropy.io.fits as fits import numpy as np import calc import combine if __name__=="__main__": argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) args = argparser.parse_args() print(args) args.func(args)
import argparse import calc import combine from combine import stack_fits_data from calc import load_fits_data def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) return argparser.parse_args() def main(): args = _argparse() args.func(args) if __name__=="__main__": main()
Create main() entry point for final script
Create main() entry point for final script Signed-off-by: Lizhou Sha <[email protected]>
Python
mit
vulpicastor/miniraf
import argparse - import astropy.io.fits as fits - import numpy as np import calc import combine - if __name__=="__main__": + from combine import stack_fits_data + from calc import load_fits_data + + def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) - args = argparser.parse_args() + return argparser.parse_args() - print(args) + + def main(): + args = _argparse() args.func(args) + if __name__=="__main__": + main()
Create main() entry point for final script
## Code Before: import argparse import astropy.io.fits as fits import numpy as np import calc import combine if __name__=="__main__": argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) args = argparser.parse_args() print(args) args.func(args) ## Instruction: Create main() entry point for final script ## Code After: import argparse import calc import combine from combine import stack_fits_data from calc import load_fits_data def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) return argparser.parse_args() def main(): args = _argparse() args.func(args) if __name__=="__main__": main()
import argparse - import astropy.io.fits as fits - import numpy as np import calc import combine - if __name__=="__main__": + from combine import stack_fits_data + from calc import load_fits_data + + def _argparse(): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(help="sub-command help") calc.create_parser(subparsers) combine.create_parser(subparsers) - args = argparser.parse_args() ? - ^^^^ + return argparser.parse_args() ? ^^^^^ - print(args) + + def main(): + args = _argparse() args.func(args) + if __name__=="__main__": + main()
61be745b641689addc9f009311d28a5775d5a18b
ctconfig.py
ctconfig.py
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) # Options for testing define( "output_routes", default=False, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) define( "output_routes", default=True, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
Set `output_routes` to True by default
Set `output_routes` to True by default
Python
agpl-3.0
hfaran/LivesPool,hfaran/LivesPool,hfaran/LivesPool,hfaran/LivesPool
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) - # Options for testing define( "output_routes", - default=False, + default=True, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
Set `output_routes` to True by default
## Code Before: import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) # Options for testing define( "output_routes", default=False, type=bool, help="If enabled, outputs all application routes to `routes.json`" ) ## Instruction: Set `output_routes` to True by default ## Code After: import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) define( "output_routes", default=True, type=bool, help="If enabled, outputs all application routes to `routes.json`" )
import logging import json from tornado.options import define, options _CONFIG_FILENAME = "cutthroat.conf" def define_options(): """Define defaults for most custom options""" # Log file and config file paths options.log_file_prefix = "/var/log/cutthroat/cutthroat.log" define( "conf_file_path", default="/etc/cutthroat/{}".format(_CONFIG_FILENAME), help="Path for the JSON configuration file with customized options", type="str" ) # Port define( "port", default=8888, help="run on the given port", type=int ) # Database options define( "sqlite_db", default="cutthroat.db" ) - # Options for testing define( "output_routes", - default=False, ? ^^^^ + default=True, ? ^^^ type=bool, help="If enabled, outputs all application routes to `routes.json`" )
6d5edb8a5eacfb2dc83a2eef5732562024995942
api/serializers.py
api/serializers.py
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): if 'is_school' in data and data['is_school']: error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
Fix bug with registering non-school teams
Fix bug with registering non-school teams
Python
bsd-3-clause
stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): + error_dict = {} if 'is_school' in data and data['is_school']: - error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
Fix bug with registering non-school teams
## Code Before: from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): if 'is_school' in data and data['is_school']: error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at') ## Instruction: Fix bug with registering non-school teams ## Code After: from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
from django.utils.translation import ugettext as _ from rest_framework.serializers import ModelSerializer, ValidationError from reg.models import Team class TeamSerializer(ModelSerializer): def validate(self, data): + error_dict = {} if 'is_school' in data and data['is_school']: - error_dict = {} if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if 'teacher_email' not in data or not data['teacher_email'].strip(): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('auth_string',) read_only_fields = ('id', 'created_at')
b9379e3c8667d062ec6511ad07f2525ea0b2f5ef
tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py
tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py
import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main()
import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' def _cleanup(self): TestHarness._cleanup(self) output = glob.glob(os.path.join(os.getcwd(), 'source.*')) for f in output: if os.path.exists(f): os.remove(f) if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main()
Make test cleanup source file
Make test cleanup source file
Python
mit
amandalund/openmc,mit-crpg/openmc,shikhar413/openmc,walshjon/openmc,bhermanmit/openmc,mjlong/openmc,paulromano/openmc,samuelshaner/openmc,smharper/openmc,liangjg/openmc,paulromano/openmc,mit-crpg/openmc,shikhar413/openmc,wbinventor/openmc,walshjon/openmc,wbinventor/openmc,wbinventor/openmc,wbinventor/openmc,kellyrowland/openmc,bhermanmit/openmc,liangjg/openmc,liangjg/openmc,shikhar413/openmc,shikhar413/openmc,mit-crpg/openmc,smharper/openmc,amandalund/openmc,johnnyliu27/openmc,smharper/openmc,paulromano/openmc,walshjon/openmc,smharper/openmc,walshjon/openmc,johnnyliu27/openmc,liangjg/openmc,amandalund/openmc,amandalund/openmc,paulromano/openmc,samuelshaner/openmc,kellyrowland/openmc,samuelshaner/openmc,mjlong/openmc,johnnyliu27/openmc,johnnyliu27/openmc,mit-crpg/openmc,samuelshaner/openmc
import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' + def _cleanup(self): + TestHarness._cleanup(self) + output = glob.glob(os.path.join(os.getcwd(), 'source.*')) + for f in output: + if os.path.exists(f): + os.remove(f) + if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main()
Make test cleanup source file
## Code Before: import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main() ## Instruction: Make test cleanup source file ## Code After: import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' def _cleanup(self): TestHarness._cleanup(self) output = glob.glob(os.path.join(os.getcwd(), 'source.*')) for f in output: if os.path.exists(f): os.remove(f) if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main()
import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path.join(os.getcwd(), 'source.*')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' assert source[0].endswith('h5'), \ 'Source file is not a HDF5 file.' + def _cleanup(self): + TestHarness._cleanup(self) + output = glob.glob(os.path.join(os.getcwd(), 'source.*')) + for f in output: + if os.path.exists(f): + os.remove(f) + if __name__ == '__main__': harness = SourcepointTestHarness('statepoint.10.*') harness.main()
1d2eef3bf6a1a5c9b5a1f34c224d3a9651e77d73
gocd/response.py
gocd/response.py
import json class Response(object): def __init__(self, status_code, body, headers=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers @property def is_ok(self): return self.status_code == 200 @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod def from_request(cls, response): return Response( response.code, response.read(), response.headers, ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, )
import json class Response(object): def __init__(self, status_code, body, headers=None, ok_status=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers self.ok_status = ok_status or 200 @property def is_ok(self): return self.status_code == self.ok_status @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod def from_request(cls, response, ok_status=None): return Response( response.code, response.read(), response.headers, ok_status=ok_status ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, )
Add configurable ok status code for Response
Add configurable ok status code for Response When scheduling a pipeline the successful code is 202, so tihis needs to be configurable.
Python
mit
henriquegemignani/py-gocd,gaqzi/py-gocd
import json class Response(object): - def __init__(self, status_code, body, headers=None): + def __init__(self, status_code, body, headers=None, ok_status=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers + self.ok_status = ok_status or 200 @property def is_ok(self): - return self.status_code == 200 + return self.status_code == self.ok_status @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod - def from_request(cls, response): + def from_request(cls, response, ok_status=None): return Response( response.code, response.read(), response.headers, + ok_status=ok_status ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, )
Add configurable ok status code for Response
## Code Before: import json class Response(object): def __init__(self, status_code, body, headers=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers @property def is_ok(self): return self.status_code == 200 @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod def from_request(cls, response): return Response( response.code, response.read(), response.headers, ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, ) ## Instruction: Add configurable ok status code for Response ## Code After: import json class Response(object): def __init__(self, status_code, body, headers=None, ok_status=None): self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers self.ok_status = ok_status or 200 @property def is_ok(self): return self.status_code == self.ok_status @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod def from_request(cls, response, ok_status=None): return Response( response.code, response.read(), response.headers, ok_status=ok_status ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, )
import json class Response(object): - def __init__(self, status_code, body, headers=None): + def __init__(self, status_code, body, headers=None, ok_status=None): ? ++++++++++++++++ self.status_code = status_code self._body = body self._body_parsed = None self.content_type = headers['content-type'].split(';')[0] self.headers = headers + self.ok_status = ok_status or 200 @property def is_ok(self): - return self.status_code == 200 ? ^^^ + return self.status_code == self.ok_status ? ^^^^^^^^^^^^^^ @property def payload(self): if self.content_type.startswith('application/json'): if not self._body_parsed: self._body_parsed = json.loads(self._body) return self._body_parsed else: return self._body @classmethod - def from_request(cls, response): + def from_request(cls, response, ok_status=None): ? ++++++++++++++++ return Response( response.code, response.read(), response.headers, + ok_status=ok_status ) @classmethod def from_http_error(cls, http_error): return Response( http_error.code, http_error.read(), http_error.headers, )
15c58fb05a9bfb06b87d8d00a1b26d50ee68c1f7
django/publicmapping/redistricting/management/commands/makelanguagefiles.py
django/publicmapping/redistricting/management/commands/makelanguagefiles.py
from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: management.call_command('makemessages', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False)
from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: # For django templates management.call_command('makemessages', locale=language[0], interactive=False) # For javascript files management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False)
Add creation of js message files to management command
Add creation of js message files to management command
Python
apache-2.0
JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder
from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: + # For django templates management.call_command('makemessages', locale=language[0], interactive=False) + + # For javascript files + management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False)
Add creation of js message files to management command
## Code Before: from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: management.call_command('makemessages', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False) ## Instruction: Add creation of js message files to management command ## Code After: from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: # For django templates management.call_command('makemessages', locale=language[0], interactive=False) # For javascript files management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False)
from django.core.management.base import BaseCommand from redistricting.utils import * class Command(BaseCommand): """ This command prints creates and compiles language message files """ args = None help = 'Create and compile language message files' def handle(self, *args, **options): """ Create and compile language message files """ # Make messages for each language defined in settings for language in settings.LANGUAGES: + # For django templates management.call_command('makemessages', locale=language[0], interactive=False) + + # For javascript files + management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False) # Compile all message files management.call_command('compilemessages', interactive=False)
a4c5e9a970a297d59000468dde8423fa9db00c0f
packs/fixtures/actions/scripts/streamwriter-script.py
packs/fixtures/actions/scripts/streamwriter-script.py
import argparse import sys import ast from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) if obj_arg: sys.stdout.write(' OBJ: %s' % obj_arg) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args)
import argparse import sys import ast import re from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) if obj_arg: # Remove any u'' so it works consistently under Python 2 and 3.x obj_arg_str = str(obj_arg) value = re.sub("u'(.*?)'", r"'\1'", obj_arg_str) sys.stdout.write(' OBJ: %s' % value) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args)
Fix streamwriter action so it doesn't include "u" type prefix in the object result.
Fix streamwriter action so it doesn't include "u" type prefix in the object result. This way it works consistently and correctly under Python 2 and Python 3.
Python
apache-2.0
StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests
import argparse import sys import ast + import re from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) + str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg + if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) + if obj_arg: + # Remove any u'' so it works consistently under Python 2 and 3.x + obj_arg_str = str(obj_arg) + value = re.sub("u'(.*?)'", r"'\1'", obj_arg_str) - sys.stdout.write(' OBJ: %s' % obj_arg) + sys.stdout.write(' OBJ: %s' % value) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args)
Fix streamwriter action so it doesn't include "u" type prefix in the object result.
## Code Before: import argparse import sys import ast from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) if obj_arg: sys.stdout.write(' OBJ: %s' % obj_arg) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args) ## Instruction: Fix streamwriter action so it doesn't include "u" type prefix in the object result. ## Code After: import argparse import sys import ast import re from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) if obj_arg: # Remove any u'' so it works consistently under Python 2 and 3.x obj_arg_str = str(obj_arg) value = re.sub("u'(.*?)'", r"'\1'", obj_arg_str) sys.stdout.write(' OBJ: %s' % value) if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args)
import argparse import sys import ast + import re from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': sys.stderr.write('STREAM IS STDERR.') return stream raise CustomException('Invalid stream specified.') def main(args): stream = args.stream writer = StreamWriter() stream = writer.run(stream) + str_arg = args.str_arg int_arg = args.int_arg obj_arg = args.obj_arg + if str_arg: sys.stdout.write(' STR: %s' % str_arg) if int_arg: sys.stdout.write(' INT: %d' % int_arg) + if obj_arg: + # Remove any u'' so it works consistently under Python 2 and 3.x + obj_arg_str = str(obj_arg) + value = re.sub("u'(.*?)'", r"'\1'", obj_arg_str) - sys.stdout.write(' OBJ: %s' % obj_arg) ? ^^^^ ^^ + sys.stdout.write(' OBJ: %s' % value) ? ^ ^^^ if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--stream', help='Stream.', required=True) parser.add_argument('--str_arg', help='Some string arg.') parser.add_argument('--int_arg', help='Some int arg.', type=float) parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval) args = parser.parse_args() main(args)
8ccffcf02cd5ba8352bc8182d7be13ea015332ca
plinth/utils.py
plinth/utils.py
import importlib def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library)
import importlib from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) def _format_lazy(string, *args, **kwargs): """Lazily format a lazy string.""" string = str(string) return string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
Add utility method to lazy format lazy string
Add utility method to lazy format lazy string This method is useful to format strings that are lazy (such as those in Forms).
Python
agpl-3.0
freedomboxtwh/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,harry-7/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth
import importlib + from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) + + def _format_lazy(string, *args, **kwargs): + """Lazily format a lazy string.""" + string = str(string) + return string.format(*args, **kwargs) + + + format_lazy = lazy(_format_lazy, str) +
Add utility method to lazy format lazy string
## Code Before: import importlib def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) ## Instruction: Add utility method to lazy format lazy string ## Code After: import importlib from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) def _format_lazy(string, *args, **kwargs): """Lazily format a lazy string.""" string = str(string) return string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
import importlib + from django.utils.functional import lazy def import_from_gi(library, version): """Import and return a GObject introspection library.""" try: import gi as package package_name = 'gi' except ImportError: import pgi as package package_name = 'pgi' package.require_version(library, version) return importlib.import_module(package_name + '.repository.' + library) + + + def _format_lazy(string, *args, **kwargs): + """Lazily format a lazy string.""" + string = str(string) + return string.format(*args, **kwargs) + + + format_lazy = lazy(_format_lazy, str)
3973e0d2591b2554e96da0a22b2d723a71d2423e
imgaug/augmenters/__init__.py
imgaug/augmenters/__init__.py
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import GammaContrast, SigmoidContrast, LogContrast, LinearContrast from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import *
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import * from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import *
Switch import from contrast to all
Switch import from contrast to all Change import from contrast.py in augmenters/__init__.py to * instead of selective, as * should not import private methods anyways.
Python
mit
aleju/ImageAugmenter,aleju/imgaug,aleju/imgaug
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * - from imgaug.augmenters.contrast import GammaContrast, SigmoidContrast, LogContrast, LinearContrast + from imgaug.augmenters.contrast import * from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import *
Switch import from contrast to all
## Code Before: from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import GammaContrast, SigmoidContrast, LogContrast, LinearContrast from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import * ## Instruction: Switch import from contrast to all ## Code After: from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import * from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import *
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * - from imgaug.augmenters.contrast import GammaContrast, SigmoidContrast, LogContrast, LinearContrast + from imgaug.augmenters.contrast import * from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import * from imgaug.augmenters.meta import * from imgaug.augmenters.overlay import * from imgaug.augmenters.segmentation import * from imgaug.augmenters.size import *
3f635db216c292c0eec720d28ecfbec3e23f1ca5
ynr/s3_storage.py
ynr/s3_storage.py
from storages.backends.s3boto3 import S3Boto3Storage from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
import os from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class PatchedS3Boto3Storage(S3Boto3Storage): def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified # size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose # instance super()._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
Patch S3Boto3Storage to prevent closed file error when collectin static
Patch S3Boto3Storage to prevent closed file error when collectin static This is copied from the aggregator API and prevents a bug where the storage closes the files too early, raising a boto exception.
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
+ import os + - from storages.backends.s3boto3 import S3Boto3Storage + from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings + class PatchedS3Boto3Storage(S3Boto3Storage): + def _save_content(self, obj, content, parameters): + """ + We create a clone of the content file as when this is passed to boto3 + it wrongly closes the file upon upload where as the storage backend + expects it to still be open + """ + # Seek our content back to the start + content.seek(0, os.SEEK_SET) + + # Create a temporary file that will write to disk after a specified + # size + content_autoclose = SpooledTemporaryFile() + + # Write our original content into our copy that will be closed by boto3 + content_autoclose.write(content.read()) + # Upload the object which will auto close the content_autoclose + # instance + super()._save_content(obj, content_autoclose, parameters) + + # Cleanup if this is fixed upstream our duplicate should always close + if not content_autoclose.closed: + content_autoclose.close() + + - class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): + class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION - class MediaStorage(S3Boto3Storage): + class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
Patch S3Boto3Storage to prevent closed file error when collectin static
## Code Before: from storages.backends.s3boto3 import S3Boto3Storage from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("") ## Instruction: Patch S3Boto3Storage to prevent closed file error when collectin static ## Code After: import os from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings class PatchedS3Boto3Storage(S3Boto3Storage): def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a specified # size content_autoclose = SpooledTemporaryFile() # Write our original content into our copy that will be closed by boto3 content_autoclose.write(content.read()) # Upload the object which will auto close the content_autoclose # instance super()._save_content(obj, content_autoclose, parameters) # Cleanup if this is fixed upstream our duplicate should always close if not content_autoclose.closed: content_autoclose.close() class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION class MediaStorage(PatchedS3Boto3Storage): """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
+ import os + - from storages.backends.s3boto3 import S3Boto3Storage + from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile ? ++++++++++++++++++++++ from django.contrib.staticfiles.storage import ManifestFilesMixin from pipeline.storage import PipelineMixin from django.conf import settings + class PatchedS3Boto3Storage(S3Boto3Storage): + def _save_content(self, obj, content, parameters): + """ + We create a clone of the content file as when this is passed to boto3 + it wrongly closes the file upon upload where as the storage backend + expects it to still be open + """ + # Seek our content back to the start + content.seek(0, os.SEEK_SET) + + # Create a temporary file that will write to disk after a specified + # size + content_autoclose = SpooledTemporaryFile() + + # Write our original content into our copy that will be closed by boto3 + content_autoclose.write(content.read()) + # Upload the object which will auto close the content_autoclose + # instance + super()._save_content(obj, content_autoclose, parameters) + + # Cleanup if this is fixed upstream our duplicate should always close + if not content_autoclose.closed: + content_autoclose.close() + + - class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage): + class StaticStorage(PipelineMixin, ManifestFilesMixin, PatchedS3Boto3Storage): ? +++++++ """ Store static files on S3 at STATICFILES_LOCATION, post-process with pipeline and then create manifest files for them. """ location = settings.STATICFILES_LOCATION - class MediaStorage(S3Boto3Storage): + class MediaStorage(PatchedS3Boto3Storage): ? +++++++ """ Store media files on S3 at MEDIAFILES_LOCATION """ location = settings.MEDIAFILES_LOCATION @property def base_url(self): """ This is a small hack around the fact that Django Storages dosn't provide the same methods as FileSystemStorage. `base_url` is missing from their implementation of the storage class, so we emulate it here by calling URL with an empty key name. """ return self.url("")
b912c1a508640c7c351ed1d945bfeebdaa995332
djcelery/management/commands/celeryd.py
djcelery/management/commands/celeryd.py
from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): worker.run(**options)
from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): worker.check_args(args) worker.run(**options)
Add requested call to check_args.
Add requested call to check_args.
Python
bsd-3-clause
Amanit/django-celery,digimarc/django-celery,iris-edu-int/django-celery,axiom-data-science/django-celery,celery/django-celery,CloudNcodeInc/django-celery,Amanit/django-celery,axiom-data-science/django-celery,georgewhewell/django-celery,CloudNcodeInc/django-celery,iris-edu-int/django-celery,digimarc/django-celery,celery/django-celery,tkanemoto/django-celery,CloudNcodeInc/django-celery,kanemra/django-celery,kanemra/django-celery,iris-edu-int/django-celery,tkanemoto/django-celery,georgewhewell/django-celery,georgewhewell/django-celery,Amanit/django-celery,digimarc/django-celery,tkanemoto/django-celery,celery/django-celery,axiom-data-science/django-celery,kanemra/django-celery
from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): + worker.check_args(args) worker.run(**options)
Add requested call to check_args.
## Code Before: from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): worker.run(**options) ## Instruction: Add requested call to check_args. ## Code After: from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): worker.check_args(args) worker.run(**options)
from __future__ import absolute_import, unicode_literals from celery.bin import worker from djcelery.app import app from djcelery.management.base import CeleryCommand worker = worker.worker(app=app) class Command(CeleryCommand): """Run the celery daemon.""" help = 'Old alias to the "celery worker" command.' requires_model_validation = True options = (CeleryCommand.options + worker.get_options() + worker.preload_options) def handle(self, *args, **options): + worker.check_args(args) worker.run(**options)
504ae635e08ccf0784db0a0586e8796f5bd360bb
test_chatbot_brain.py
test_chatbot_brain.py
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Python
mit
corinnelhh/chatbot,corinnelhh/chatbot
import chatbot_brain + + stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): - u"""Assert the returned word is in the lexicon and is not a stop char.""" + u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] - assert bot.i_filter_random(words) == u"What a funny thing to say!" + assert bot.i_filter_random(words) == stock + + + def test_i_filter_random_words_not_in_lexicon(): + u"""Assert that if all words are not in lexicon the default is returned.""" + bot = chatbot_brain.Chatbot() + words = ["moose", "bear", "eagle"] + lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} + assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
## Code Before: import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive ## Instruction: Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon ## Code After: import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
import chatbot_brain + + stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): - u"""Assert the returned word is in the lexicon and is not a stop char.""" + u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] - assert bot.i_filter_random(words) == u"What a funny thing to say!" + assert bot.i_filter_random(words) == stock + + + def test_i_filter_random_words_not_in_lexicon(): + u"""Assert that if all words are not in lexicon the default is returned.""" + bot = chatbot_brain.Chatbot() + words = ["moose", "bear", "eagle"] + lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} + assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
c5cf8df78106e15a81f976f99d26d361b036318a
indra/tools/reading/run_drum_reading.py
indra/tools/reading/run_drum_reading.py
import sys import json from indra.sources.trips.drum_reader import DrumReader from indra.sources.trips import process_xml def read_content(content): sentences = [] for k, v in content.items(): sentences += v dr = DrumReader(to_read=sentences) try: dr.start() except SystemExit: pass statements = [] for extraction in dr.extractions: statements += process_xml(extraction).statements return statements if __name__ == '__main__': file_name = sys.argv[1] with open(file_name, 'rt') as fh: content = json.load(fh) statements = read_content(content) print(statements)
import sys import json import time import pickle from indra.sources.trips import process_xml from indra.sources.trips.drum_reader import DrumReader def set_pmid(statements, pmid): for stmt in statements: for evidence in stmt.evidence: evidence.pmid = pmid def read_content(content, host): all_statements = [] for pmid, sentences in content.items(): print('================================') print('Processing %d sentences for %s' % (len(sentences), pmid)) ts = time.time() dr = DrumReader(to_read=sentences, host=host) try: dr.start() except SystemExit: pass statements = [] for extraction in dr.extractions: tp = process_xml(extraction) statements += tp.statements set_pmid(statements, pmid) te = time.time() print('Reading took %d seconds and produced %d Statements.' % (te-ts, len(statements))) all_statements += statements return all_statements def save_results(statements, out_fname): with open(out_fname, 'wb') as fh: pickle.dump(statements, fh) if __name__ == '__main__': host = sys.argv[1] file_name = sys.argv[2] with open(file_name, 'rt') as fh: content = json.load(fh) statements = read_content(content, host) save_results(statements, 'results.pkl')
Improve batch Drum reading implementation
Improve batch Drum reading implementation
Python
bsd-2-clause
bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra
import sys import json + import time + import pickle + from indra.sources.trips import process_xml from indra.sources.trips.drum_reader import DrumReader - from indra.sources.trips import process_xml + + def set_pmid(statements, pmid): + for stmt in statements: + for evidence in stmt.evidence: + evidence.pmid = pmid + + - def read_content(content): + def read_content(content, host): - sentences = [] + all_statements = [] - for k, v in content.items(): + for pmid, sentences in content.items(): - sentences += v + print('================================') + print('Processing %d sentences for %s' % (len(sentences), pmid)) + ts = time.time() - dr = DrumReader(to_read=sentences) + dr = DrumReader(to_read=sentences, host=host) - try: + try: - dr.start() + dr.start() - except SystemExit: + except SystemExit: - pass + pass - statements = [] + statements = [] - for extraction in dr.extractions: + for extraction in dr.extractions: - statements += process_xml(extraction).statements + tp = process_xml(extraction) + statements += tp.statements + set_pmid(statements, pmid) + te = time.time() + print('Reading took %d seconds and produced %d Statements.' % + (te-ts, len(statements))) + all_statements += statements - return statements + return all_statements + + + def save_results(statements, out_fname): + with open(out_fname, 'wb') as fh: + pickle.dump(statements, fh) + if __name__ == '__main__': + host = sys.argv[1] - file_name = sys.argv[1] + file_name = sys.argv[2] with open(file_name, 'rt') as fh: content = json.load(fh) - statements = read_content(content) + statements = read_content(content, host) - print(statements) + save_results(statements, 'results.pkl')
Improve batch Drum reading implementation
## Code Before: import sys import json from indra.sources.trips.drum_reader import DrumReader from indra.sources.trips import process_xml def read_content(content): sentences = [] for k, v in content.items(): sentences += v dr = DrumReader(to_read=sentences) try: dr.start() except SystemExit: pass statements = [] for extraction in dr.extractions: statements += process_xml(extraction).statements return statements if __name__ == '__main__': file_name = sys.argv[1] with open(file_name, 'rt') as fh: content = json.load(fh) statements = read_content(content) print(statements) ## Instruction: Improve batch Drum reading implementation ## Code After: import sys import json import time import pickle from indra.sources.trips import process_xml from indra.sources.trips.drum_reader import DrumReader def set_pmid(statements, pmid): for stmt in statements: for evidence in stmt.evidence: evidence.pmid = pmid def read_content(content, host): all_statements = [] for pmid, sentences in content.items(): print('================================') print('Processing %d sentences for %s' % (len(sentences), pmid)) ts = time.time() dr = DrumReader(to_read=sentences, host=host) try: dr.start() except SystemExit: pass statements = [] for extraction in dr.extractions: tp = process_xml(extraction) statements += tp.statements set_pmid(statements, pmid) te = time.time() print('Reading took %d seconds and produced %d Statements.' % (te-ts, len(statements))) all_statements += statements return all_statements def save_results(statements, out_fname): with open(out_fname, 'wb') as fh: pickle.dump(statements, fh) if __name__ == '__main__': host = sys.argv[1] file_name = sys.argv[2] with open(file_name, 'rt') as fh: content = json.load(fh) statements = read_content(content, host) save_results(statements, 'results.pkl')
import sys import json + import time + import pickle + from indra.sources.trips import process_xml from indra.sources.trips.drum_reader import DrumReader - from indra.sources.trips import process_xml + + def set_pmid(statements, pmid): + for stmt in statements: + for evidence in stmt.evidence: + evidence.pmid = pmid + + - def read_content(content): + def read_content(content, host): ? ++++++ - sentences = [] + all_statements = [] - for k, v in content.items(): ? ^ ^ + for pmid, sentences in content.items(): ? ^^^^ ^^^^^^^^^ - sentences += v + print('================================') + print('Processing %d sentences for %s' % (len(sentences), pmid)) + ts = time.time() - dr = DrumReader(to_read=sentences) + dr = DrumReader(to_read=sentences, host=host) ? ++++ +++++++++++ - try: + try: ? ++++ - dr.start() + dr.start() ? ++++ - except SystemExit: + except SystemExit: ? ++++ - pass + pass ? ++++ - statements = [] + statements = [] ? ++++ - for extraction in dr.extractions: + for extraction in dr.extractions: ? ++++ - statements += process_xml(extraction).statements + tp = process_xml(extraction) + statements += tp.statements + set_pmid(statements, pmid) + te = time.time() + print('Reading took %d seconds and produced %d Statements.' % + (te-ts, len(statements))) + all_statements += statements - return statements + return all_statements ? ++++ + + + def save_results(statements, out_fname): + with open(out_fname, 'wb') as fh: + pickle.dump(statements, fh) + if __name__ == '__main__': + host = sys.argv[1] - file_name = sys.argv[1] ? ^ + file_name = sys.argv[2] ? ^ with open(file_name, 'rt') as fh: content = json.load(fh) - statements = read_content(content) + statements = read_content(content, host) ? ++++++ - print(statements) + save_results(statements, 'results.pkl')
f106a434df84497e12cfbdf1e693e28b6c567711
kubespawner/utils.py
kubespawner/utils.py
from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs): loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break if func(*args, **kwargs): return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message)
from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine def exponential_backoff(pass_func, fail_message, timeout=10, *args, **kwargs): """ Exponentially backoff until pass_func is true. This function will wait with exponential backoff + random jitter for as many iterations as needed, with maximum timeout timeout. If pass_func is still returning false at the end of timeout, a TimeoutError will be raised. *args and **kwargs are passed to pass_func. """ loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break if pass_func(*args, **kwargs): return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message)
Add docstrings to exponential backoff
Add docstrings to exponential backoff
Python
bsd-3-clause
yuvipanda/jupyterhub-kubernetes-spawner,jupyterhub/kubespawner
from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine - def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs): + def exponential_backoff(pass_func, fail_message, timeout=10, *args, **kwargs): + """ + Exponentially backoff until pass_func is true. + + This function will wait with exponential backoff + random jitter for as + many iterations as needed, with maximum timeout timeout. If pass_func is + still returning false at the end of timeout, a TimeoutError will be raised. + + *args and **kwargs are passed to pass_func. + """ loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break - if func(*args, **kwargs): + if pass_func(*args, **kwargs): return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message)
Add docstrings to exponential backoff
## Code Before: from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs): loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break if func(*args, **kwargs): return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message) ## Instruction: Add docstrings to exponential backoff ## Code After: from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine def exponential_backoff(pass_func, fail_message, timeout=10, *args, **kwargs): """ Exponentially backoff until pass_func is true. This function will wait with exponential backoff + random jitter for as many iterations as needed, with maximum timeout timeout. If pass_func is still returning false at the end of timeout, a TimeoutError will be raised. *args and **kwargs are passed to pass_func. """ loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break if pass_func(*args, **kwargs): return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message)
from concurrent.futures import ThreadPoolExecutor import random from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE from tornado import gen, ioloop from traitlets.config import SingletonConfigurable class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor): """ Simple wrapper to ThreadPoolExecutor that is also a singleton. We want one ThreadPool that is used by all the spawners, rather than one ThreadPool per spawner! """ pass @gen.coroutine - def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs): + def exponential_backoff(pass_func, fail_message, timeout=10, *args, **kwargs): ? +++++ + """ + Exponentially backoff until pass_func is true. + + This function will wait with exponential backoff + random jitter for as + many iterations as needed, with maximum timeout timeout. If pass_func is + still returning false at the end of timeout, a TimeoutError will be raised. + + *args and **kwargs are passed to pass_func. + """ loop = ioloop.IOLoop.current() start_tic = loop.time() dt = DT_MIN while True: if (loop.time() - start_tic) > timeout: # We time out! break - if func(*args, **kwargs): + if pass_func(*args, **kwargs): ? +++++ return else: yield gen.sleep(dt) # Add some random jitter to improve performance # This makes sure that we don't overload any single iteration # of the tornado loop with too many things # See https://www.awsarchitectureblog.com/2015/03/backoff.html # for a good example of why and how this helps dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE)) raise TimeoutError(fail_message)
d9fd011a2750a01cac67aa6ca37c0aedc2a7ad94
law/workflow/local.py
law/workflow/local.py
__all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
__all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def __init__(self, *args, **kwargs): super(LocalWorkflowProxy, self).__init__(*args, **kwargs) self._has_run = False def complete(self): return self._has_run def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs def run(self): self._has_run = True class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
Add missing run method to LocalWorkflow.
Add missing run method to LocalWorkflow.
Python
bsd-3-clause
riga/law,riga/law
__all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" + def __init__(self, *args, **kwargs): + super(LocalWorkflowProxy, self).__init__(*args, **kwargs) + + self._has_run = False + + def complete(self): + return self._has_run + def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs + + def run(self): + self._has_run = True class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
Add missing run method to LocalWorkflow.
## Code Before: __all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy ## Instruction: Add missing run method to LocalWorkflow. ## Code After: __all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def __init__(self, *args, **kwargs): super(LocalWorkflowProxy, self).__init__(*args, **kwargs) self._has_run = False def complete(self): return self._has_run def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs def run(self): self._has_run = True class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
__all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" + def __init__(self, *args, **kwargs): + super(LocalWorkflowProxy, self).__init__(*args, **kwargs) + + self._has_run = False + + def complete(self): + return self._has_run + def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs + + def run(self): + self._has_run = True class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
e99697b18c7ec6052ed161467197b0e86ed3603d
nbgrader/preprocessors/execute.py
nbgrader/preprocessors/execute.py
from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) extra_arguments = List(["--HistoryManager.hist_file=:memory:"])
from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List from textwrap import dedent from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) extra_arguments = List([], config=True, help=dedent( """ A list of extra arguments to pass to the kernel. For python kernels, this defaults to ``--HistoryManager.hist_file=:memory:``. For other kernels this is just an empty list. """)) def preprocess(self, nb, resources): kernel_name = nb.metadata.get('kernelspec', {}).get('name', 'python') if self.extra_arguments == [] and kernel_name == "python": self.extra_arguments = ["--HistoryManager.hist_file=:memory:"] return super(Execute, self).preprocess(nb, resources)
Change options so other kernels work with nbgrader
Change options so other kernels work with nbgrader
Python
bsd-3-clause
ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,jhamrick/nbgrader
from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List + from textwrap import dedent from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) - extra_arguments = List(["--HistoryManager.hist_file=:memory:"]) + extra_arguments = List([], config=True, help=dedent( + """ + A list of extra arguments to pass to the kernel. For python kernels, + this defaults to ``--HistoryManager.hist_file=:memory:``. For other + kernels this is just an empty list. + """)) + def preprocess(self, nb, resources): + kernel_name = nb.metadata.get('kernelspec', {}).get('name', 'python') + if self.extra_arguments == [] and kernel_name == "python": + self.extra_arguments = ["--HistoryManager.hist_file=:memory:"] + + return super(Execute, self).preprocess(nb, resources) +
Change options so other kernels work with nbgrader
## Code Before: from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) extra_arguments = List(["--HistoryManager.hist_file=:memory:"]) ## Instruction: Change options so other kernels work with nbgrader ## Code After: from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List from textwrap import dedent from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) extra_arguments = List([], config=True, help=dedent( """ A list of extra arguments to pass to the kernel. For python kernels, this defaults to ``--HistoryManager.hist_file=:memory:``. For other kernels this is just an empty list. """)) def preprocess(self, nb, resources): kernel_name = nb.metadata.get('kernelspec', {}).get('name', 'python') if self.extra_arguments == [] and kernel_name == "python": self.extra_arguments = ["--HistoryManager.hist_file=:memory:"] return super(Execute, self).preprocess(nb, resources)
from nbconvert.preprocessors import ExecutePreprocessor from traitlets import Bool, List + from textwrap import dedent from . import NbGraderPreprocessor class Execute(NbGraderPreprocessor, ExecutePreprocessor): interrupt_on_timeout = Bool(True) allow_errors = Bool(True) + extra_arguments = List([], config=True, help=dedent( + """ + A list of extra arguments to pass to the kernel. For python kernels, + this defaults to ``--HistoryManager.hist_file=:memory:``. For other + kernels this is just an empty list. + """)) + + def preprocess(self, nb, resources): + kernel_name = nb.metadata.get('kernelspec', {}).get('name', 'python') + if self.extra_arguments == [] and kernel_name == "python": - extra_arguments = List(["--HistoryManager.hist_file=:memory:"]) ? ----- - + self.extra_arguments = ["--HistoryManager.hist_file=:memory:"] ? +++++++++++++ + + return super(Execute, self).preprocess(nb, resources)
1de19bed8b61b87c1f1afd1b2c8e5499a9e2da9a
backend/breach/tests.py
backend/breach/tests.py
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint="http://di.uoa.gr/", prefix="test", alphabet="0123456789" ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="0", data="bigbigbigbigbigbig" ), SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="1", data="small" ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='1', data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
Fix double quotes in analyzer testcase
Fix double quotes in analyzer testcase
Python
mit
dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( - endpoint="http://di.uoa.gr/", + endpoint='http://di.uoa.gr/', - prefix="test", + prefix='test', - alphabet="0123456789" + alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, - knownsecret="testsecret", + knownsecret='testsecret', - knownalphabet="01", + knownalphabet='01', - candidatealphabet="0", + candidatealphabet='0', - data="bigbigbigbigbigbig" + data='bigbigbigbigbigbig' ), SampleSet.objects.create( victim=victim, amount=1, - knownsecret="testsecret", + knownsecret='testsecret', - knownalphabet="01", + knownalphabet='01', - candidatealphabet="1", + candidatealphabet='1', - data="small" + data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
Fix double quotes in analyzer testcase
## Code Before: from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint="http://di.uoa.gr/", prefix="test", alphabet="0123456789" ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="0", data="bigbigbigbigbigbig" ), SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="1", data="small" ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1") ## Instruction: Fix double quotes in analyzer testcase ## Code After: from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='1', data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( - endpoint="http://di.uoa.gr/", ? ^ ^ + endpoint='http://di.uoa.gr/', ? ^ ^ - prefix="test", ? ^ ^ + prefix='test', ? ^ ^ - alphabet="0123456789" ? ^ ^ + alphabet='0123456789' ? ^ ^ ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, - knownsecret="testsecret", ? ^ ^ + knownsecret='testsecret', ? ^ ^ - knownalphabet="01", ? ^ ^ + knownalphabet='01', ? ^ ^ - candidatealphabet="0", ? ^ ^ + candidatealphabet='0', ? ^ ^ - data="bigbigbigbigbigbig" ? ^ ^ + data='bigbigbigbigbigbig' ? ^ ^ ), SampleSet.objects.create( victim=victim, amount=1, - knownsecret="testsecret", ? ^ ^ + knownsecret='testsecret', ? ^ ^ - knownalphabet="01", ? ^ ^ + knownalphabet='01', ? ^ ^ - candidatealphabet="1", ? ^ ^ + candidatealphabet='1', ? ^ ^ - data="small" ? ^ ^ + data='small' ? ^ ^ ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
af63afb5d5a010406557e325e759cdd310214c71
setup.py
setup.py
def main(): x = input("Enter a number: ") print("Your number is {}".format(x)) if __name__ == '__main__': main()
def main(): # Get input from user and display it feels = input("On a scale of 1-10, how do you feel? ") print("You selected: {}".format(feels)) # Python Data Types integer = 42 floater = 3.14 stringer = 'Hello, World!' tupler = (1, 2, 3) lister = [1, 2, 3] dicter = dict( one = 1, two = 2, three = 3 ) boolTrue = True boolFalse = False # Conditionals num1, num2 = 0, 1 if (num1 > num2): print("{} is greater than {}".format(num1, num2)) elif (num1 < num2): print("{} is less than {}".format(num1, num2)) else: print("{} is equal to {}".format(num1, num2)) bigger = num1 if num1 >= num2 else num2 smaller = num1 if num1 < num2 else num2 print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller)) # Python version of a switch statement choices = dict( a = 'First', b = 'Second', c = 'Third', d = 'Fourth', e = 'Fifth' ) opt1 = 'c' opt2 = 'f' default = 'Option not found' print(choices) print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default))) print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default))) # Loops print("Fibonacci series up to 100:") a, b = 0, 1 while b < 100: print(b, end=" ") a, b = b, a + b print() for letter in stringer: if letter in 'aeiouAEIOU': continue if letter in '!@#$%^&*.,?;:-_+=|': break print(letter) # Get an index using a for loop with enumerate() for index, letter in enumerate(stringer): print("Index: {} is letter: {}".format(index, letter)) if __name__ == '__main__': main()
Add PY quick start examples
Add PY quick start examples
Python
mit
HKuz/Test_Code
def main(): - x = input("Enter a number: ") - print("Your number is {}".format(x)) + # Get input from user and display it + feels = input("On a scale of 1-10, how do you feel? ") + print("You selected: {}".format(feels)) + + # Python Data Types + integer = 42 + floater = 3.14 + stringer = 'Hello, World!' + tupler = (1, 2, 3) + lister = [1, 2, 3] + dicter = dict( + one = 1, + two = 2, + three = 3 + ) + boolTrue = True + boolFalse = False + + # Conditionals + num1, num2 = 0, 1 + if (num1 > num2): + print("{} is greater than {}".format(num1, num2)) + elif (num1 < num2): + print("{} is less than {}".format(num1, num2)) + else: + print("{} is equal to {}".format(num1, num2)) + + bigger = num1 if num1 >= num2 else num2 + smaller = num1 if num1 < num2 else num2 + print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller)) + + # Python version of a switch statement + choices = dict( + a = 'First', + b = 'Second', + c = 'Third', + d = 'Fourth', + e = 'Fifth' + ) + opt1 = 'c' + opt2 = 'f' + default = 'Option not found' + + print(choices) + print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default))) + print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default))) + + # Loops + print("Fibonacci series up to 100:") + a, b = 0, 1 + while b < 100: + print(b, end=" ") + a, b = b, a + b + print() + + for letter in stringer: + if letter in 'aeiouAEIOU': + continue + if letter in '!@#$%^&*.,?;:-_+=|': + break + print(letter) + + # Get an index using a for loop with enumerate() + for index, letter in enumerate(stringer): + print("Index: {} is letter: {}".format(index, letter)) if __name__ == '__main__': main()
Add PY quick start examples
## Code Before: def main(): x = input("Enter a number: ") print("Your number is {}".format(x)) if __name__ == '__main__': main() ## Instruction: Add PY quick start examples ## Code After: def main(): # Get input from user and display it feels = input("On a scale of 1-10, how do you feel? ") print("You selected: {}".format(feels)) # Python Data Types integer = 42 floater = 3.14 stringer = 'Hello, World!' tupler = (1, 2, 3) lister = [1, 2, 3] dicter = dict( one = 1, two = 2, three = 3 ) boolTrue = True boolFalse = False # Conditionals num1, num2 = 0, 1 if (num1 > num2): print("{} is greater than {}".format(num1, num2)) elif (num1 < num2): print("{} is less than {}".format(num1, num2)) else: print("{} is equal to {}".format(num1, num2)) bigger = num1 if num1 >= num2 else num2 smaller = num1 if num1 < num2 else num2 print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller)) # Python version of a switch statement choices = dict( a = 'First', b = 'Second', c = 'Third', d = 'Fourth', e = 'Fifth' ) opt1 = 'c' opt2 = 'f' default = 'Option not found' print(choices) print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default))) print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default))) # Loops print("Fibonacci series up to 100:") a, b = 0, 1 while b < 100: print(b, end=" ") a, b = b, a + b print() for letter in stringer: if letter in 'aeiouAEIOU': continue if letter in '!@#$%^&*.,?;:-_+=|': break print(letter) # Get an index using a for loop with enumerate() for index, letter in enumerate(stringer): print("Index: {} is letter: {}".format(index, letter)) if __name__ == '__main__': main()
def main(): - x = input("Enter a number: ") - print("Your number is {}".format(x)) + # Get input from user and display it + feels = input("On a scale of 1-10, how do you feel? ") + print("You selected: {}".format(feels)) + + # Python Data Types + integer = 42 + floater = 3.14 + stringer = 'Hello, World!' + tupler = (1, 2, 3) + lister = [1, 2, 3] + dicter = dict( + one = 1, + two = 2, + three = 3 + ) + boolTrue = True + boolFalse = False + + # Conditionals + num1, num2 = 0, 1 + if (num1 > num2): + print("{} is greater than {}".format(num1, num2)) + elif (num1 < num2): + print("{} is less than {}".format(num1, num2)) + else: + print("{} is equal to {}".format(num1, num2)) + + bigger = num1 if num1 >= num2 else num2 + smaller = num1 if num1 < num2 else num2 + print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller)) + + # Python version of a switch statement + choices = dict( + a = 'First', + b = 'Second', + c = 'Third', + d = 'Fourth', + e = 'Fifth' + ) + opt1 = 'c' + opt2 = 'f' + default = 'Option not found' + + print(choices) + print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default))) + print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default))) + + # Loops + print("Fibonacci series up to 100:") + a, b = 0, 1 + while b < 100: + print(b, end=" ") + a, b = b, a + b + print() + + for letter in stringer: + if letter in 'aeiouAEIOU': + continue + if letter in '!@#$%^&*.,?;:-_+=|': + break + print(letter) + + # Get an index using a for loop with enumerate() + for index, letter in enumerate(stringer): + print("Index: {} is letter: {}".format(index, letter)) if __name__ == '__main__': main()
0b6d5b0d10974842a0e52904d9793bfa4313ffb0
src/api/v1/watchers/__init__.py
src/api/v1/watchers/__init__.py
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None else: return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
Fix user role filtered namespace
Fix user role filtered namespace
Python
apache-2.0
ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None - else: - return data + return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
Fix user role filtered namespace
## Code Before: def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None else: return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data ## Instruction: Fix user role filtered namespace ## Code After: def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None - else: - return data ? ---- + return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
a6bd1cfc5f87d6f9a7ac846665fcab5b02c33c1d
tubular/scripts/hipchat/submit_hipchat_msg.py
tubular/scripts/hipchat/submit_hipchat_msg.py
import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) def cli(auth_token_env_var, channel): """ Post a message to a HipChat channel. """ msg = "Test message from the demo GoCD release pipeline." headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", "message": msg, "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli()
import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) @click.option('--message', '-m', default="Default message.", help="Message to send to HipChat channel.", ) def cli(auth_token_env_var, channel, message): """ Post a message to a HipChat channel. """ headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", "message": message, "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli()
Add ability to set HipChat message contents.
Add ability to set HipChat message contents.
Python
agpl-3.0
eltoncarr/tubular,eltoncarr/tubular
import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) + @click.option('--message', '-m', + default="Default message.", + help="Message to send to HipChat channel.", + ) - def cli(auth_token_env_var, channel): + def cli(auth_token_env_var, channel, message): """ Post a message to a HipChat channel. """ - msg = "Test message from the demo GoCD release pipeline." - headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", - "message": msg, + "message": message, "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli()
Add ability to set HipChat message contents.
## Code Before: import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) def cli(auth_token_env_var, channel): """ Post a message to a HipChat channel. """ msg = "Test message from the demo GoCD release pipeline." headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", "message": msg, "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli() ## Instruction: Add ability to set HipChat message contents. ## Code After: import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) @click.option('--message', '-m', default="Default message.", help="Message to send to HipChat channel.", ) def cli(auth_token_env_var, channel, message): """ Post a message to a HipChat channel. """ headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", "message": message, "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli()
import os import sys import requests import click HIPCHAT_API_URL = "http://api.hipchat.com" NOTIFICATION_POST = "/v2/room/{}/notification" AUTH_HEADER = "Authorization: Bearer {}" @click.command() @click.option('--auth_token_env_var', '-a', help="Environment variable containing authentication token to use for HipChat REST API.", ) @click.option('--channel', '-c', default="release pipeline", help="Channel to which the script should post a message.", ) + @click.option('--message', '-m', + default="Default message.", + help="Message to send to HipChat channel.", + ) - def cli(auth_token_env_var, channel): + def cli(auth_token_env_var, channel, message): ? +++++++++ """ Post a message to a HipChat channel. """ - msg = "Test message from the demo GoCD release pipeline." - headers = { "Authorization": "Bearer {}".format(os.environ[auth_token_env_var]) } msg_payload = { "color": "green", - "message": msg, + "message": message, ? + ++ + "notify": False, "message_format": "text" } post_url = HIPCHAT_API_URL + NOTIFICATION_POST.format(channel) r = requests.post(post_url, headers=headers, json=msg_payload) # An exit code of 0 means success and non-zero means failure. success = r.status_code in (200, 201, 204) sys.exit(not success) if __name__ == '__main__': cli()
c47df6cf4533676c33ca3466cb269657df3e228f
intexration/__main__.py
intexration/__main__.py
import argparse import logging.config import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
import argparse import logging.config from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('SERVER', 'host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('SERVER', 'port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
Set config contained a bug after refactoring
Set config contained a bug after refactoring
Python
apache-2.0
JDevlieghere/InTeXration,JDevlieghere/InTeXration
import argparse import logging.config - import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: - settings.set_config('host', args.host) + settings.set_config('SERVER', 'host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: - settings.set_config('port', args.port) + settings.set_config('SERVER', 'port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
Set config contained a bug after refactoring
## Code Before: import argparse import logging.config import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main() ## Instruction: Set config contained a bug after refactoring ## Code After: import argparse import logging.config from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('SERVER', 'host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('SERVER', 'port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
import argparse import logging.config - import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: - settings.set_config('host', args.host) + settings.set_config('SERVER', 'host', args.host) ? ++++++++++ logging.INFO("Host changed to %s", args.host) if args.port is not None: - settings.set_config('port', args.port) + settings.set_config('SERVER', 'port', args.port) ? ++++++++++ logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
6b7e32c98fa8a11dcd7bbbadaa2a057e4ff0ce90
f5_os_test/__init__.py
f5_os_test/__init__.py
__version__ = '0.2.0'
import random import string __version__ = '0.2.0' def random_name(prefix, N): """Creates a name with random characters. Returns a new string created from an input prefix appended with a set of random characters. The number of random characters appended to the prefix string is defined by the N parameter. For example, random_name('test_', 6) might return "test_FR3N5Y" :param string prefix: String to append randoms characters. :param int N: Number of random characters to append. """ return prefix + ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(N))
Add function to create name strings with random characters
Add function to create name strings with random characters Issues: Fixes #48 Problem: Need a function that will generate names with random chars. Analysis: Added new function, random_name(). Tests: test_solution.py
Python
apache-2.0
F5Networks/f5-openstack-test,pjbreaux/f5-openstack-test
+ + import random + import string + __version__ = '0.2.0' + + def random_name(prefix, N): + """Creates a name with random characters. + + Returns a new string created from an input prefix appended with a set of + random characters. The number of random characters appended to + the prefix string is defined by the N parameter. For example, + + random_name('test_', 6) might return "test_FR3N5Y" + + :param string prefix: String to append randoms characters. + :param int N: Number of random characters to append. + """ + return prefix + ''.join( + random.SystemRandom().choice( + string.ascii_uppercase + string.digits) for _ in range(N)) +
Add function to create name strings with random characters
## Code Before: __version__ = '0.2.0' ## Instruction: Add function to create name strings with random characters ## Code After: import random import string __version__ = '0.2.0' def random_name(prefix, N): """Creates a name with random characters. Returns a new string created from an input prefix appended with a set of random characters. The number of random characters appended to the prefix string is defined by the N parameter. For example, random_name('test_', 6) might return "test_FR3N5Y" :param string prefix: String to append randoms characters. :param int N: Number of random characters to append. """ return prefix + ''.join( random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(N))
+ + import random + import string + __version__ = '0.2.0' + + + def random_name(prefix, N): + """Creates a name with random characters. + + Returns a new string created from an input prefix appended with a set of + random characters. The number of random characters appended to + the prefix string is defined by the N parameter. For example, + + random_name('test_', 6) might return "test_FR3N5Y" + + :param string prefix: String to append randoms characters. + :param int N: Number of random characters to append. + """ + return prefix + ''.join( + random.SystemRandom().choice( + string.ascii_uppercase + string.digits) for _ in range(N))
1101fd3855c90ece679e4b9af37c5f3f5dc343eb
spacy/en/__init__.py
spacy/en/__init__.py
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides)
from __future__ import unicode_literals from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides)
Fix formatting and remove unused imports
Fix formatting and remove unused imports
Python
mit
recognai/spaCy,raphael0202/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,explosion/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,raphael0202/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy
- from __future__ import unicode_literals, print_function + from __future__ import unicode_literals - from os import path from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * + try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides)
Fix formatting and remove unused imports
## Code Before: from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides) ## Instruction: Fix formatting and remove unused imports ## Code After: from __future__ import unicode_literals from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides)
- from __future__ import unicode_literals, print_function ? ---------------- + from __future__ import unicode_literals - from os import path from ..language import Language from ..lemmatizer import Lemmatizer from ..vocab import Vocab from ..tokenizer import Tokenizer from ..attrs import LANG from ..deprecated import fix_glove_vectors_loading from .language_data import * + try: basestring except NameError: basestring = str class English(Language): lang = 'en' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'en' tokenizer_exceptions = TOKENIZER_EXCEPTIONS tag_map = TAG_MAP stop_words = STOP_WORDS def __init__(self, **overrides): # Special-case hack for loading the GloVe vectors, to support <1.0 overrides = fix_glove_vectors_loading(overrides) Language.__init__(self, **overrides)
5bbd288c40e3a2bc1ee791545d704452699334f3
cr8/aio.py
cr8/aio.py
from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) await q.join() await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) q.task_done() def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q)))
from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q)))
Remove q.join() / task_done() usage
Remove q.join() / task_done() usage Don't have to block producer anymore - it will wait for the consumer to finish anyway
Python
mit
mikethebeer/cr8,mfussenegger/cr8
from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) - await q.join() await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) - q.task_done() def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q)))
Remove q.join() / task_done() usage
## Code Before: from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) await q.join() await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) q.task_done() def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q))) ## Instruction: Remove q.join() / task_done() usage ## Code After: from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q)))
from tqdm import tqdm import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass async def map_async(q, corof, iterable): for i in iterable: task = asyncio.ensure_future(corof(*i)) await q.put(task) - await q.join() await q.put(None) async def consume(q): with tqdm(unit=' requests') as t: while True: task = await q.get() if task is None: break await task t.update(1) - q.task_done() def run(coro, iterable, concurrency, loop=None): loop = loop or asyncio.get_event_loop() q = asyncio.Queue(maxsize=concurrency) loop.run_until_complete(asyncio.gather( map_async(q, coro, iterable), consume(q)))
424f6c8c1c4b65e04196a568cfe56b77265aa063
kobo/apps/external_integrations/models.py
kobo/apps/external_integrations/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ def _set_cors_field_options(name, bases, attrs): cls = type(name, bases, attrs) # The `cors` field is already defined by `AbstractCorsModel`, but let's # help folks out by giving it a more descriptive name and help text, which # will both appear in the admin interface cors_field = cls._meta.get_field('cors') cors_field.verbose_name = _('allowed origin') cors_field.help_text = _('You must include scheme (http:// or https://)') return cls class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match the host with its scheme. e.g. https://example.com """ cors = models.CharField(max_length=255) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
from django.db import models from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( max_length=255, verbose_name=_('allowed origin'), help_text=_( 'Must contain exactly the URI scheme, host, and port, e.g. ' 'https://example.com:1234. Standard ports (80 for http and 443 ' 'for https) may be omitted.' ) ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
Simplify CORS model and improve wording
Simplify CORS model and improve wording
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
from django.db import models from django.utils.translation import ugettext_lazy as _ + class CorsModel(models.Model): - def _set_cors_field_options(name, bases, attrs): - cls = type(name, bases, attrs) - # The `cors` field is already defined by `AbstractCorsModel`, but let's - # help folks out by giving it a more descriptive name and help text, which - # will both appear in the admin interface - cors_field = cls._meta.get_field('cors') - cors_field.verbose_name = _('allowed origin') - cors_field.help_text = _('You must include scheme (http:// or https://)') - return cls - - - class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must - exactly match the host with its scheme. e.g. https://example.com + exactly match `request.META.get('HTTP_ORIGIN')` """ - cors = models.CharField(max_length=255) + cors = models.CharField( + max_length=255, + verbose_name=_('allowed origin'), + help_text=_( + 'Must contain exactly the URI scheme, host, and port, e.g. ' + 'https://example.com:1234. Standard ports (80 for http and 443 ' + 'for https) may be omitted.' + ) + ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
Simplify CORS model and improve wording
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ def _set_cors_field_options(name, bases, attrs): cls = type(name, bases, attrs) # The `cors` field is already defined by `AbstractCorsModel`, but let's # help folks out by giving it a more descriptive name and help text, which # will both appear in the admin interface cors_field = cls._meta.get_field('cors') cors_field.verbose_name = _('allowed origin') cors_field.help_text = _('You must include scheme (http:// or https://)') return cls class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match the host with its scheme. e.g. https://example.com """ cors = models.CharField(max_length=255) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin') ## Instruction: Simplify CORS model and improve wording ## Code After: from django.db import models from django.utils.translation import ugettext_lazy as _ class CorsModel(models.Model): """ A model with one field, `cors`, which specifies an allowed origin that must exactly match `request.META.get('HTTP_ORIGIN')` """ cors = models.CharField( max_length=255, verbose_name=_('allowed origin'), help_text=_( 'Must contain exactly the URI scheme, host, and port, e.g. ' 'https://example.com:1234. Standard ports (80 for http and 443 ' 'for https) may be omitted.' ) ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
from django.db import models from django.utils.translation import ugettext_lazy as _ + class CorsModel(models.Model): - def _set_cors_field_options(name, bases, attrs): - cls = type(name, bases, attrs) - # The `cors` field is already defined by `AbstractCorsModel`, but let's - # help folks out by giving it a more descriptive name and help text, which - # will both appear in the admin interface - cors_field = cls._meta.get_field('cors') - cors_field.verbose_name = _('allowed origin') - cors_field.help_text = _('You must include scheme (http:// or https://)') - return cls - - - class CorsModel(models.Model, metaclass=_set_cors_field_options): """ A model with one field, `cors`, which specifies an allowed origin that must - exactly match the host with its scheme. e.g. https://example.com + exactly match `request.META.get('HTTP_ORIGIN')` """ - cors = models.CharField(max_length=255) ? --------------- + cors = models.CharField( + max_length=255, + verbose_name=_('allowed origin'), + help_text=_( + 'Must contain exactly the URI scheme, host, and port, e.g. ' + 'https://example.com:1234. Standard ports (80 for http and 443 ' + 'for https) may be omitted.' + ) + ) def __str__(self): return self.cors class Meta: verbose_name = _('allowed CORS origin')
cce8c4b40038a8b8ddccc76f7d13c7f5d0e5e566
txircd/modules/rfc/cmd_links.py
txircd/modules/rfc/cmd_links.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand()
Make the order of LINKS output consistent
Make the order of LINKS output consistent
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): + user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) - user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand()
Make the order of LINKS output consistent
## Code Before: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand() ## Instruction: Make the order of LINKS output consistent ## Code After: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class LinksCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "LinksCommand" core = True def userCommands(self): return [ ("LINKS", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): + user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) for server in self.ircd.servers.itervalues(): hopCount = 1 nextServer = server.nextClosest while nextServer != self.ircd.serverID: nextServer = self.ircd.servers[nextServer].nextClosest hopCount += 1 if server.nextClosest == self.ircd.serverID: nextClosestName = self.ircd.name else: nextClosestName = self.ircd.servers[server.nextClosest].name user.sendMessage(irc.RPL_LINKS, server.name, nextClosestName, "{} {}".format(hopCount, server.description)) - user.sendMessage(irc.RPL_LINKS, self.ircd.name, self.ircd.name, "0 {}".format(self.ircd.config["server_description"])) user.sendMessage(irc.RPL_ENDOFLINKS, "*", "End of /LINKS list.") return True linksCmd = LinksCommand()
38efa77f8831b2fcceb5f86f31a1ec7dc6aa5627
src/odometry.py
src/odometry.py
import rospy from nav_msgs.msg import Odometry current_odometry = None def get_odometry(message): global current_odometry current_odometry = message if __name__ == '__main__': rospy.init_node('odometry') subscriber = rospy.Subscriber('odom', Odometry, get_odometry) publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1) while current_odometry == None: pass rate = rospy.Rate(10) while not rospy.is_shutdown(): publisher.publish(current_odometry) rate.sleep()
import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Pose current_pose = None def get_pose(message): global current_pose current_pose = message.pose[0] if __name__ == '__main__': rospy.init_node('pose') subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1) while current_pose == None: pass rate = rospy.Rate(10) while not rospy.is_shutdown(): publisher.publish(current_pose) rate.sleep()
Change subscribed topic and message type
Change subscribed topic and message type
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
import rospy - from nav_msgs.msg import Odometry + from gazebo_msgs.msg import ModelStates + from geometry_msgs.msg import Pose - current_odometry = None + current_pose = None - def get_odometry(message): + def get_pose(message): - global current_odometry + global current_pose + - current_odometry = message + current_pose = message.pose[0] if __name__ == '__main__': - rospy.init_node('odometry') + rospy.init_node('pose') - subscriber = rospy.Subscriber('odom', Odometry, get_odometry) + subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) - publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1) + publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1) - while current_odometry == None: + while current_pose == None: pass rate = rospy.Rate(10) while not rospy.is_shutdown(): - publisher.publish(current_odometry) + publisher.publish(current_pose) rate.sleep()
Change subscribed topic and message type
## Code Before: import rospy from nav_msgs.msg import Odometry current_odometry = None def get_odometry(message): global current_odometry current_odometry = message if __name__ == '__main__': rospy.init_node('odometry') subscriber = rospy.Subscriber('odom', Odometry, get_odometry) publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1) while current_odometry == None: pass rate = rospy.Rate(10) while not rospy.is_shutdown(): publisher.publish(current_odometry) rate.sleep() ## Instruction: Change subscribed topic and message type ## Code After: import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Pose current_pose = None def get_pose(message): global current_pose current_pose = message.pose[0] if __name__ == '__main__': rospy.init_node('pose') subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1) while current_pose == None: pass rate = rospy.Rate(10) while not rospy.is_shutdown(): publisher.publish(current_pose) rate.sleep()
import rospy - from nav_msgs.msg import Odometry + from gazebo_msgs.msg import ModelStates + from geometry_msgs.msg import Pose - current_odometry = None ? ^^^ --- + current_pose = None ? + ^ - def get_odometry(message): ? ^^^ --- + def get_pose(message): ? + ^ - global current_odometry ? ^^^ --- + global current_pose ? + ^ + - current_odometry = message ? ^^^ --- + current_pose = message.pose[0] ? + ^ ++++++++ if __name__ == '__main__': - rospy.init_node('odometry') ? ^^^ --- + rospy.init_node('pose') ? + ^ - subscriber = rospy.Subscriber('odom', Odometry, get_odometry) + subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) - publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1) ? ^^^ --- ^^ ^ --- + publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1) ? + ^ ^ ^ - while current_odometry == None: ? ^^^ --- + while current_pose == None: ? + ^ pass rate = rospy.Rate(10) while not rospy.is_shutdown(): - publisher.publish(current_odometry) ? ^^^ --- + publisher.publish(current_pose) ? + ^ rate.sleep()
c0cc820b933913a3d5967d377f557a26ff21dcf7
tests/test_utils.py
tests/test_utils.py
from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension from pilkit.utils import extension_to_format, format_to_extension, FileWrapper from nose.tools import eq_, raises def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno()
from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper, save_image) from nose.tools import eq_, raises from tempfile import NamedTemporaryFile from .utils import create_image def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno() def test_save_with_filename(): """ Test that ``save_image`` accepts filename strings (not just file objects). This is a test for GH-8. """ im = create_image() outfile = NamedTemporaryFile() save_image(im, outfile.name, 'JPEG') outfile.close()
Test that filename string can be used with save_image
Test that filename string can be used with save_image
Python
bsd-3-clause
kezabelle/pilkit,fladi/pilkit
from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension - from pilkit.utils import extension_to_format, format_to_extension, FileWrapper + from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper, + save_image) from nose.tools import eq_, raises + from tempfile import NamedTemporaryFile + from .utils import create_image def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno() + + def test_save_with_filename(): + """ + Test that ``save_image`` accepts filename strings (not just file objects). + This is a test for GH-8. + + """ + im = create_image() + outfile = NamedTemporaryFile() + save_image(im, outfile.name, 'JPEG') + outfile.close() +
Test that filename string can be used with save_image
## Code Before: from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension from pilkit.utils import extension_to_format, format_to_extension, FileWrapper from nose.tools import eq_, raises def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno() ## Instruction: Test that filename string can be used with save_image ## Code After: from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper, save_image) from nose.tools import eq_, raises from tempfile import NamedTemporaryFile from .utils import create_image def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno() def test_save_with_filename(): """ Test that ``save_image`` accepts filename strings (not just file objects). This is a test for GH-8. """ im = create_image() outfile = NamedTemporaryFile() save_image(im, outfile.name, 'JPEG') outfile.close()
from io import UnsupportedOperation from pilkit.exceptions import UnknownFormat, UnknownExtension - from pilkit.utils import extension_to_format, format_to_extension, FileWrapper + from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper, ? + + + save_image) from nose.tools import eq_, raises + from tempfile import NamedTemporaryFile + from .utils import create_image def test_extension_to_format(): eq_(extension_to_format('.jpeg'), 'JPEG') eq_(extension_to_format('.rgba'), 'SGI') def test_format_to_extension_no_init(): eq_(format_to_extension('PNG'), '.png') eq_(format_to_extension('ICO'), '.ico') @raises(UnknownFormat) def test_unknown_format(): format_to_extension('TXT') @raises(UnknownExtension) def test_unknown_extension(): extension_to_format('.txt') def test_default_extension(): """ Ensure default extensions are honored. Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common JPEG extensions, it would normally be the extension we'd get for that format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which extensions we'd prefer, and this tests to make sure it's working. """ eq_(format_to_extension('JPEG'), '.jpg') @raises(AttributeError) def test_filewrapper(): class K(object): def fileno(self): raise UnsupportedOperation FileWrapper(K()).fileno() + + + def test_save_with_filename(): + """ + Test that ``save_image`` accepts filename strings (not just file objects). + This is a test for GH-8. + + """ + im = create_image() + outfile = NamedTemporaryFile() + save_image(im, outfile.name, 'JPEG') + outfile.close()
b7f2efe79e5a91ab78850842eafc73d1ee0a52cc
shortuuid/__init__.py
shortuuid/__init__.py
from shortuuid.main import ( encode, decode, uuid, get_alphabet, set_alphabet, ShortUUID, )
from shortuuid.main import ( encode, decode, uuid, random, get_alphabet, set_alphabet, ShortUUID, )
Include `random` in imports from shortuuid.main
Include `random` in imports from shortuuid.main When `random` was added to `main.py` the `__init__.py` file wasn't updated to expose it. Currently, to use, you have to do: `import shortuuid; shortuuid.main.random(24)`. With these changes you can do `import shortuuid; shortuuid.random()`. This better mirrors the behavior of `uuid`, etc.
Python
bsd-3-clause
skorokithakis/shortuuid,stochastic-technologies/shortuuid
from shortuuid.main import ( encode, decode, uuid, + random, get_alphabet, set_alphabet, ShortUUID, )
Include `random` in imports from shortuuid.main
## Code Before: from shortuuid.main import ( encode, decode, uuid, get_alphabet, set_alphabet, ShortUUID, ) ## Instruction: Include `random` in imports from shortuuid.main ## Code After: from shortuuid.main import ( encode, decode, uuid, random, get_alphabet, set_alphabet, ShortUUID, )
from shortuuid.main import ( encode, decode, uuid, + random, get_alphabet, set_alphabet, ShortUUID, )
38bf0cba402d3c747584b8aae109c3735d23f6fa
config/settings/__init__.py
config/settings/__init__.py
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
Python
apache-2.0
aipescience/django-daiquiri-app,aipescience/django-daiquiri-app
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL - ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
## Code Before: import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename']) ## Instruction: Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL ## Code After: import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS # prepend the local.BASE_URL to the different URL settings try: LOGIN_URL = BASE_URL + LOGIN_URL LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL LOGOUT_URL = BASE_URL + LOGOUT_URL - ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL MEDIA_URL = BASE_URL + MEDIA_URL STATIC_URL = BASE_URL + STATIC_URL CSRF_COOKIE_PATH = BASE_URL + '/' LANGUAGE_COOKIE_PATH = BASE_URL + '/' SESSION_COOKIE_PATH = BASE_URL + '/' except NameError: pass # prepend the LOGGING_DIR to the filenames in LOGGING for handler in LOGGING['handlers'].values(): if 'filename' in handler: handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
759e6b66ebd601fb1902f6bee2cbc980d61baab8
unitTestUtils/parseXML.py
unitTestUtils/parseXML.py
from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
Add a print with file where mistake is
Add a print with file where mistake is
Python
apache-2.0
alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework
from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") + print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
Add a print with file where mistake is
## Code Before: from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main() ## Instruction: Add a print with file where mistake is ## Code After: from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") + print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
e6d28d55309cdf7c25062d469646e0671e877607
nose2/tests/functional/support/scenario/tests_in_package/pkg1/test/test_things.py
nose2/tests/functional/support/scenario/tests_in_package/pkg1/test/test_things.py
import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup
import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") def test_gen_method(self): def check(x): assert x == 1 yield check, 1 yield check, 2 def test_params_method(self, a): self.assertEqual(a, 1) test_params_method.paramList = (1, 2) def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup def test_params_func(a): assert a == 1 test_params_func.paramList = (1, 2) def test_params_func_multi_arg(a, b): assert a == b test_params_func_multi_arg.paramList = ((1, 1), (1, 2), (2, 2))
Add param test cases to func test target project
Add param test cases to func test target project
Python
bsd-2-clause
ojengwa/nose2,ezigman/nose2,ezigman/nose2,leth/nose2,leth/nose2,little-dude/nose2,ptthiem/nose2,ptthiem/nose2,little-dude/nose2,ojengwa/nose2
import unittest + class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") + + def test_gen_method(self): + def check(x): + assert x == 1 + yield check, 1 + yield check, 2 + + def test_params_method(self, a): + self.assertEqual(a, 1) + test_params_method.paramList = (1, 2) def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup + def test_params_func(a): + assert a == 1 + test_params_func.paramList = (1, 2) + + + def test_params_func_multi_arg(a, b): + assert a == b + test_params_func_multi_arg.paramList = ((1, 1), (1, 2), (2, 2)) +
Add param test cases to func test target project
## Code Before: import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup ## Instruction: Add param test cases to func test target project ## Code After: import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") def test_gen_method(self): def check(x): assert x == 1 yield check, 1 yield check, 2 def test_params_method(self, a): self.assertEqual(a, 1) test_params_method.paramList = (1, 2) def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup def test_params_func(a): assert a == 1 test_params_func.paramList = (1, 2) def test_params_func_multi_arg(a, b): assert a == b test_params_func_multi_arg.paramList = ((1, 1), (1, 2), (2, 2))
import unittest + class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip") + + def test_gen_method(self): + def check(x): + assert x == 1 + yield check, 1 + yield check, 2 + + def test_params_method(self, a): + self.assertEqual(a, 1) + test_params_method.paramList = (1, 2) def test_func(): assert 1 == 1 def test_gen(): def check(a, b): assert a == b for i in range(0, 5): yield check, (i, i,) test_gen.testGenerator = True def test_gen_nose_style(): def check(a, b): assert a == b for i in range(0, 5): yield check, i, i did_setup = False def setup(): global did_setup did_setup = True def test_fixt(): assert did_setup test_fixt.setup = setup + + def test_params_func(a): + assert a == 1 + test_params_func.paramList = (1, 2) + + + def test_params_func_multi_arg(a, b): + assert a == b + test_params_func_multi_arg.paramList = ((1, 1), (1, 2), (2, 2))
2d57d87b15c73fe1f9b884dc57ecf2c25a5e7454
tensorflow_probability/python/internal/backend/numpy/tensor_spec.py
tensorflow_probability/python/internal/backend/numpy/tensor_spec.py
"""Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass
"""Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend.
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774
Python
apache-2.0
tensorflow/probability,tensorflow/probability
"""Numpy stub for `tensor_spec`.""" + + from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): - pass + @classmethod + def from_tensor(cls, tensor, name=None): + tensor = _convert_to_tensor(tensor) + return cls(tensor.shape, tensor.dtype, name) +
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend.
## Code Before: """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass ## Instruction: Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. ## Code After: """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
"""Numpy stub for `tensor_spec`.""" + + from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): - pass + + @classmethod + def from_tensor(cls, tensor, name=None): + tensor = _convert_to_tensor(tensor) + return cls(tensor.shape, tensor.dtype, name)
e679b7d45cd4fd552b1fe54b61b914f23aca2c94
backdrop/__init__.py
backdrop/__init__.py
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX")))
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv( "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
Add a prefix to the statsd key
Add a prefix to the statsd key We have loads of stats at the top leve of our statsd stats in graphite. It makes looking for things that aren't created by backdrop really hard.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( - _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX"))) + _statsd.StatsClient(prefix=os.getenv( + "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
Add a prefix to the statsd key
## Code Before: import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX"))) ## Instruction: Add a prefix to the statsd key ## Code After: import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv( "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( - _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX"))) ? ------------------------ + _statsd.StatsClient(prefix=os.getenv( + "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
4511fef9b2c6521197dc64963c58c1a77e3475b3
counterid.py
counterid.py
"""counterid - Simple utility to discover perfmon counter paths""" # Compile to EXE using c:\Python27\scripts\pyinstaller.exe -F counterid.py __author__ = '[email protected] (Scott Vintinner)' import win32pdh # Will display a window with available counters. Click add to print out counter name. def print_counter(counter): print counter win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List")
"""counterid - Simple utility to discover perfmon counter paths""" # pip install pyinstaller # Compile to EXE using pyinstaller.exe -F counterid.py __author__ = '[email protected] (Scott Vintinner)' import win32pdh # Will display a window with available counters. Click add to print out counter name. def print_counter(counter): print(counter) win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List")
Update to make compatible with Python 3
Update to make compatible with Python 3
Python
mit
flakshack/pyPerfmon
- """counterid - Simple utility to discover perfmon counter paths""" + """counterid - Simple utility to discover perfmon counter paths""" + # pip install pyinstaller - # Compile to EXE using c:\Python27\scripts\pyinstaller.exe -F counterid.py + # Compile to EXE using pyinstaller.exe -F counterid.py - + - __author__ = '[email protected] (Scott Vintinner)' + __author__ = '[email protected] (Scott Vintinner)' - import win32pdh + import win32pdh - - + + - # Will display a window with available counters. Click add to print out counter name. + # Will display a window with available counters. Click add to print out counter name. - def print_counter(counter): + def print_counter(counter): - print counter + print(counter) - + + win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List")
Update to make compatible with Python 3
## Code Before: """counterid - Simple utility to discover perfmon counter paths""" # Compile to EXE using c:\Python27\scripts\pyinstaller.exe -F counterid.py __author__ = '[email protected] (Scott Vintinner)' import win32pdh # Will display a window with available counters. Click add to print out counter name. def print_counter(counter): print counter win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List") ## Instruction: Update to make compatible with Python 3 ## Code After: """counterid - Simple utility to discover perfmon counter paths""" # pip install pyinstaller # Compile to EXE using pyinstaller.exe -F counterid.py __author__ = '[email protected] (Scott Vintinner)' import win32pdh # Will display a window with available counters. Click add to print out counter name. def print_counter(counter): print(counter) win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List")
"""counterid - Simple utility to discover perfmon counter paths""" + # pip install pyinstaller - # Compile to EXE using c:\Python27\scripts\pyinstaller.exe -F counterid.py ? -------------------- + # Compile to EXE using pyinstaller.exe -F counterid.py __author__ = '[email protected] (Scott Vintinner)' import win32pdh # Will display a window with available counters. Click add to print out counter name. def print_counter(counter): - print counter ? ^ + print(counter) ? ^ + + win32pdh.BrowseCounters(None, 0, print_counter, win32pdh.PERF_DETAIL_WIZARD, "Counter List")
118eabf049db8804635001b2348fcb81c8a2a4f4
openstack_dashboard/dashboards/admin/routers/ports/tables.py
openstack_dashboard/dashboards/admin/routers/ports/tables.py
from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.project.networks.ports \ import tables as networks_tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables DISPLAY_CHOICES = ( ("UP", pgettext_lazy("Admin state of a Network", u"UP")), ("DOWN", pgettext_lazy("Admin state of a Network", u"DOWN")), ) class PortsTable(tables.DataTable): name = tables.Column("name", verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") fixed_ips = tables.Column(networks_tables.get_fixed_ips, verbose_name=_("Fixed IPs")) status = tables.Column("status", verbose_name=_("Status")) device_owner = tables.Column(routers_tables.get_device_owner, verbose_name=_("Type")) admin_state = tables.Column("admin_state", verbose_name=_("Admin State"), display_choices=DISPLAY_CHOICES) def get_object_display(self, port): return port.id class Meta(object): name = "interfaces" verbose_name = _("Interfaces")
from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables class PortsTable(routers_tables.PortsTable): name = tables.Column("name_or_id", verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") class Meta(object): name = "interfaces" verbose_name = _("Interfaces")
Fix router details's name empty and change inheritance project table
Fix router details's name empty and change inheritance project table In admin router details page, the name column is empty, change to if no name show id. And change to inheritance from port table of project. Change-Id: I54d4ad95bd04db2432eb47f848917a452c5f54e9 Closes-bug:#1417948
Python
apache-2.0
j4/horizon,yeming233/horizon,henaras/horizon,yeming233/horizon,damien-dg/horizon,tqtran7/horizon,BiznetGIO/horizon,Hodorable/0602,tqtran7/horizon,RudoCris/horizon,dan1/horizon-x509,agileblaze/OpenStackTwoFactorAuthentication,kfox1111/horizon,maestro-hybrid-cloud/horizon,NeCTAR-RC/horizon,redhat-openstack/horizon,Tesora/tesora-horizon,vladryk/horizon,agileblaze/OpenStackTwoFactorAuthentication,yjxtogo/horizon,NCI-Cloud/horizon,wolverineav/horizon,Solinea/horizon,ChameleonCloud/horizon,saydulk/horizon,bac/horizon,mdavid/horizon,damien-dg/horizon,tellesnobrega/horizon,tqtran7/horizon,redhat-openstack/horizon,ChameleonCloud/horizon,openstack/horizon,Tesora/tesora-horizon,Metaswitch/horizon,icloudrnd/automation_tools,BiznetGIO/horizon,django-leonardo/horizon,tellesnobrega/horizon,luhanhan/horizon,dan1/horizon-proto,Tesora/tesora-horizon,mandeepdhami/horizon,tellesnobrega/horizon,yeming233/horizon,blueboxgroup/horizon,RudoCris/horizon,icloudrnd/automation_tools,mandeepdhami/horizon,Solinea/horizon,newrocknj/horizon,sandvine/horizon,endorphinl/horizon-fork,Mirantis/mos-horizon,Metaswitch/horizon,VaneCloud/horizon,FNST-OpenStack/horizon,liyitest/rr,pranavtendolkr/horizon,philoniare/horizon,coreycb/horizon,mandeepdhami/horizon,icloudrnd/automation_tools,henaras/horizon,redhat-cip/horizon,CiscoSystems/horizon,kfox1111/horizon,dan1/horizon-x509,Mirantis/mos-horizon,Mirantis/mos-horizon,Tesora/tesora-horizon,yeming233/horizon,promptworks/horizon,yjxtogo/horizon,xinwu/horizon,newrocknj/horizon,BiznetGIO/horizon,promptworks/horizon,pranavtendolkr/horizon,newrocknj/horizon,NeCTAR-RC/horizon,pranavtendolkr/horizon,CiscoSystems/horizon,vladryk/horizon,philoniare/horizon,anthonydillon/horizon,luhanhan/horizon,luhanhan/horizon,xinwu/horizon,sandvine/horizon,eayunstack/horizon,xinwu/horizon,bac/horizon,dan1/horizon-proto,j4/horizon,eayunstack/horizon,izadorozhna/dashboard_integration_tests,newrocknj/horizon,henaras/horizon,philoniare/horizon,anthonydillon/horizon,Metaswitch/horizon,mdavid/horizon,kfox1111/horizon,blueboxgroup/horizon,icloudrnd/automation_tools,gerrive/horizon,tqtran7/horizon,j4/horizon,django-leonardo/horizon,redhat-cip/horizon,endorphinl/horizon,noironetworks/horizon,dan1/horizon-x509,tellesnobrega/horizon,agileblaze/OpenStackTwoFactorAuthentication,endorphinl/horizon-fork,Dark-Hacker/horizon,ChameleonCloud/horizon,takeshineshiro/horizon,coreycb/horizon,mdavid/horizon,anthonydillon/horizon,Dark-Hacker/horizon,NCI-Cloud/horizon,karthik-suresh/horizon,luhanhan/horizon,blueboxgroup/horizon,philoniare/horizon,Daniex/horizon,endorphinl/horizon,RudoCris/horizon,bigswitch/horizon,redhat-cip/horizon,FNST-OpenStack/horizon,openstack/horizon,endorphinl/horizon-fork,noironetworks/horizon,CiscoSystems/horizon,noironetworks/horizon,saydulk/horizon,wangxiangyu/horizon,openstack/horizon,NeCTAR-RC/horizon,davidcusatis/horizon,NCI-Cloud/horizon,wolverineav/horizon,wolverineav/horizon,redhat-openstack/horizon,doug-fish/horizon,gerrive/horizon,liyitest/rr,bac/horizon,wangxiangyu/horizon,endorphinl/horizon,yjxtogo/horizon,wolverineav/horizon,agileblaze/OpenStackTwoFactorAuthentication,endorphinl/horizon,FNST-OpenStack/horizon,takeshineshiro/horizon,BiznetGIO/horizon,mdavid/horizon,dan1/horizon-proto,takeshineshiro/horizon,henaras/horizon,xinwu/horizon,saydulk/horizon,maestro-hybrid-cloud/horizon,j4/horizon,davidcusatis/horizon,bigswitch/horizon,coreycb/horizon,karthik-suresh/horizon,wangxiangyu/horizon,VaneCloud/horizon,watonyweng/horizon,vladryk/horizon,promptworks/horizon,mandeepdhami/horizon,maestro-hybrid-cloud/horizon,idjaw/horizon,dan1/horizon-proto,endorphinl/horizon-fork,NeCTAR-RC/horizon,davidcusatis/horizon,Daniex/horizon,Mirantis/mos-horizon,saydulk/horizon,RudoCris/horizon,django-leonardo/horizon,gerrive/horizon,Daniex/horizon,izadorozhna/dashboard_integration_tests,liyitest/rr,yjxtogo/horizon,idjaw/horizon,FNST-OpenStack/horizon,karthik-suresh/horizon,bigswitch/horizon,idjaw/horizon,Solinea/horizon,damien-dg/horizon,VaneCloud/horizon,maestro-hybrid-cloud/horizon,sandvine/horizon,eayunstack/horizon,karthik-suresh/horizon,coreycb/horizon,vladryk/horizon,Hodorable/0602,CiscoSystems/horizon,ChameleonCloud/horizon,gerrive/horizon,openstack/horizon,dan1/horizon-x509,Metaswitch/horizon,Dark-Hacker/horizon,redhat-openstack/horizon,django-leonardo/horizon,liyitest/rr,Solinea/horizon,wangxiangyu/horizon,Hodorable/0602,damien-dg/horizon,bigswitch/horizon,VaneCloud/horizon,idjaw/horizon,watonyweng/horizon,sandvine/horizon,promptworks/horizon,doug-fish/horizon,pranavtendolkr/horizon,bac/horizon,Hodorable/0602,doug-fish/horizon,doug-fish/horizon,blueboxgroup/horizon,watonyweng/horizon,watonyweng/horizon,takeshineshiro/horizon,noironetworks/horizon,Dark-Hacker/horizon,anthonydillon/horizon,Daniex/horizon,davidcusatis/horizon,kfox1111/horizon,NCI-Cloud/horizon,redhat-cip/horizon
- from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from horizon import tables - from openstack_dashboard.dashboards.project.networks.ports \ - import tables as networks_tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables - DISPLAY_CHOICES = ( - ("UP", pgettext_lazy("Admin state of a Network", u"UP")), - ("DOWN", pgettext_lazy("Admin state of a Network", u"DOWN")), - ) - - - class PortsTable(tables.DataTable): + class PortsTable(routers_tables.PortsTable): - name = tables.Column("name", + name = tables.Column("name_or_id", verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") - fixed_ips = tables.Column(networks_tables.get_fixed_ips, - verbose_name=_("Fixed IPs")) - status = tables.Column("status", verbose_name=_("Status")) - device_owner = tables.Column(routers_tables.get_device_owner, - verbose_name=_("Type")) - admin_state = tables.Column("admin_state", - verbose_name=_("Admin State"), - display_choices=DISPLAY_CHOICES) - - def get_object_display(self, port): - return port.id class Meta(object): name = "interfaces" verbose_name = _("Interfaces")
Fix router details's name empty and change inheritance project table
## Code Before: from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.project.networks.ports \ import tables as networks_tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables DISPLAY_CHOICES = ( ("UP", pgettext_lazy("Admin state of a Network", u"UP")), ("DOWN", pgettext_lazy("Admin state of a Network", u"DOWN")), ) class PortsTable(tables.DataTable): name = tables.Column("name", verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") fixed_ips = tables.Column(networks_tables.get_fixed_ips, verbose_name=_("Fixed IPs")) status = tables.Column("status", verbose_name=_("Status")) device_owner = tables.Column(routers_tables.get_device_owner, verbose_name=_("Type")) admin_state = tables.Column("admin_state", verbose_name=_("Admin State"), display_choices=DISPLAY_CHOICES) def get_object_display(self, port): return port.id class Meta(object): name = "interfaces" verbose_name = _("Interfaces") ## Instruction: Fix router details's name empty and change inheritance project table ## Code After: from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables class PortsTable(routers_tables.PortsTable): name = tables.Column("name_or_id", verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") class Meta(object): name = "interfaces" verbose_name = _("Interfaces")
- from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from horizon import tables - from openstack_dashboard.dashboards.project.networks.ports \ - import tables as networks_tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables - DISPLAY_CHOICES = ( - ("UP", pgettext_lazy("Admin state of a Network", u"UP")), - ("DOWN", pgettext_lazy("Admin state of a Network", u"DOWN")), - ) - - - class PortsTable(tables.DataTable): ? ^^ ^ + class PortsTable(routers_tables.PortsTable): ? ++++++++ ^^^ ^ - name = tables.Column("name", + name = tables.Column("name_or_id", ? ++++++ verbose_name=_("Name"), link="horizon:admin:networks:ports:detail") - fixed_ips = tables.Column(networks_tables.get_fixed_ips, - verbose_name=_("Fixed IPs")) - status = tables.Column("status", verbose_name=_("Status")) - device_owner = tables.Column(routers_tables.get_device_owner, - verbose_name=_("Type")) - admin_state = tables.Column("admin_state", - verbose_name=_("Admin State"), - display_choices=DISPLAY_CHOICES) - - def get_object_display(self, port): - return port.id class Meta(object): name = "interfaces" verbose_name = _("Interfaces")
62f4c6b7d24176284054b13c4e1e9b6d631c7b42
basicTest.py
basicTest.py
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither continueLoop = True while continueLoop: slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) # Handle quitting for event in pygame.event.get(): if event.type == pygame.QUIT: continueLoop = False time.sleep(0.01)
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither def run_a_frame(): snakey.changeXBy(1) SoExcited.changeDirectionBy(1) slither.runMainLoop(run_a_frame)
Update basic test Now uses the new format by @BookOwl.
Update basic test Now uses the new format by @BookOwl.
Python
mit
PySlither/Slither,PySlither/Slither
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither + def run_a_frame(): - continueLoop = True - while continueLoop: - slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) - # Handle quitting - for event in pygame.event.get(): - if event.type == pygame.QUIT: - continueLoop = False - time.sleep(0.01) + slither.runMainLoop(run_a_frame) +
Update basic test Now uses the new format by @BookOwl.
## Code Before: import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither continueLoop = True while continueLoop: slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) # Handle quitting for event in pygame.event.get(): if event.type == pygame.QUIT: continueLoop = False time.sleep(0.01) ## Instruction: Update basic test Now uses the new format by @BookOwl. ## Code After: import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither def run_a_frame(): snakey.changeXBy(1) SoExcited.changeDirectionBy(1) slither.runMainLoop(run_a_frame)
import slither, pygame, time snakey = slither.Sprite() snakey.setCostumeByName("costume0") SoExcited = slither.Sprite() SoExcited.addCostume("SoExcited.png", "avatar") SoExcited.setCostumeByNumber(0) SoExcited.goTo(300, 300) SoExcited.setScaleTo(0.33) slither.slitherStage.setColor(40, 222, 40) screen = slither.setup() # Begin slither + def run_a_frame(): - continueLoop = True - while continueLoop: - slither.blit(screen) # Display snakey.changeXBy(1) SoExcited.changeDirectionBy(1) + + slither.runMainLoop(run_a_frame) - # Handle quitting - for event in pygame.event.get(): - if event.type == pygame.QUIT: - continueLoop = False - time.sleep(0.01)
ea1c095fb12c4062616ee0d38818ab1baaabd1eb
ipywidgets/widgets/tests/test_widget_upload.py
ipywidgets/widgets/tests/test_widget_upload.py
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == []
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] def test_receive_single_file(self): uploader = FileUpload() content = memoryview(b"file content") message = { "value": [ { "name": "file-name.txt", "type": "text/plain", "size": 20760, "lastModified": 1578578296434, "error": "", "content": content, } ] } uploader.set_state(message) assert len(uploader.value) == 1 [uploaded_file] = uploader.value assert uploaded_file.name == "file-name.txt" assert uploaded_file.type == "text/plain" assert uploaded_file.size == 20760 assert uploaded_file.content.tobytes() == b"file content"
Test deserialization of comm message following upload
Test deserialization of comm message following upload
Python
bsd-3-clause
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] + def test_receive_single_file(self): + uploader = FileUpload() + content = memoryview(b"file content") + message = { + "value": [ + { + "name": "file-name.txt", + "type": "text/plain", + "size": 20760, + "lastModified": 1578578296434, + "error": "", + "content": content, + } + ] + } + uploader.set_state(message) + assert len(uploader.value) == 1 + [uploaded_file] = uploader.value + assert uploaded_file.name == "file-name.txt" + assert uploaded_file.type == "text/plain" + assert uploaded_file.size == 20760 + assert uploaded_file.content.tobytes() == b"file content" +
Test deserialization of comm message following upload
## Code Before: from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] ## Instruction: Test deserialization of comm message following upload ## Code After: from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] def test_receive_single_file(self): uploader = FileUpload() content = memoryview(b"file content") message = { "value": [ { "name": "file-name.txt", "type": "text/plain", "size": 20760, "lastModified": 1578578296434, "error": "", "content": content, } ] } uploader.set_state(message) assert len(uploader.value) == 1 [uploaded_file] = uploader.value assert uploaded_file.name == "file-name.txt" assert uploaded_file.type == "text/plain" assert uploaded_file.size == 20760 assert uploaded_file.content.tobytes() == b"file content"
from unittest import TestCase from traitlets import TraitError from ipywidgets import FileUpload class TestFileUpload(TestCase): def test_construction(self): uploader = FileUpload() # Default assert uploader.accept == '' assert not uploader.multiple assert not uploader.disabled def test_construction_with_params(self): uploader = FileUpload( accept='.txt', multiple=True, disabled=True) assert uploader.accept == '.txt' assert uploader.multiple assert uploader.disabled def test_empty_initial_value(self): uploader = FileUpload() assert uploader.value == [] + + def test_receive_single_file(self): + uploader = FileUpload() + content = memoryview(b"file content") + message = { + "value": [ + { + "name": "file-name.txt", + "type": "text/plain", + "size": 20760, + "lastModified": 1578578296434, + "error": "", + "content": content, + } + ] + } + uploader.set_state(message) + assert len(uploader.value) == 1 + [uploaded_file] = uploader.value + assert uploaded_file.name == "file-name.txt" + assert uploaded_file.type == "text/plain" + assert uploaded_file.size == 20760 + assert uploaded_file.content.tobytes() == b"file content"
1aec583a52ac9edc95138f5df356da60451dfe2b
enthought/tvtk/view/parametric_function_source_view.py
enthought/tvtk/view/parametric_function_source_view.py
from enthought.traits.ui.api import View, HGroup, Item view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel'])
from enthought.traits.ui.api import View, HGroup, Item from enthought.tvtk.tvtk_base import TVTKBaseHandler view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), Item('handler.advanced_view'), handler = TVTKBaseHandler, title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel'])
Add handler to the view.
Add handler to the view.
Python
bsd-3-clause
liulion/mayavi,liulion/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,dmsurti/mayavi,alexandreleroux/mayavi
from enthought.traits.ui.api import View, HGroup, Item + from enthought.tvtk.tvtk_base import TVTKBaseHandler view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), + Item('handler.advanced_view'), + handler = TVTKBaseHandler, title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel'])
Add handler to the view.
## Code Before: from enthought.traits.ui.api import View, HGroup, Item view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel']) ## Instruction: Add handler to the view. ## Code After: from enthought.traits.ui.api import View, HGroup, Item from enthought.tvtk.tvtk_base import TVTKBaseHandler view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), Item('handler.advanced_view'), handler = TVTKBaseHandler, title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel'])
from enthought.traits.ui.api import View, HGroup, Item + from enthought.tvtk.tvtk_base import TVTKBaseHandler view = View((['generate_texture_coordinates'], ['scalar_mode'], HGroup(Item('u_resolution', label = 'u'), Item('v_resolution', label = 'v'), Item('w_resolution', label = 'w'), label = 'Resolution', show_border = True)), + Item('handler.advanced_view'), + handler = TVTKBaseHandler, title='Edit ParametricFunctionSource properties', scrollable=True, buttons=['OK', 'Cancel'])
6664f77b8193343fe840b2542a84cc2bf585108a
check_version.py
check_version.py
import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) if changes_version != setup_version: print('Version numbers differ') print('CHANGES.txt states: v' + changes_version) print('setup.py states: v' + setup_version) exit(1)
import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) sphinx_file = open('sphinx/conf.py', 'r') sphinx_content = sphinx_file.read() sphinx_version = re.search(r'version = \'(\d\.\d)\'', sphinx_content).group(1) sphinx_release = re.search(r'release = \'(\d\.\d\.\d)\'', sphinx_content).group(1) if changes_version != setup_version or changes_version != sphinx_release: print('Version numbers differ:') print('CHANGES.txt states: v' + changes_version) print('setup.py states: v' + setup_version) print('sphinx/conf.py states: v' + sphinx_release) exit(1) if not sphinx_release.startswith(sphinx_version): print('Sphinx version configuration differs:') print('Sphinx version: ' + sphinx_version) print('Sphinx release: ' + sphinx_release) exit(1)
Update release version checking to include documentation
Update release version checking to include documentation
Python
unlicense
mmurdoch/Vengeance,mmurdoch/Vengeance
import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() - changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) + changes_version = re.match(r'v(\d\.\d\.\d).*', + changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() - setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) + setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', + setup_content).group(1) - if changes_version != setup_version: + sphinx_file = open('sphinx/conf.py', 'r') + sphinx_content = sphinx_file.read() + sphinx_version = re.search(r'version = \'(\d\.\d)\'', + sphinx_content).group(1) + sphinx_release = re.search(r'release = \'(\d\.\d\.\d)\'', + sphinx_content).group(1) + + if changes_version != setup_version or changes_version != sphinx_release: - print('Version numbers differ') + print('Version numbers differ:') - print('CHANGES.txt states: v' + changes_version) + print('CHANGES.txt states: v' + changes_version) - print('setup.py states: v' + setup_version) + print('setup.py states: v' + setup_version) + print('sphinx/conf.py states: v' + sphinx_release) exit(1) + + if not sphinx_release.startswith(sphinx_version): + print('Sphinx version configuration differs:') + print('Sphinx version: ' + sphinx_version) + print('Sphinx release: ' + sphinx_release) + exit(1)
Update release version checking to include documentation
## Code Before: import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) if changes_version != setup_version: print('Version numbers differ') print('CHANGES.txt states: v' + changes_version) print('setup.py states: v' + setup_version) exit(1) ## Instruction: Update release version checking to include documentation ## Code After: import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) sphinx_file = open('sphinx/conf.py', 'r') sphinx_content = sphinx_file.read() sphinx_version = re.search(r'version = \'(\d\.\d)\'', sphinx_content).group(1) sphinx_release = re.search(r'release = \'(\d\.\d\.\d)\'', sphinx_content).group(1) if changes_version != setup_version or changes_version != sphinx_release: print('Version numbers differ:') print('CHANGES.txt states: v' + changes_version) print('setup.py states: v' + setup_version) print('sphinx/conf.py states: v' + sphinx_release) exit(1) if not sphinx_release.startswith(sphinx_version): print('Sphinx version configuration differs:') print('Sphinx version: ' + sphinx_version) print('Sphinx release: ' + sphinx_release) exit(1)
import re import sys changes_file = open('CHANGES.txt', 'r') changes_first_line = changes_file.readline() - changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1) ? ----------------------------- + changes_version = re.match(r'v(\d\.\d\.\d).*', + changes_first_line).group(1) setup_file = open('setup.py', 'r') setup_content = setup_file.read() - setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_content).group(1) ? ------------------------ + setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', + setup_content).group(1) - if changes_version != setup_version: + sphinx_file = open('sphinx/conf.py', 'r') + sphinx_content = sphinx_file.read() + sphinx_version = re.search(r'version = \'(\d\.\d)\'', + sphinx_content).group(1) + sphinx_release = re.search(r'release = \'(\d\.\d\.\d)\'', + sphinx_content).group(1) + + if changes_version != setup_version or changes_version != sphinx_release: - print('Version numbers differ') + print('Version numbers differ:') ? + - print('CHANGES.txt states: v' + changes_version) + print('CHANGES.txt states: v' + changes_version) ? +++ - print('setup.py states: v' + setup_version) + print('setup.py states: v' + setup_version) ? +++ + print('sphinx/conf.py states: v' + sphinx_release) exit(1) + + if not sphinx_release.startswith(sphinx_version): + print('Sphinx version configuration differs:') + print('Sphinx version: ' + sphinx_version) + print('Sphinx release: ' + sphinx_release) + exit(1)
8930337ef2402a9e5a6dfe3a336fc24b0ffbf87f
reviewboard/accounts/urls.py
reviewboard/accounts/urls.py
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Fix internal server error at url /account/recover
Fix internal server error at url /account/recover Fixed a 500 error at /account/recover when trying to reset password on the login page. Testing Done: Verified that the server no longer returns a 500 error when loading the form. Reviewed at https://reviews.reviewboard.org/r/5431/
Python
mit
beol/reviewboard,davidt/reviewboard,beol/reviewboard,1tush/reviewboard,custode/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,KnowNo/reviewboard,1tush/reviewboard,beol/reviewboard,1tush/reviewboard,beol/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,chipx86/reviewboard,chipx86/reviewboard,1tush/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,chipx86/reviewboard,davidt/reviewboard,KnowNo/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,1tush/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,1tush/reviewboard,1tush/reviewboard,sgallagher/reviewboard
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', - {'template_name': 'accounts/password_reset_done.html'}), + {'template_name': 'accounts/password_reset_done.html'}, + name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
Fix internal server error at url /account/recover
## Code Before: from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), ) ## Instruction: Fix internal server error at url /account/recover ## Code After: from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', {'template_name': 'accounts/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( "reviewboard.accounts.views", url(r'^register/$', 'account_register', {'next_url': 'dashboard'}, name="register"), url(r'^preferences/$', 'user_preferences', name="user-preferences"), ) urlpatterns += patterns( "django.contrib.auth.views", url(r'^login/$', 'login', {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$', 'logout_then_login', name='logout'), url(r'^recover/$', 'password_reset', { 'template_name': 'accounts/password_reset.html', 'email_template_name': 'accounts/password_reset_email.txt' }, name='recover'), url(r'^recover/done/$', 'password_reset_done', - {'template_name': 'accounts/password_reset_done.html'}), ? - + {'template_name': 'accounts/password_reset_done.html'}, + name='password_reset_done'), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'password_reset_confirm', {'template_name': 'accounts/password_reset_confirm.html'}, name='password-reset-confirm'), url(r'^reset/done/$', 'password_reset_complete', {'template_name': 'accounts/password_reset_complete.html'}), )
359040acc4b8c54db84e154b15cabfb23b4e18a6
src/aiy/vision/models/utils.py
src/aiy/vision/models/utils.py
"""Utility to load compute graphs from diffrent sources.""" import os def load_compute_graph(name): path = os.path.join('/opt/aiy/models', name) with open(path, 'rb') as f: return f.read()
"""Utility to load compute graphs from diffrent sources.""" import os def load_compute_graph(name): path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models') with open(os.path.join(path, name), 'rb') as f: return f.read()
Use VISION_BONNET_MODELS_PATH env var for custom models path.
Use VISION_BONNET_MODELS_PATH env var for custom models path. Change-Id: I687ca96e4cf768617fa45d50d68dadffde750b87
Python
apache-2.0
google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian
"""Utility to load compute graphs from diffrent sources.""" import os + def load_compute_graph(name): - path = os.path.join('/opt/aiy/models', name) - with open(path, 'rb') as f: + path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models') + with open(os.path.join(path, name), 'rb') as f: return f.read() -
Use VISION_BONNET_MODELS_PATH env var for custom models path.
## Code Before: """Utility to load compute graphs from diffrent sources.""" import os def load_compute_graph(name): path = os.path.join('/opt/aiy/models', name) with open(path, 'rb') as f: return f.read() ## Instruction: Use VISION_BONNET_MODELS_PATH env var for custom models path. ## Code After: """Utility to load compute graphs from diffrent sources.""" import os def load_compute_graph(name): path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models') with open(os.path.join(path, name), 'rb') as f: return f.read()
"""Utility to load compute graphs from diffrent sources.""" import os + def load_compute_graph(name): - path = os.path.join('/opt/aiy/models', name) - with open(path, 'rb') as f: + path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models') + with open(os.path.join(path, name), 'rb') as f: return f.read() -
a06e6cc3c0b0440d3adedd1ccce78309d8fae9a9
feincms/module/page/extensions/navigationgroups.py
feincms/module/page/extensions/navigationgroups.py
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
Allow navigationgroup to be blank
Allow navigationgroup to be blank
Python
bsd-3-clause
joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,mjl/feincms,mjl/feincms
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, + blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
Allow navigationgroup to be blank
## Code Before: from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group']) ## Instruction: Allow navigationgroup to be blank ## Code After: from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, + blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
64f2720507067d10f298aa50245fa3b7b57a5bd4
dabuildsys/srcname.py
dabuildsys/srcname.py
from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" if len(spec) > 1 or not spec[0].startswith('all'): return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos
from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" if len(spec) == 1 and spec[0] == '*': checkouts = [] for pkg in config.package_map: try: checkouts.append(checkout.PackageCheckout(pkg)) except Exception as e: pass return checkouts, {} elif len(spec) > 1 or not spec[0].startswith('all'): return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos
Implement '*' package for all packages in Git
Implement '*' package for all packages in Git
Python
mit
mit-athena/build-system
from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" + if len(spec) == 1 and spec[0] == '*': + checkouts = [] + for pkg in config.package_map: + try: + checkouts.append(checkout.PackageCheckout(pkg)) + except Exception as e: + pass + return checkouts, {} - if len(spec) > 1 or not spec[0].startswith('all'): + elif len(spec) > 1 or not spec[0].startswith('all'): return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos
Implement '*' package for all packages in Git
## Code Before: from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" if len(spec) > 1 or not spec[0].startswith('all'): return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos ## Instruction: Implement '*' package for all packages in Git ## Code After: from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" if len(spec) == 1 and spec[0] == '*': checkouts = [] for pkg in config.package_map: try: checkouts.append(checkout.PackageCheckout(pkg)) except Exception as e: pass return checkouts, {} elif len(spec) > 1 or not spec[0].startswith('all'): return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos
from common import BuildError import apt import config import checkout def expand_srcname_spec(spec): """Parse a list of source packages on which the operation is to be performed. If some variant of 'all' is specified, comparison against packages currently APT repository is made and packages which have older version in APT than in Git are returned.""" + if len(spec) == 1 and spec[0] == '*': + checkouts = [] + for pkg in config.package_map: + try: + checkouts.append(checkout.PackageCheckout(pkg)) + except Exception as e: + pass + return checkouts, {} - if len(spec) > 1 or not spec[0].startswith('all'): + elif len(spec) > 1 or not spec[0].startswith('all'): ? ++ return [checkout.PackageCheckout(pkg) for pkg in spec], {} else: if spec[0] == 'all': releases = config.releases elif spec[0].startswith('all:'): releases = [spec[0].split(':')[1]] else: raise BuildError("Invalid all-package qualifier specified") cache = {} packages = set() repos = {} for release in releases: _, _, apt_repo = apt.get_release(release) repos[release] = apt_repo comparison = apt.compare_against_git(apt_repo, checkout_cache=cache) packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver) return [cache[pkg] for pkg in packages], repos
52c8b8d2676024ff07722115c815ecdd04dd000c
etrago/cluster/analyses/config.py
etrago/cluster/analyses/config.py
from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
Set path automatically to home of user
Set path automatically to home of user
Python
agpl-3.0
openego/eTraGo
from os import path - root_path = '/home/openego/pf_results/' \ + + root_path = path.join(path.expanduser('~'),'pf_results/' \ - 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' + 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
Set path automatically to home of user
## Code Before: from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path ## Instruction: Set path automatically to home of user ## Code After: from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
from os import path - root_path = '/home/openego/pf_results/' \ + + root_path = path.join(path.expanduser('~'),'pf_results/' \ - 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' ? ------------------- + 'snapshot-clustering-results-k10-cyclic/') ? + clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
74bfe9bf1501d5c31e2ab6d8dc174467e47e200e
app/dao/magazines_dao.py
app/dao/magazines_dao.py
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
Add get magazine by id to magazine dao
Add get magazine by id to magazine dao
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() + def dao_get_magazine_by_id(id): + return Magazine.query.filter_by(id=id).one() + + def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
Add get magazine by id to magazine dao
## Code Before: from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first() ## Instruction: Add get magazine by id to magazine dao ## Code After: from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() + def dao_get_magazine_by_id(id): + return Magazine.query.filter_by(id=id).one() + + def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
e1fc818b8d563c00c77060cd74d2781b287c0b5d
xnuplot/__init__.py
xnuplot/__init__.py
from .plot import Plot, SPlot __all__ = ["gnuplot", "numplot"]
from .plot import Plot, SPlot __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
Include Plot, SPlot in xnuplot.__all__.
Include Plot, SPlot in xnuplot.__all__.
Python
mit
marktsuchida/Xnuplot
from .plot import Plot, SPlot - __all__ = ["gnuplot", "numplot"] + __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
Include Plot, SPlot in xnuplot.__all__.
## Code Before: from .plot import Plot, SPlot __all__ = ["gnuplot", "numplot"] ## Instruction: Include Plot, SPlot in xnuplot.__all__. ## Code After: from .plot import Plot, SPlot __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
from .plot import Plot, SPlot - __all__ = ["gnuplot", "numplot"] + __all__ = ["Plot", "SPlot", "gnuplot", "numplot"] ? +++++++++++++++++
0d7f93a787dcf723d79e9122702833c4942f09cc
photo/qt/image.py
photo/qt/image.py
import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) if self.item.orientation: rm = QtGui.QMatrix() m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = rm.rotate(int(m.group(1))) return pixmap.transformed(rm) else: return pixmap
import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) rm = None try: rm = self.item.rotmatrix except AttributeError: if self.item.orientation: m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = QtGui.QMatrix().rotate(int(m.group(1))) self.item.rotmatrix = rm if rm: return pixmap.transformed(rm) else: return pixmap
Store the rotation matrix corresponding to the orientation in the item.
Store the rotation matrix corresponding to the orientation in the item.
Python
apache-2.0
RKrahl/photo-tools
import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) + rm = None + try: + rm = self.item.rotmatrix + except AttributeError: - if self.item.orientation: + if self.item.orientation: - rm = QtGui.QMatrix() - m = re.match(r"Rotate (\d+) CW", self.item.orientation) + m = re.match(r"Rotate (\d+) CW", self.item.orientation) - if m: + if m: - rm = rm.rotate(int(m.group(1))) + rm = QtGui.QMatrix().rotate(int(m.group(1))) + self.item.rotmatrix = rm + if rm: return pixmap.transformed(rm) else: return pixmap
Store the rotation matrix corresponding to the orientation in the item.
## Code Before: import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) if self.item.orientation: rm = QtGui.QMatrix() m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = rm.rotate(int(m.group(1))) return pixmap.transformed(rm) else: return pixmap ## Instruction: Store the rotation matrix corresponding to the orientation in the item. ## Code After: import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) rm = None try: rm = self.item.rotmatrix except AttributeError: if self.item.orientation: m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = QtGui.QMatrix().rotate(int(m.group(1))) self.item.rotmatrix = rm if rm: return pixmap.transformed(rm) else: return pixmap
import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) + rm = None + try: + rm = self.item.rotmatrix + except AttributeError: - if self.item.orientation: + if self.item.orientation: ? ++++ - rm = QtGui.QMatrix() - m = re.match(r"Rotate (\d+) CW", self.item.orientation) + m = re.match(r"Rotate (\d+) CW", self.item.orientation) ? ++++ - if m: + if m: ? ++++ - rm = rm.rotate(int(m.group(1))) ? ^ + rm = QtGui.QMatrix().rotate(int(m.group(1))) ? ++++ ++++++++++ ^^^^ + self.item.rotmatrix = rm + if rm: return pixmap.transformed(rm) else: return pixmap
2cb2779bfe1ddfcd6651665276ed0a1d513c57de
fireplace/cards/wog/shaman.py
fireplace/cards/wog/shaman.py
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT))
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_026: "Eternal Sentinel" play = UnlockOverload(CONTROLLER) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT)) ## # Spells class OG_206: "Stormcrack" play = Hit(TARGET, 4) ## # Weapons class OG_031: "Hammer of Twilight" deathrattle = Summon(CONTROLLER, "OG_031a")
Implement Eternal Sentinel, Stormcrack and Hammer of Twilight
Implement Eternal Sentinel, Stormcrack and Hammer of Twilight
Python
agpl-3.0
NightKev/fireplace,beheh/fireplace,jleclanche/fireplace
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) + class OG_026: + "Eternal Sentinel" + play = UnlockOverload(CONTROLLER) + + class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT)) + + ## + # Spells + + class OG_206: + "Stormcrack" + play = Hit(TARGET, 4) + + + ## + # Weapons + + class OG_031: + "Hammer of Twilight" + deathrattle = Summon(CONTROLLER, "OG_031a") +
Implement Eternal Sentinel, Stormcrack and Hammer of Twilight
## Code Before: from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT)) ## Instruction: Implement Eternal Sentinel, Stormcrack and Hammer of Twilight ## Code After: from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_026: "Eternal Sentinel" play = UnlockOverload(CONTROLLER) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT)) ## # Spells class OG_206: "Stormcrack" play = Hit(TARGET, 4) ## # Weapons class OG_031: "Hammer of Twilight" deathrattle = Summon(CONTROLLER, "OG_031a")
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) + class OG_026: + "Eternal Sentinel" + play = UnlockOverload(CONTROLLER) + + class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT)) + + + ## + # Spells + + class OG_206: + "Stormcrack" + play = Hit(TARGET, 4) + + + ## + # Weapons + + class OG_031: + "Hammer of Twilight" + deathrattle = Summon(CONTROLLER, "OG_031a")
550106fbff26c16cdf2269dc0778814c05ed1e3b
nap/apps.py
nap/apps.py
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' name = 'nap' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
Fix to include mandatory name attribute
Fix to include mandatory name attribute
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' + + name = 'nap' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
Fix to include mandatory name attribute
## Code Before: from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers') ## Instruction: Fix to include mandatory name attribute ## Code After: from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' name = 'nap' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' + + name = 'nap' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
a3c2f22819271adb7f08d18a54af863e5ca75c51
test/test_api.py
test/test_api.py
import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')]) intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api"
import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')]) intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api"
Add potential to include warnings in warthog.exceptions
Add potential to include warnings in warthog.exceptions
Python
mit
smarter-travel-media/warthog
import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): - errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')]) + errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')]) intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api"
Add potential to include warnings in warthog.exceptions
## Code Before: import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')]) intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api" ## Instruction: Add potential to include warnings in warthog.exceptions ## Code After: import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')]) intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api"
import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __all__ members should match' def test_all_exceptions_imported(exports): - errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')]) + errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')]) ? ++++++++++++++++++++++++++++ intersection = errors.intersection(exports) assert intersection == errors, "All available errors should be in warthog.api"
bcb24ef03a65d80c09ef47f19a64fd854a70c082
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__)
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
Test PrintReport with a real stream
Test PrintReport with a real stream
Python
mit
ktnyt/chainer,pfnet/chainer,rezoo/chainer,hvy/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,jnishi/chainer,niboshi/chainer,hvy/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,ktnyt/chainer,niboshi/chainer,wkentaro/chainer,chainer/chainer,ktnyt/chainer,niboshi/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,tkerola/chainer,wkentaro/chainer
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions + class TestPrintReport(unittest.TestCase): - def _setup(self, delete_flush=False): + def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) + if stream is None: - self.stream = MagicMock() + self.stream = MagicMock() - if delete_flush: + if delete_flush: - del self.stream.flush + del self.stream.flush + else: + self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) + def test_real_stream_raises_no_exception(self): + self._setup(stream=sys.stderr) + self.report(self.trainer) + testing.run_module(__name__, __file__)
Test PrintReport with a real stream
## Code Before: import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__) ## Instruction: Test PrintReport with a real stream ## Code After: import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions + class TestPrintReport(unittest.TestCase): - def _setup(self, delete_flush=False): + def _setup(self, stream=None, delete_flush=False): ? +++++++++++++ self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) + if stream is None: - self.stream = MagicMock() + self.stream = MagicMock() ? ++++ - if delete_flush: + if delete_flush: ? ++++ - del self.stream.flush + del self.stream.flush ? ++++ + else: + self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) + def test_real_stream_raises_no_exception(self): + self._setup(stream=sys.stderr) + self.report(self.trainer) + testing.run_module(__name__, __file__)
6926ddbb9cdbf05808339412cee5106e581f66cb
tests/import_wordpress_and_build_workflow.py
tests/import_wordpress_and_build_workflow.py
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
Use the more or less new options for importing
Use the more or less new options for importing
Python
mit
damianavila/nikola,xuhdev/nikola,getnikola/nikola,berezovskyi/nikola,TyberiusPrime/nikola,kotnik/nikola,atiro/nikola,servalproject/nikola,gwax/nikola,schettino72/nikola,kotnik/nikola,lucacerone/nikola,okin/nikola,s2hc-johan/nikola,andredias/nikola,masayuko/nikola,x1101/nikola,s2hc-johan/nikola,Proteus-tech/nikola,techdragon/nikola,jjconti/nikola,berezovskyi/nikola,techdragon/nikola,servalproject/nikola,masayuko/nikola,getnikola/nikola,immanetize/nikola,damianavila/nikola,jjconti/nikola,knowsuchagency/nikola,wcmckee/nikola,JohnTroony/nikola,xuhdev/nikola,getnikola/nikola,masayuko/nikola,andredias/nikola,gwax/nikola,knowsuchagency/nikola,damianavila/nikola,berezovskyi/nikola,TyberiusPrime/nikola,wcmckee/nikola,pluser/nikola,okin/nikola,schettino72/nikola,xuhdev/nikola,okin/nikola,x1101/nikola,TyberiusPrime/nikola,JohnTroony/nikola,wcmckee/nikola,atiro/nikola,lucacerone/nikola,yamila-moreno/nikola,Proteus-tech/nikola,x1101/nikola,lucacerone/nikola,kotnik/nikola,jjconti/nikola,JohnTroony/nikola,xuhdev/nikola,atiro/nikola,knowsuchagency/nikola,immanetize/nikola,Proteus-tech/nikola,gwax/nikola,techdragon/nikola,getnikola/nikola,pluser/nikola,s2hc-johan/nikola,immanetize/nikola,schettino72/nikola,servalproject/nikola,Proteus-tech/nikola,yamila-moreno/nikola,okin/nikola,andredias/nikola,pluser/nikola,yamila-moreno/nikola
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( - 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) + 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, + folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
Use the more or less new options for importing
## Code Before: from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main() ## Instruction: Use the more or less new options for importing ## Code After: from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
from __future__ import unicode_literals, print_function import os import shutil TEST_SITE_DIRECTORY = 'import_test_site' def main(import_directory=None): if import_directory is None: import_directory = TEST_SITE_DIRECTORY if os.path.exists(import_directory): print('deleting %s' % import_directory) shutil.rmtree(import_directory) test_directory = os.path.dirname(__file__) package_directory = os.path.abspath(os.path.join(test_directory, '..')) os.system('echo "y" | pip uninstall Nikola') os.system('pip install %s' % package_directory) os.system('nikola') import_file = os.path.join(test_directory, 'wordpress_export_example.xml') os.system( - 'nikola import_wordpress -f %s -o %s' % (import_file, import_directory)) + 'nikola import_wordpress -o {folder} {file}'.format(file=import_file, + folder=import_directory)) assert os.path.exists( import_directory), "The directory %s should be existing." os.chdir(import_directory) os.system('nikola build') if __name__ == '__main__': main()
f0af944db962bdb8ea764737860ce9168f779977
perfkitbenchmarker/linux_packages/azure_credentials.py
perfkitbenchmarker/linux_packages/azure_credentials.py
"""Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), AZURE_CREDENTIAL_LOCATION) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), AZURE_CREDENTIAL_LOCATION)
"""Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" vm.RemoteCommand('mkdir -p {0}'.format(AZURE_CREDENTIAL_LOCATION)) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), AZURE_CREDENTIAL_TOKENS_FILE) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), AZURE_CREDENTIAL_PROFILE_FILE)
Fix a bug in the Azure credentials package in which they would overwrite the directory.
Fix a bug in the Azure credentials package in which they would overwrite the directory. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=248750675
Python
apache-2.0
GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker
"""Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" + vm.RemoteCommand('mkdir -p {0}'.format(AZURE_CREDENTIAL_LOCATION)) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), - AZURE_CREDENTIAL_LOCATION) + AZURE_CREDENTIAL_TOKENS_FILE) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), - AZURE_CREDENTIAL_LOCATION) + AZURE_CREDENTIAL_PROFILE_FILE)
Fix a bug in the Azure credentials package in which they would overwrite the directory.
## Code Before: """Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), AZURE_CREDENTIAL_LOCATION) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), AZURE_CREDENTIAL_LOCATION) ## Instruction: Fix a bug in the Azure credentials package in which they would overwrite the directory. ## Code After: """Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" vm.RemoteCommand('mkdir -p {0}'.format(AZURE_CREDENTIAL_LOCATION)) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), AZURE_CREDENTIAL_TOKENS_FILE) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), AZURE_CREDENTIAL_PROFILE_FILE)
"""Package for installing the Azure credentials.""" import os from perfkitbenchmarker import object_storage_service AZURE_CREDENTIAL_LOCATION = '.azure' AZURE_CREDENTIAL_TOKENS_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'accessTokens.json') AZURE_CREDENTIAL_PROFILE_FILE = os.path.join( AZURE_CREDENTIAL_LOCATION, 'azureProfile.json') def Install(vm): """Copies Azure credentials to the VM.""" + vm.RemoteCommand('mkdir -p {0}'.format(AZURE_CREDENTIAL_LOCATION)) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_TOKENS_FILE)), - AZURE_CREDENTIAL_LOCATION) + AZURE_CREDENTIAL_TOKENS_FILE) vm.PushFile( object_storage_service.FindCredentialFile( os.path.join('~', AZURE_CREDENTIAL_PROFILE_FILE)), - AZURE_CREDENTIAL_LOCATION) ? ^^^^ ^^ + AZURE_CREDENTIAL_PROFILE_FILE) ? +++++ ^^^ ^^
cd2b628ca118ffae8090004e845e399110aada21
disk/datadog_checks/disk/__init__.py
disk/datadog_checks/disk/__init__.py
from .disk import Disk __all__ = ['Disk']
from .__about__ import __version__ from .disk import Disk all = [ '__version__', 'Disk' ]
Allow Agent to properly pull version info
[Disk] Allow Agent to properly pull version info
Python
bsd-3-clause
DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core
+ from .__about__ import __version__ from .disk import Disk - __all__ = ['Disk'] + all = [ + '__version__', 'Disk' + ]
Allow Agent to properly pull version info
## Code Before: from .disk import Disk __all__ = ['Disk'] ## Instruction: Allow Agent to properly pull version info ## Code After: from .__about__ import __version__ from .disk import Disk all = [ '__version__', 'Disk' ]
+ from .__about__ import __version__ from .disk import Disk - __all__ = ['Disk'] + all = [ + '__version__', 'Disk' + ]
0cd5deefc61f56351af24f6597a1509ea4b4b567
settings.py
settings.py
import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] LOG_FILE = 'rightnowalerts.log'
import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_FILE = os.environ.get('LOG_FILE', BASE_DIR + '/rightnowalerts.log')
Read log file from ENV and add full path for default
Read log file from ENV and add full path for default
Python
mit
lorden/right-now-alerts
import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] - LOG_FILE = 'rightnowalerts.log' + BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + LOG_FILE = os.environ.get('LOG_FILE', BASE_DIR + '/rightnowalerts.log')
Read log file from ENV and add full path for default
## Code Before: import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] LOG_FILE = 'rightnowalerts.log' ## Instruction: Read log file from ENV and add full path for default ## Code After: import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_FILE = os.environ.get('LOG_FILE', BASE_DIR + '/rightnowalerts.log')
import os INTERVAL = int(os.environ.get('INTERVAL', 60)) AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_REGION = os.environ.get('AWS_REGION', 'us-west-2') ALERTS = os.environ['ALERTS'] ANALYTICS_KEY_NAME = os.environ['ANALYTICS_KEY_NAME'] FROM_EMAIL = os.environ['FROM_EMAIL'] - LOG_FILE = 'rightnowalerts.log' + BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + LOG_FILE = os.environ.get('LOG_FILE', BASE_DIR + '/rightnowalerts.log')
8b3e40e70101433157709d9d774b199ce606196f
violations/tests/test_base.py
violations/tests/test_base.py
from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass self.assertEqual(self.library.get('dummy'), violation) def test_not_found(self): """Test violation not found""" with self.assertRaises(ViolationDoesNotExists): self.library.get('dummy!!!') def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass self.assertTrue(self.library.has('dummy')) self.assertFalse(self.library.has('dummy!!!'))
import sure from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass self.library.get('dummy').should.be.equal(violation) def test_not_found(self): """Test violation not found""" self.library.get.when.called_with('dummy!!!')\ .should.throw(ViolationDoesNotExists) def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass self.library.has('dummy').should.be.true self.library.has('dummy!!!').should.be.false
Use sure in violations bases tests
Use sure in violations bases tests
Python
mit
nvbn/coviolations_web,nvbn/coviolations_web
+ import sure from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass - self.assertEqual(self.library.get('dummy'), violation) + self.library.get('dummy').should.be.equal(violation) def test_not_found(self): """Test violation not found""" - with self.assertRaises(ViolationDoesNotExists): - self.library.get('dummy!!!') + self.library.get.when.called_with('dummy!!!')\ + .should.throw(ViolationDoesNotExists) def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass - self.assertTrue(self.library.has('dummy')) - self.assertFalse(self.library.has('dummy!!!')) + self.library.has('dummy').should.be.true + self.library.has('dummy!!!').should.be.false
Use sure in violations bases tests
## Code Before: from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass self.assertEqual(self.library.get('dummy'), violation) def test_not_found(self): """Test violation not found""" with self.assertRaises(ViolationDoesNotExists): self.library.get('dummy!!!') def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass self.assertTrue(self.library.has('dummy')) self.assertFalse(self.library.has('dummy!!!')) ## Instruction: Use sure in violations bases tests ## Code After: import sure from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass self.library.get('dummy').should.be.equal(violation) def test_not_found(self): """Test violation not found""" self.library.get.when.called_with('dummy!!!')\ .should.throw(ViolationDoesNotExists) def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass self.library.has('dummy').should.be.true self.library.has('dummy!!!').should.be.false
+ import sure from django.test import TestCase from ..base import ViolationsLibrary from ..exceptions import ViolationDoesNotExists class ViolationsLibraryCase(TestCase): """Violations library case""" def setUp(self): self.library = ViolationsLibrary() def test_register(self): """Test register""" @self.library.register('dummy') def violation(): pass - self.assertEqual(self.library.get('dummy'), violation) + self.library.get('dummy').should.be.equal(violation) def test_not_found(self): """Test violation not found""" - with self.assertRaises(ViolationDoesNotExists): - self.library.get('dummy!!!') ? ---- + self.library.get.when.called_with('dummy!!!')\ ? +++++++++++++++++ + + .should.throw(ViolationDoesNotExists) def test_has(self): """Test has method""" @self.library.register('dummy') def violation(): pass - self.assertTrue(self.library.has('dummy')) - self.assertFalse(self.library.has('dummy!!!')) + self.library.has('dummy').should.be.true + self.library.has('dummy!!!').should.be.false
02f7edc042b46f091663fc12451aa043106f4f38
correctiv_justizgelder/urls.py
correctiv_justizgelder/urls.py
from functools import wraps from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = patterns('', url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), )
from functools import wraps from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = [ url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), ]
Update urlpatterns and remove old patterns pattern
Update urlpatterns and remove old patterns pattern
Python
mit
correctiv/correctiv-justizgelder,correctiv/correctiv-justizgelder
from functools import wraps - from django.conf.urls import patterns, url + from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous - urlpatterns = patterns('', + urlpatterns = [ url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), - ) + ]
Update urlpatterns and remove old patterns pattern
## Code Before: from functools import wraps from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = patterns('', url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), ) ## Instruction: Update urlpatterns and remove old patterns pattern ## Code After: from functools import wraps from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous urlpatterns = [ url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), ]
from functools import wraps - from django.conf.urls import patterns, url ? ---------- + from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from .views import OrganisationSearchView, OrganisationDetail CACHE_TIME = 15 * 60 def c(view): @wraps(view) def cache_page_anonymous(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) return cache_page(CACHE_TIME)(view)(request, *args, **kwargs) return cache_page_anonymous - urlpatterns = patterns('', + urlpatterns = [ url(r'^$', c(OrganisationSearchView.as_view()), name='search'), url(_(r'^recipient/(?P<slug>[^/]+)/$'), c(OrganisationDetail.as_view()), name='organisation_detail'), - ) + ]
9de5a1935ceb3f39b17807096c800cdf01b219bf
Scripts/multi_process_files.py
Scripts/multi_process_files.py
from joblib import Parallel, delayed import multiprocessing import os from subprocess import call inputpath = '/data/amnh/darwin/images' segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
from joblib import Parallel, delayed import multiprocessing import os from subprocess import call # inputpath = '/data/amnh/darwin/images' # segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' inputpath = '/home/ibanez/data/amnh/darwin_notes/images' segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Fix paths for local execution different from cloud server.
Fix paths for local execution different from cloud server.
Python
apache-2.0
HackTheStacks/darwin-notes-image-processing,HackTheStacks/darwin-notes-image-processing
from joblib import Parallel, delayed import multiprocessing import os from subprocess import call - inputpath = '/data/amnh/darwin/images' + # inputpath = '/data/amnh/darwin/images' - segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' + # segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' + inputpath = '/home/ibanez/data/amnh/darwin_notes/images' + segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Fix paths for local execution different from cloud server.
## Code Before: from joblib import Parallel, delayed import multiprocessing import os from subprocess import call inputpath = '/data/amnh/darwin/images' segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs) ## Instruction: Fix paths for local execution different from cloud server. ## Code After: from joblib import Parallel, delayed import multiprocessing import os from subprocess import call # inputpath = '/data/amnh/darwin/images' # segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' inputpath = '/home/ibanez/data/amnh/darwin_notes/images' segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
from joblib import Parallel, delayed import multiprocessing import os from subprocess import call - inputpath = '/data/amnh/darwin/images' + # inputpath = '/data/amnh/darwin/images' ? ++ - segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' + # segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' ? ++ + inputpath = '/home/ibanez/data/amnh/darwin_notes/images' + segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges' def handle_file(filename): call([segment_exe, filename]) inputs = os.listdir(inputpath) num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
76728fcba7671575053620da9e1e26aaa279547a
awx/main/notifications/webhook_backend.py
awx/main/notifications/webhook_backend.py
import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages
import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend from awx.main.utils import get_awx_version logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 if 'User-Agent' not in self.headers: self.headers['User-Agent'] = "Tower {}".format(get_awx_version()) for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages
Set a user agent for the webhook if not provided
Set a user agent for the webhook if not provided
Python
apache-2.0
wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx
import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend + from awx.main.utils import get_awx_version logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 + if 'User-Agent' not in self.headers: + self.headers['User-Agent'] = "Tower {}".format(get_awx_version()) for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages
Set a user agent for the webhook if not provided
## Code Before: import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages ## Instruction: Set a user agent for the webhook if not provided ## Code After: import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend from awx.main.utils import get_awx_version logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 if 'User-Agent' not in self.headers: self.headers['User-Agent'] = "Tower {}".format(get_awx_version()) for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages
import logging import requests import json from django.utils.encoding import smart_text from awx.main.notifications.base import TowerBaseEmailBackend + from awx.main.utils import get_awx_version logger = logging.getLogger('awx.main.notifications.webhook_backend') class WebhookBackend(TowerBaseEmailBackend): init_parameters = {"url": {"label": "Target URL", "type": "string"}, "headers": {"label": "HTTP Headers", "type": "object"}} recipient_parameter = "url" sender_parameter = None def __init__(self, headers, fail_silently=False, **kwargs): self.headers = headers super(WebhookBackend, self).__init__(fail_silently=fail_silently) def format_body(self, body): return body def send_messages(self, messages): sent_messages = 0 + if 'User-Agent' not in self.headers: + self.headers['User-Agent'] = "Tower {}".format(get_awx_version()) for m in messages: r = requests.post("{}".format(m.recipients()[0]), data=json.dumps(m.body), headers=self.headers) if r.status_code >= 400: logger.error(smart_text("Error sending notification webhook: {}".format(r.text))) if not self.fail_silently: raise Exception(smart_text("Error sending notification webhook: {}".format(r.text))) sent_messages += 1 return sent_messages
a8515cf56837ef3f32ea53003f88275a47c4d249
src/pipeline.py
src/pipeline.py
import os import fnmatch import re import subprocess import sys import json import imp import time class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: mod = imp.load_source(step["packageName"], './') if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish()
import os import fnmatch import re import subprocess import sys import json import imp import time from pprint import pprint class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: mod = __import__(step["packageName"]) if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish()
Change the way to import package dynamically
Change the way to import package dynamically
Python
mit
s4553711/HiScript
import os import fnmatch import re import subprocess import sys import json import imp import time + from pprint import pprint class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: - mod = imp.load_source(step["packageName"], './') + mod = __import__(step["packageName"]) if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish()
Change the way to import package dynamically
## Code Before: import os import fnmatch import re import subprocess import sys import json import imp import time class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: mod = imp.load_source(step["packageName"], './') if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish() ## Instruction: Change the way to import package dynamically ## Code After: import os import fnmatch import re import subprocess import sys import json import imp import time from pprint import pprint class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: mod = __import__(step["packageName"]) if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish()
import os import fnmatch import re import subprocess import sys import json import imp import time + from pprint import pprint class pipeline(object): def __init__(self): self.name = '' self.taskId = '' self.taskPath = '' self.scriptPath = '' self.inputPath = '' self.outputPath = '' self.setting = '' def logger(self, message): print("["+time.strftime('%Y-%m-%d %H:%M%p %Z')+"] "+message) def read_config(self): with open("app.json") as json_file: self.setting = json.load(json_file) def clean(self): self.read_config() self.logger("Start pipeline") def processApp(self): self.logger("processApp") def pj_initialize(self): self.logger("initialize") def run(self): for step in self.setting['step']: - mod = imp.load_source(step["packageName"], './') ? -- ^^ ^^^^^^ ------ + mod = __import__(step["packageName"]) ? ++ ^^ ^ if hasattr(mod, step["className"]): class_inst = getattr(mod, step["className"])() class_inst.setName(step['name']) class_inst.init() class_inst.run() class_inst.finish()
eab72cdb7e58b5398ace19c74569b1eb35ea91f8
toolbox/plugins/standard_object_features.py
toolbox/plugins/standard_object_features.py
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): return vigra.analysis.extractRegionFeatures(rawImage.astype('float32'), labelImage.astype('uint32'), ignoreLabel=0)
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): return vigra.analysis.extractRegionFeatures(rawImage.squeeze().astype('float32'), labelImage.squeeze().astype('uint32'), ignoreLabel=0)
Fix default region feature computation plugin
Fix default region feature computation plugin
Python
mit
chaubold/hytra,chaubold/hytra,chaubold/hytra
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): - return vigra.analysis.extractRegionFeatures(rawImage.astype('float32'), + return vigra.analysis.extractRegionFeatures(rawImage.squeeze().astype('float32'), - labelImage.astype('uint32'), + labelImage.squeeze().astype('uint32'), ignoreLabel=0)
Fix default region feature computation plugin
## Code Before: from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): return vigra.analysis.extractRegionFeatures(rawImage.astype('float32'), labelImage.astype('uint32'), ignoreLabel=0) ## Instruction: Fix default region feature computation plugin ## Code After: from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): return vigra.analysis.extractRegionFeatures(rawImage.squeeze().astype('float32'), labelImage.squeeze().astype('uint32'), ignoreLabel=0)
from pluginsystem import object_feature_computation_plugin import vigra from vigra import numpy as np class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin): """ Computes the standard vigra region features """ worksForDimensions = [2, 3] omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>'] def computeFeatures(self, rawImage, labelImage, frameNumber): - return vigra.analysis.extractRegionFeatures(rawImage.astype('float32'), + return vigra.analysis.extractRegionFeatures(rawImage.squeeze().astype('float32'), ? ++++++++++ - labelImage.astype('uint32'), + labelImage.squeeze().astype('uint32'), ? ++++++++++ ignoreLabel=0)
3c30166378d37c812cecb505a3d9023b079d24be
app/__init__.py
app/__init__.py
from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
Fix stupid nltk data download thing
Fix stupid nltk data download thing
Python
mit
PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews
from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk - try: - nltk.data.find('tokenizers/punkt') - except LookupError: - nltk.download("punkt") + nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
Fix stupid nltk data download thing
## Code Before: from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 ## Instruction: Fix stupid nltk data download thing ## Code After: from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk - try: - nltk.data.find('tokenizers/punkt') - except LookupError: - nltk.download("punkt") ? ---- + nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
50fa164c4b09845bfa262c2f6959a3c5dfd6f76b
fluentcheck/classes/is_cls.py
fluentcheck/classes/is_cls.py
from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): def __init__(self, object_under_test: Any): super().__init__(object_under_test)
from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): pass
Remove methods with unnecessary super delegation.
Remove methods with unnecessary super delegation.
Python
mit
csparpa/check
from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): + pass - def __init__(self, object_under_test: Any): - super().__init__(object_under_test) -
Remove methods with unnecessary super delegation.
## Code Before: from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): def __init__(self, object_under_test: Any): super().__init__(object_under_test) ## Instruction: Remove methods with unnecessary super delegation. ## Code After: from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): pass
from typing import Any from ..assertions_is.booleans import __IsBool from ..assertions_is.collections import __IsCollections from ..assertions_is.dicts import __IsDicts from ..assertions_is.emptiness import __IsEmptiness from ..assertions_is.geo import __IsGeo from ..assertions_is.numbers import __IsNumbers from ..assertions_is.sequences import __IsSequences from ..assertions_is.strings import __IsStrings from ..assertions_is.types import __IsTypes from ..assertions_is.uuids import __IsUUIDs class Is(__IsBool, __IsCollections, __IsDicts, __IsEmptiness, __IsGeo, __IsNumbers, __IsSequences, __IsStrings, __IsTypes, __IsUUIDs): + pass - - def __init__(self, object_under_test: Any): - super().__init__(object_under_test)
23c9aeb707f6bc0b6948dffb03bd7c960b7e97a8
tests/test_vector2_reflect.py
tests/test_vector2_reflect.py
from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf from utils import units, vectors reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal))
from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf from utils import angle_isclose, units, vectors reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal)) assert angle_isclose(normal.angle(initial), 180 - normal.angle(reflected) )
Add a property tying reflect() and angle()
test_reflect_prop: Add a property tying reflect() and angle()
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf - from utils import units, vectors + from utils import angle_isclose, units, vectors reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal)) + assert angle_isclose(normal.angle(initial), + 180 - normal.angle(reflected) + )
Add a property tying reflect() and angle()
## Code Before: from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf from utils import units, vectors reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal)) ## Instruction: Add a property tying reflect() and angle() ## Code After: from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf from utils import angle_isclose, units, vectors reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal)) assert angle_isclose(normal.angle(initial), 180 - normal.angle(reflected) )
from ppb_vector import Vector2 import pytest from hypothesis import given, assume, note from math import isclose, isinf - from utils import units, vectors + from utils import angle_isclose, units, vectors ? +++++++++++++++ reflect_data = ( (Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)), (Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)), (Vector2(0, 1), Vector2(0, -1), Vector2(0, -1)), (Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1)), (Vector2(-1, -1), Vector2(-1, 0), Vector2(1, -1)) ) @pytest.mark.parametrize("initial_vector, surface_normal, expected_vector", reflect_data) def test_reflect(initial_vector, surface_normal, expected_vector): assert initial_vector.reflect(surface_normal).isclose(expected_vector) @given(initial=vectors(), normal=units()) def test_reflect_prop(initial: Vector2, normal: Vector2): assume(initial ^ normal != 0) reflected = initial.reflect(normal) returned = reflected.reflect(normal) note(f"Reflected: {reflected}") assert not any(map(isinf, reflected)) assert initial.isclose(returned) assert isclose((initial * normal), -(reflected * normal)) + assert angle_isclose(normal.angle(initial), + 180 - normal.angle(reflected) + )
138aa351b3dbe95f3cdebf01dbd3c75f1ce3fac2
src/ggrc/fulltext/sql.py
src/ggrc/fulltext/sql.py
from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, record.type, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
Fix test broken due to delete_record change
Fix test broken due to delete_record change
Python
apache-2.0
kr41/ggrc-core,uskudnik/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,josthkko/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,uskudnik/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,vladan-m/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,uskudnik/ggrc-core,NejcZupec/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,plamut/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core
from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): - self.delete_record(record.key, commit=False) + self.delete_record(record.key, record.type, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
Fix test broken due to delete_record change
## Code Before: from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit() ## Instruction: Fix test broken due to delete_record change ## Code After: from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): self.delete_record(record.key, record.type, commit=False) self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
from ggrc import db from . import Indexer class SqlIndexer(Indexer): def create_record(self, record, commit=True): for k,v in record.properties.items(): db.session.add(self.record_type( key=record.key, type=record.type, context_id=record.context_id, tags=record.tags, property=k, content=v, )) if commit: db.session.commit() def update_record(self, record, commit=True): - self.delete_record(record.key, commit=False) + self.delete_record(record.key, record.type, commit=False) ? +++++++++++++ self.create_record(record, commit=commit) def delete_record(self, key, type, commit=True): db.session.query(self.record_type).filter(\ self.record_type.key == key, self.record_type.type == type).delete() if commit: db.session.commit() def delete_all_records(self, commit=True): db.session.query(self.record_type).delete() if commit: db.session.commit()
d67099ce7d30e31b98251f7386b33caaa5199a01
censusreporter/config/prod/wsgi.py
censusreporter/config/prod/wsgi.py
import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
Correct location of newrelic config
Correct location of newrelic config
Python
mit
sseguku/simplecensusug,Code4SA/censusreporter,Code4SA/censusreporter,Code4SA/censusreporter,sseguku/simplecensusug,4bic/censusreporter,sseguku/simplecensusug,4bic/censusreporter,Code4SA/censusreporter,4bic/censusreporter
import os from django.core.wsgi import get_wsgi_application import newrelic.agent - newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') + newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
Correct location of newrelic config
## Code Before: import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application() ## Instruction: Correct location of newrelic config ## Code After: import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
import os from django.core.wsgi import get_wsgi_application import newrelic.agent - newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') + newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
05e651b0e606f216a78c61ccfb441ce7ed41d852
reg/compat.py
reg/compat.py
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) else: def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__)
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) else: # pragma: no cover def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__)
Exclude from coverage the code pathways that are specific to Python 2.
Exclude from coverage the code pathways that are specific to Python 2.
Python
bsd-3-clause
morepath/reg,taschini/reg
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) - else: + else: # pragma: no cover def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__)
Exclude from coverage the code pathways that are specific to Python 2.
## Code Before: import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) else: def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__) ## Instruction: Exclude from coverage the code pathways that are specific to Python 2. ## Code After: import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) else: # pragma: no cover def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__)
import sys from types import MethodType # True if we are running on Python 3. PY3 = sys.version_info[0] == 3 if PY3: string_types = (str,) else: # pragma: no cover string_types = (basestring,) # noqa if PY3: def create_method_for_class(callable, type): return MethodType(callable, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj) - else: + else: # pragma: no cover def create_method_for_class(callable, type): return MethodType(callable, None, type) def create_method_for_instance(callable, obj): return MethodType(callable, obj, obj.__class__)
84816dda37d071e521f65449ee59c992b5e302bc
megaprojects/blog/models.py
megaprojects/blog/models.py
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created']
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() @property def thumbnail(self): if self.image_set.published(): return self.image_set.published()[:1].get() class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created']
Add property for Post thumbnail
Add property for Post thumbnail
Python
apache-2.0
megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() + @property + def thumbnail(self): + if self.image_set.published(): + return self.image_set.published()[:1].get() + class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created']
Add property for Post thumbnail
## Code Before: from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created'] ## Instruction: Add property for Post thumbnail ## Code After: from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() @property def thumbnail(self): if self.image_set.published(): return self.image_set.published()[:1].get() class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created']
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from core.models import AuthorModel, ImageModel from .managers import PostManager, ImageManager import util STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')] class Post(AuthorModel): pubdate = models.DateTimeField('publication date', default=timezone.now()) status = models.CharField(max_length=1, choices=STATUS_CHOICES) body = models.TextField() drupal_id = models.IntegerField('drupal NID', unique=True, blank=True, null=True, help_text='Node ID from the previous Drupal website (imported).') objects = PostManager() + @property + def thumbnail(self): + if self.image_set.published(): + return self.image_set.published()[:1].get() + class Meta: ordering = ['-pubdate'] class Image(ImageModel): image = models.ImageField(upload_to=util.get_image_path) post = models.ForeignKey(Post) objects = ImageManager() class Meta: ordering = ['-post__pubdate', '-created']
769c83564d5f2272837c2fbea6d781110b71b8ca
main.py
main.py
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: if len(vectors[0]) == 2: display_source(vectors) clusters = kmeans(vectors, clusters_count=clusters_count) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: clusters = kmeans(vectors, clusters_count=clusters_count) if len(vectors[0]) == 2: display_source(vectors) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
Fix trying to display result in case of not 2D vectors
Fix trying to display result in case of not 2D vectors
Python
mit
vanashimko/k-means
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: + clusters = kmeans(vectors, clusters_count=clusters_count) if len(vectors[0]) == 2: display_source(vectors) - clusters = kmeans(vectors, clusters_count=clusters_count) - display_result(vectors, clusters) + display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
Fix trying to display result in case of not 2D vectors
## Code Before: from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: if len(vectors[0]) == 2: display_source(vectors) clusters = kmeans(vectors, clusters_count=clusters_count) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main() ## Instruction: Fix trying to display result in case of not 2D vectors ## Code After: from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: clusters = kmeans(vectors, clusters_count=clusters_count) if len(vectors[0]) == 2: display_source(vectors) display_result(vectors, clusters) else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
from sys import argv, stderr from drawer import * from kmeans import kmeans def read_vectors(file_name): result = None with open(file_name, 'r') as f: vector_length = int(f.readline()) vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines())) if all((len(x) == vector_length for x in vectors)): result = vectors return result def main(): vectors = read_vectors(argv[1]) clusters_count = int(argv[2]) if vectors: + clusters = kmeans(vectors, clusters_count=clusters_count) if len(vectors[0]) == 2: display_source(vectors) - clusters = kmeans(vectors, clusters_count=clusters_count) - display_result(vectors, clusters) + display_result(vectors, clusters) ? ++++ else: print('Invalid input', file=stderr) if __name__ == '__main__': main()
9608e32ded51ce87e890fd880044f252c6574ea5
examples/aiohttp_server.py
examples/aiohttp_server.py
from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: return web.json_response(response) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000)
from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: return web.json_response(response, status=response.http_status) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000)
Return http status in aiohttp example
Return http status in aiohttp example
Python
mit
bcb/jsonrpcserver
from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: - return web.json_response(response) + return web.json_response(response, status=response.http_status) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000)
Return http status in aiohttp example
## Code Before: from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: return web.json_response(response) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000) ## Instruction: Return http status in aiohttp example ## Code After: from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: return web.json_response(response, status=response.http_status) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000)
from aiohttp import web from jsonrpcserver.aio import methods @methods.add async def ping(): return 'pong' async def handle(request): request = await request.text() response = await methods.dispatch(request) if response.is_notification: return web.Response() else: - return web.json_response(response) + return web.json_response(response, status=response.http_status) app = web.Application() app.router.add_post('/', handle) if __name__ == '__main__': web.run_app(app, port=5000)
385e9c0b8af79de58efd3cf43b1981b7981d0a53
sympy/geometry/__init__.py
sympy/geometry/__init__.py
from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import * from sympy.geometry.exceptions import * from sympy.geometry.curve import Curve
from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \ intersection from sympy.geometry.exceptions import GeometryError from sympy.geometry.curve import Curve
Remove glob imports from sympy.geometry.
Remove glob imports from sympy.geometry.
Python
bsd-3-clause
postvakje/sympy,Mitchkoens/sympy,farhaanbukhsh/sympy,sampadsaha5/sympy,kumarkrishna/sympy,MechCoder/sympy,lindsayad/sympy,maniteja123/sympy,yashsharan/sympy,sahilshekhawat/sympy,MechCoder/sympy,rahuldan/sympy,yashsharan/sympy,kevalds51/sympy,Designist/sympy,jaimahajan1997/sympy,emon10005/sympy,skidzo/sympy,mcdaniel67/sympy,kaushik94/sympy,bukzor/sympy,beni55/sympy,Curious72/sympy,lindsayad/sympy,ga7g08/sympy,jaimahajan1997/sympy,amitjamadagni/sympy,sampadsaha5/sympy,AkademieOlympia/sympy,kaichogami/sympy,asm666/sympy,atsao72/sympy,aktech/sympy,hargup/sympy,kumarkrishna/sympy,kaichogami/sympy,emon10005/sympy,Arafatk/sympy,kaushik94/sympy,Sumith1896/sympy,AunShiLord/sympy,sahilshekhawat/sympy,debugger22/sympy,drufat/sympy,Titan-C/sympy,jamesblunt/sympy,wanglongqi/sympy,cccfran/sympy,rahuldan/sympy,dqnykamp/sympy,maniteja123/sympy,jerli/sympy,Designist/sympy,hargup/sympy,asm666/sympy,drufat/sympy,wyom/sympy,madan96/sympy,kevalds51/sympy,mafiya69/sympy,liangjiaxing/sympy,farhaanbukhsh/sympy,Davidjohnwilson/sympy,hargup/sympy,jbbskinny/sympy,shikil/sympy,jamesblunt/sympy,jerli/sympy,ahhda/sympy,shipci/sympy,garvitr/sympy,sunny94/temp,saurabhjn76/sympy,shikil/sympy,skirpichev/omg,meghana1995/sympy,abloomston/sympy,vipulroxx/sympy,Arafatk/sympy,atreyv/sympy,Davidjohnwilson/sympy,atsao72/sympy,drufat/sympy,Gadal/sympy,debugger22/sympy,lidavidm/sympy,mcdaniel67/sympy,ChristinaZografou/sympy,hrashk/sympy,sampadsaha5/sympy,Shaswat27/sympy,Mitchkoens/sympy,sahmed95/sympy,bukzor/sympy,pbrady/sympy,atreyv/sympy,iamutkarshtiwari/sympy,souravsingh/sympy,garvitr/sympy,Shaswat27/sympy,Designist/sympy,yashsharan/sympy,ChristinaZografou/sympy,moble/sympy,debugger22/sympy,pandeyadarsh/sympy,ga7g08/sympy,Sumith1896/sympy,AunShiLord/sympy,maniteja123/sympy,AkademieOlympia/sympy,Davidjohnwilson/sympy,dqnykamp/sympy,Gadal/sympy,shipci/sympy,moble/sympy,kaushik94/sympy,mcdaniel67/sympy,meghana1995/sympy,jamesblunt/sympy,grevutiu-gabriel/sympy,VaibhavAgarwalVA/sympy,garvitr/sympy,pandeyadarsh/sympy,ga7g08/sympy,sahmed95/sympy,MridulS/sympy,rahuldan/sympy,aktech/sympy,madan96/sympy,skidzo/sympy,oliverlee/sympy,asm666/sympy,dqnykamp/sympy,Sumith1896/sympy,ahhda/sympy,emon10005/sympy,chaffra/sympy,yukoba/sympy,MridulS/sympy,farhaanbukhsh/sympy,jbbskinny/sympy,saurabhjn76/sympy,souravsingh/sympy,sunny94/temp,abloomston/sympy,Vishluck/sympy,kaichogami/sympy,mafiya69/sympy,Arafatk/sympy,Curious72/sympy,mafiya69/sympy,liangjiaxing/sympy,Titan-C/sympy,shikil/sympy,madan96/sympy,abhiii5459/sympy,hrashk/sympy,abhiii5459/sympy,kmacinnis/sympy,Vishluck/sympy,kmacinnis/sympy,jbbskinny/sympy,oliverlee/sympy,MridulS/sympy,jaimahajan1997/sympy,cccfran/sympy,atsao72/sympy,aktech/sympy,souravsingh/sympy,sunny94/temp,beni55/sympy,moble/sympy,ahhda/sympy,MechCoder/sympy,toolforger/sympy,cswiercz/sympy,vipulroxx/sympy,chaffra/sympy,jerli/sympy,AkademieOlympia/sympy,postvakje/sympy,meghana1995/sympy,iamutkarshtiwari/sympy,VaibhavAgarwalVA/sympy,Mitchkoens/sympy,abloomston/sympy,pbrady/sympy,yukoba/sympy,Gadal/sympy,kmacinnis/sympy,pbrady/sympy,lidavidm/sympy,grevutiu-gabriel/sympy,toolforger/sympy,diofant/diofant,kumarkrishna/sympy,ChristinaZografou/sympy,kevalds51/sympy,AunShiLord/sympy,flacjacket/sympy,liangjiaxing/sympy,postvakje/sympy,pandeyadarsh/sympy,oliverlee/sympy,beni55/sympy,shipci/sympy,saurabhjn76/sympy,grevutiu-gabriel/sympy,wanglongqi/sympy,cswiercz/sympy,lidavidm/sympy,abhiii5459/sympy,skidzo/sympy,wanglongqi/sympy,amitjamadagni/sympy,Shaswat27/sympy,cccfran/sympy,Titan-C/sympy,sahmed95/sympy,Vishluck/sympy,wyom/sympy,wyom/sympy,cswiercz/sympy,bukzor/sympy,VaibhavAgarwalVA/sympy,sahilshekhawat/sympy,lindsayad/sympy,yukoba/sympy,Curious72/sympy,iamutkarshtiwari/sympy,atreyv/sympy,toolforger/sympy,vipulroxx/sympy,hrashk/sympy,chaffra/sympy
from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg - from sympy.geometry.util import * + from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \ + intersection - from sympy.geometry.exceptions import * + from sympy.geometry.exceptions import GeometryError from sympy.geometry.curve import Curve
Remove glob imports from sympy.geometry.
## Code Before: from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import * from sympy.geometry.exceptions import * from sympy.geometry.curve import Curve ## Instruction: Remove glob imports from sympy.geometry. ## Code After: from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \ intersection from sympy.geometry.exceptions import GeometryError from sympy.geometry.curve import Curve
from sympy.geometry.point import Point from sympy.geometry.line import Line, Ray, Segment from sympy.geometry.ellipse import Ellipse, Circle from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg - from sympy.geometry.util import * + from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \ + intersection - from sympy.geometry.exceptions import * ? ^ + from sympy.geometry.exceptions import GeometryError ? ^^^^^^^^^^^^^ from sympy.geometry.curve import Curve
c974a2fe075accdf58148fceb3f722b144e0b8d8
diylang/types.py
diylang/types.py
class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure: def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) class Environment: def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") class String: """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val
class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure(object): def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) class Environment(object): def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") class String(object): """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val
Fix Old-style class, subclass object explicitly.
Fix Old-style class, subclass object explicitly.
Python
bsd-3-clause
kvalle/diy-lisp,kvalle/diy-lisp,kvalle/diy-lang,kvalle/diy-lang
class DiyLangError(Exception): """General DIY Lang error class.""" pass - class Closure: + class Closure(object): def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) - class Environment: + class Environment(object): def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") - class String: + class String(object): + """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val
Fix Old-style class, subclass object explicitly.
## Code Before: class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure: def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) class Environment: def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") class String: """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val ## Instruction: Fix Old-style class, subclass object explicitly. ## Code After: class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure(object): def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) class Environment(object): def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") class String(object): """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val
class DiyLangError(Exception): """General DIY Lang error class.""" pass - class Closure: + class Closure(object): ? ++++++++ def __init__(self, env, params, body): raise NotImplementedError("DIY") def __repr__(self): return "<closure/%d>" % len(self.params) - class Environment: + class Environment(object): ? ++++++++ def __init__(self, variables=None): self.bindings = variables if variables else {} def lookup(self, symbol): raise NotImplementedError("DIY") def extend(self, variables): raise NotImplementedError("DIY") def set(self, symbol, value): raise NotImplementedError("DIY") - class String: + class String(object): ? ++++++++ + """ Simple data object for representing DIY Lang strings. Ignore this until you start working on part 8. """ def __init__(self, val=""): self.val = val def __str__(self): return '"{}"'.format(self.val) def __eq__(self, other): return isinstance(other, String) and other.val == self.val
6856c469da365c7463017e4c064e1ed25c12dfdc
foyer/tests/test_performance.py
foyer/tests/test_performance.py
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
Allow for some missing silica bond parameters
Python
mit
mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) - forcefield.apply(surface) + forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
Allow for some missing silica bond parameters
## Code Before: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100) ## Instruction: Allow for some missing silica bond parameters ## Code After: import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn @pytest.mark.timeout(1) def test_fullerene(): fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True) forcefield = Forcefield(get_fn('fullerene.xml')) forcefield.apply(fullerene, assert_dihedral_params=False) @pytest.mark.timeout(15) def test_surface(): surface = mb.load(get_fn('silica.mol2')) forcefield = Forcefield(get_fn('opls-silica.xml')) - forcefield.apply(surface) + forcefield.apply(surface, assert_bond_params=False) @pytest.mark.timeout(45) def test_polymer(): peg100 = mb.load(get_fn('peg100.mol2')) forcefield = Forcefield(name='oplsaa') forcefield.apply(peg100)
ef8f869c5a254d2e3d84c3fa8829215da88681b4
djangocms_export_objects/tests/docs.py
djangocms_export_objects/tests/docs.py
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
Fix build on python 2.6
Fix build on python 2.6
Python
bsd-3-clause
nephila/djangocms-export-objects,nephila/djangocms-export-objects
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir - from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ - @skipIf(has_no_internet(), "No internet") + @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
Fix build on python 2.6
## Code Before: from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise ## Instruction: Fix build on python 2.6 ## Code After: from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir - from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ - @skipIf(has_no_internet(), "No internet") + @unittest.skipIf(has_no_internet(), "No internet") ? +++++++++ def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise