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
02ef2f1cb4e1e0bf3696ea68b73d0d9c3b9c8657
events/views.py
events/views.py
from datetime import date from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) return render_to_response('events/event_archive_month.html', {'month': month})
from datetime import date, timedelta from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) previous = month - timedelta(days=15) next = month + timedelta(days=45) return render_to_response('events/event_archive_month.html', { 'month': month, 'previous_month': previous, 'next_month': next, })
Add links to previous and next month
Add links to previous and next month
Python
agpl-3.0
vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre
- from datetime import date + from datetime import date, timedelta from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) + previous = month - timedelta(days=15) + next = month + timedelta(days=45) - return render_to_response('events/event_archive_month.html', {'month': month}) + return render_to_response('events/event_archive_month.html', { + 'month': month, + 'previous_month': previous, + 'next_month': next, + })
Add links to previous and next month
## Code Before: from datetime import date from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) return render_to_response('events/event_archive_month.html', {'month': month}) ## Instruction: Add links to previous and next month ## Code After: from datetime import date, timedelta from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) previous = month - timedelta(days=15) next = month + timedelta(days=45) return render_to_response('events/event_archive_month.html', { 'month': month, 'previous_month': previous, 'next_month': next, })
- from datetime import date + from datetime import date, timedelta ? +++++++++++ from django.shortcuts import render_to_response def month (request, year, month): month = date(int(year), int(month), 1) + previous = month - timedelta(days=15) + next = month + timedelta(days=45) - return render_to_response('events/event_archive_month.html', {'month': month}) ? ---------------- + return render_to_response('events/event_archive_month.html', { + 'month': month, + 'previous_month': previous, + 'next_month': next, + })
8182b0b053d45252c7800aa1bf1f750fdfa7f876
examples/jumbo_fields.py
examples/jumbo_fields.py
from __future__ import print_function import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
from __future__ import print_function import os from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
Make JumboFieldsWorkflow fail if no env var
Make JumboFieldsWorkflow fail if no env var If SIMPLEFLOW_JUMBO_FIELDS_BUCKET is not set, the example doesn't work; make this clear. Signed-off-by: Yves Bastide <[email protected]>
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
from __future__ import print_function - import time + import os + from simpleflow import Workflow, activity - from simpleflow import ( - activity, - Workflow, - futures, - ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): + if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: + print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") + raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
Make JumboFieldsWorkflow fail if no env var
## Code Before: from __future__ import print_function import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result)) ## Instruction: Make JumboFieldsWorkflow fail if no env var ## Code After: from __future__ import print_function import os from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
from __future__ import print_function - import time + import os + from simpleflow import Workflow, activity - from simpleflow import ( - activity, - Workflow, - futures, - ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): + if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: + print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") + raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
273999eeedee551a4490c89928650fbfebeb4a22
tests/_test.py
tests/_test.py
import unittest class TestCase(unittest.TestCase): pass
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
Fix random seed in unit tests
Fix random seed in unit tests Signed-off-by: Niklas Koep <[email protected]>
Python
bsd-3-clause
pymanopt/pymanopt,pymanopt/pymanopt
+ import random import unittest + + import autograd.numpy as anp + import numpy as np + import tensorflow as tf + import torch class TestCase(unittest.TestCase): - pass + @classmethod + def testSetUp(cls): + seed = 42 + random.seed(seed) + anp.random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + tf.random.set_seed(seed)
Fix random seed in unit tests
## Code Before: import unittest class TestCase(unittest.TestCase): pass ## Instruction: Fix random seed in unit tests ## Code After: import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
+ import random import unittest + + import autograd.numpy as anp + import numpy as np + import tensorflow as tf + import torch class TestCase(unittest.TestCase): - pass + @classmethod + def testSetUp(cls): + seed = 42 + random.seed(seed) + anp.random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + tf.random.set_seed(seed)
a775cd66de2bbc2e176f946e93fe9c0636cf7115
documents/views/utils.py
documents/views/utils.py
from django.http import HttpResponse def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() return response
from django.http import HttpResponse import os def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() # remove the tmp file os.remove(outputFile) return response
Remove temporary files after delivering them
Remove temporary files after delivering them
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
from django.http import HttpResponse + import os def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() + # remove the tmp file + os.remove(outputFile) + return response
Remove temporary files after delivering them
## Code Before: from django.http import HttpResponse def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() return response ## Instruction: Remove temporary files after delivering them ## Code After: from django.http import HttpResponse import os def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() # remove the tmp file os.remove(outputFile) return response
from django.http import HttpResponse + import os def render_to_mimetype_response(mimetype, filename, outputFile): response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = "attachment; filename=\"%s\"" % (filename) f = open(outputFile) try: content = f.read() response.write(content) finally: f.close() + # remove the tmp file + os.remove(outputFile) + return response
eaea19daa9ccb01b0dbef999c1f897fb9c4c19ee
Sketches/MH/pymedia/test_Input.py
Sketches/MH/pymedia/test_Input.py
from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"), Output(sample_rate=44100, channels=1, format="U8"), ).run()
from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"), Output(sample_rate=8000, channels=1, format="S16_LE"), ).run()
Fix so both input and output are the same format!
Fix so both input and output are the same format! Matt
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline - Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"), + Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"), - Output(sample_rate=44100, channels=1, format="U8"), + Output(sample_rate=8000, channels=1, format="S16_LE"), ).run()
Fix so both input and output are the same format!
## Code Before: from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"), Output(sample_rate=44100, channels=1, format="U8"), ).run() ## Instruction: Fix so both input and output are the same format! ## Code After: from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"), Output(sample_rate=8000, channels=1, format="S16_LE"), ).run()
from Audio.PyMedia.Input import Input from Audio.PyMedia.Output import Output from Kamaelia.Chassis.Pipeline import Pipeline - Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"), ? ^^^ + Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"), ? ^^ - Output(sample_rate=44100, channels=1, format="U8"), ? ^^^ ^^ + Output(sample_rate=8000, channels=1, format="S16_LE"), ? ^^ ^^^^^^ ).run()
46017b7c1f480f5cb94ca0ef380b0666f8b77d0f
helevents/models.py
helevents/models.py
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
Remove uuid display from user string
Remove uuid display from user string
Python
mit
City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): - return ' - '.join([super().__str__(), self.get_display_name(), self.email]) + return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
Remove uuid display from user string
## Code Before: from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first() ## Instruction: Remove uuid display from user string ## Code After: from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): - return ' - '.join([super().__str__(), self.get_display_name(), self.email]) ? ------------------- + return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
ba3009d1d19243c703743070df68ad1ea11d454e
addons/hr_contract/__terp__.py
addons/hr_contract/__terp__.py
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], "update_xml" : ["hr_contract_view.xml"], "active": False, "installable": True }
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], "update_xml" : [ "hr_contract_view.xml", "hr_contract_security.xml" ], "active": False, "installable": True }
Add hr_contract_security.xml file entry in update_xml section
Add hr_contract_security.xml file entry in update_xml section bzr revid: [email protected]
Python
agpl-3.0
ygol/odoo,fossoult/odoo,leoliujie/odoo,hoatle/odoo,vrenaville/ngo-addons-backport,matrixise/odoo,cedk/odoo,chiragjogi/odoo,lsinfo/odoo,Nick-OpusVL/odoo,ihsanudin/odoo,dfang/odoo,gsmartway/odoo,ojengwa/odoo,windedge/odoo,tangyiyong/odoo,agrista/odoo-saas,mlaitinen/odoo,Daniel-CA/odoo,incaser/odoo-odoo,VitalPet/odoo,xujb/odoo,ojengwa/odoo,frouty/odoo_oph,ClearCorp-dev/odoo,sysadminmatmoz/OCB,syci/OCB,klunwebale/odoo,jusdng/odoo,VielSoft/odoo,goliveirab/odoo,Nowheresly/odoo,VielSoft/odoo,gorjuce/odoo,ccomb/OpenUpgrade,ChanduERP/odoo,fuselock/odoo,odoousers2014/odoo,acshan/odoo,patmcb/odoo,PongPi/isl-odoo,hmen89/odoo,Eric-Zhong/odoo,zchking/odoo,guerrerocarlos/odoo,Noviat/odoo,naousse/odoo,bakhtout/odoo-educ,AuyaJackie/odoo,jiangzhixiao/odoo,kittiu/odoo,Kilhog/odoo,xzYue/odoo,bguillot/OpenUpgrade,tangyiyong/odoo,jesramirez/odoo,markeTIC/OCB,shingonoide/odoo,xzYue/odoo,savoirfairelinux/odoo,matrixise/odoo,dariemp/odoo,ClearCorp-dev/odoo,dkubiak789/odoo,naousse/odoo,x111ong/odoo,virgree/odoo,odoousers2014/odoo,Nick-OpusVL/odoo,OSSESAC/odoopubarquiluz,lombritz/odoo,Drooids/odoo,Eric-Zhong/odoo,TRESCLOUD/odoopub,chiragjogi/odoo,prospwro/odoo,lsinfo/odoo,QianBIG/odoo,factorlibre/OCB,Drooids/odoo,florian-dacosta/OpenUpgrade,bakhtout/odoo-educ,guerrerocarlos/odoo,erkrishna9/odoo,syci/OCB,dkubiak789/odoo,FlorianLudwig/odoo,mvaled/OpenUpgrade,JonathanStein/odoo,jiachenning/odoo,Antiun/odoo,ShineFan/odoo,joshuajan/odoo,brijeshkesariya/odoo,Maspear/odoo,rubencabrera/odoo,PongPi/isl-odoo,RafaelTorrealba/odoo,TRESCLOUD/odoopub,blaggacao/OpenUpgrade,ingadhoc/odoo,gvb/odoo,leorochael/odoo,rdeheele/odoo,ovnicraft/odoo,colinnewell/odoo,gsmartway/odoo,syci/OCB,thanhacun/odoo,hubsaysnuaa/odoo,kybriainfotech/iSocioCRM,Elico-Corp/odoo_OCB,CopeX/odoo,codekaki/odoo,bkirui/odoo,bplancher/odoo,JonathanStein/odoo,massot/odoo,florian-dacosta/OpenUpgrade,Kilhog/odoo,BT-ojossen/odoo,slevenhagen/odoo,mmbtba/odoo,BT-ojossen/odoo,SerpentCS/odoo,ojengwa/odoo,ygol/odoo,charbeljc/OCB,ThinkOpen-Solutions/odoo,ihsanudin/odoo,synconics/odoo,stonegithubs/odoo,mkieszek/odoo,optima-ict/odoo,rschnapka/odoo,takis/odoo,Adel-Magebinary/odoo,brijeshkesariya/odoo,florian-dacosta/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,MarcosCommunity/odoo,Grirrane/odoo,aviciimaxwell/odoo,juanalfonsopr/odoo,CubicERP/odoo,nagyistoce/odoo-dev-odoo,hip-odoo/odoo,podemos-info/odoo,jfpla/odoo,alexcuellar/odoo,optima-ict/odoo,cedk/odoo,ihsanudin/odoo,chiragjogi/odoo,OpenUpgrade/OpenUpgrade,jeasoft/odoo,lombritz/odoo,luiseduardohdbackup/odoo,vnsofthe/odoo,xujb/odoo,apanju/GMIO_Odoo,Ichag/odoo,srsman/odoo,mmbtba/odoo,BT-rmartin/odoo,addition-it-solutions/project-all,hip-odoo/odoo,andreparames/odoo,SerpentCS/odoo,ramadhane/odoo,OpenUpgrade-dev/OpenUpgrade,savoirfairelinux/OpenUpgrade,Nowheresly/odoo,fuhongliang/odoo,mlaitinen/odoo,ingadhoc/odoo,tinkerthaler/odoo,fossoult/odoo,microcom/odoo,apocalypsebg/odoo,bealdav/OpenUpgrade,GauravSahu/odoo,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,apanju/odoo,dfang/odoo,oasiswork/odoo,ingadhoc/odoo,OSSESAC/odoopubarquiluz,oliverhr/odoo,fgesora/odoo,gdgellatly/OCB1,hassoon3/odoo,janocat/odoo,mustafat/odoo-1,vnsofthe/odoo,osvalr/odoo,Drooids/odoo,slevenhagen/odoo,credativUK/OCB,tvibliani/odoo,sysadminmatmoz/OCB,CatsAndDogsbvba/odoo,blaggacao/OpenUpgrade,spadae22/odoo,sve-odoo/odoo,NeovaHealth/odoo,mkieszek/odoo,sv-dev1/odoo,feroda/odoo,hassoon3/odoo,apocalypsebg/odoo,SAM-IT-SA/odoo,savoirfairelinux/OpenUpgrade,prospwro/odoo,pedrobaeza/odoo,alexcuellar/odoo,lombritz/odoo,OSSESAC/odoopubarquiluz,Nowheresly/odoo,florentx/OpenUpgrade,x111ong/odoo,sysadminmatmoz/OCB,shaufi10/odoo,tangyiyong/odoo,datenbetrieb/odoo,Grirrane/odoo,dllsf/odootest,kybriainfotech/iSocioCRM,slevenhagen/odoo,shivam1111/odoo,oliverhr/odoo,ojengwa/odoo,rahuldhote/odoo,ovnicraft/odoo,cysnake4713/odoo,fjbatresv/odoo,csrocha/OpenUpgrade,andreparames/odoo,bkirui/odoo,BT-rmartin/odoo,datenbetrieb/odoo,JCA-Developpement/Odoo,elmerdpadilla/iv,abenzbiria/clients_odoo,gsmartway/odoo,dezynetechnologies/odoo,javierTerry/odoo,apanju/odoo,camptocamp/ngo-addons-backport,takis/odoo,patmcb/odoo,minhtuancn/odoo,storm-computers/odoo,fevxie/odoo,CopeX/odoo,erkrishna9/odoo,Drooids/odoo,omprakasha/odoo,stephen144/odoo,shivam1111/odoo,joshuajan/odoo,Grirrane/odoo,kifcaliph/odoo,colinnewell/odoo,mmbtba/odoo,javierTerry/odoo,microcom/odoo,thanhacun/odoo,mvaled/OpenUpgrade,kittiu/odoo,alexteodor/odoo,credativUK/OCB,synconics/odoo,srsman/odoo,apanju/odoo,markeTIC/OCB,poljeff/odoo,CatsAndDogsbvba/odoo,fuhongliang/odoo,steedos/odoo,BT-ojossen/odoo,kittiu/odoo,aviciimaxwell/odoo,fevxie/odoo,laslabs/odoo,diagramsoftware/odoo,cysnake4713/odoo,incaser/odoo-odoo,waytai/odoo,ovnicraft/odoo,agrista/odoo-saas,omprakasha/odoo,omprakasha/odoo,BT-astauder/odoo,jeasoft/odoo,minhtuancn/odoo,ygol/odoo,rubencabrera/odoo,grap/OCB,leorochael/odoo,Ichag/odoo,numerigraphe/odoo,BT-fgarbely/odoo,omprakasha/odoo,jusdng/odoo,diagramsoftware/odoo,sinbazhou/odoo,podemos-info/odoo,rubencabrera/odoo,bakhtout/odoo-educ,diagramsoftware/odoo,salaria/odoo,optima-ict/odoo,Nowheresly/odoo,shaufi/odoo,dalegregory/odoo,oihane/odoo,mvaled/OpenUpgrade,jfpla/odoo,patmcb/odoo,bwrsandman/OpenUpgrade,deKupini/erp,ramadhane/odoo,factorlibre/OCB,Nowheresly/odoo,luiseduardohdbackup/odoo,shaufi10/odoo,CopeX/odoo,laslabs/odoo,windedge/odoo,abdellatifkarroum/odoo,ujjwalwahi/odoo,mvaled/OpenUpgrade,fuhongliang/odoo,grap/OCB,BT-ojossen/odoo,gavin-feng/odoo,diagramsoftware/odoo,markeTIC/OCB,doomsterinc/odoo,oliverhr/odoo,salaria/odoo,nitinitprof/odoo,dezynetechnologies/odoo,numerigraphe/odoo,Elico-Corp/odoo_OCB,OpenPymeMx/OCB,addition-it-solutions/project-all,ihsanudin/odoo,doomsterinc/odoo,incaser/odoo-odoo,shingonoide/odoo,avoinsystems/odoo,salaria/odoo,mmbtba/odoo,Kilhog/odoo,numerigraphe/odoo,Bachaco-ve/odoo,tinkerthaler/odoo,shaufi/odoo,storm-computers/odoo,shingonoide/odoo,CatsAndDogsbvba/odoo,fdvarela/odoo8,tinkhaven-organization/odoo,slevenhagen/odoo-npg,savoirfairelinux/OpenUpgrade,ubic135/odoo-design,Gitlab11/odoo,alqfahad/odoo,Nick-OpusVL/odoo,guerrerocarlos/odoo,OpenUpgrade/OpenUpgrade,alhashash/odoo,vnsofthe/odoo,windedge/odoo,collex100/odoo,storm-computers/odoo,rahuldhote/odoo,massot/odoo,nagyistoce/odoo-dev-odoo,funkring/fdoo,dgzurita/odoo,eino-makitalo/odoo,savoirfairelinux/odoo,hanicker/odoo,sysadminmatmoz/OCB,srsman/odoo,apanju/odoo,hifly/OpenUpgrade,tinkerthaler/odoo,fjbatresv/odoo,bealdav/OpenUpgrade,SerpentCS/odoo,lightcn/odoo,ujjwalwahi/odoo,synconics/odoo,hopeall/odoo,jiangzhixiao/odoo,PongPi/isl-odoo,papouso/odoo,vnsofthe/odoo,bplancher/odoo,pplatek/odoo,stonegithubs/odoo,fevxie/odoo,Eric-Zhong/odoo,damdam-s/OpenUpgrade,nagyistoce/odoo-dev-odoo,RafaelTorrealba/odoo,brijeshkesariya/odoo,papouso/odoo,ovnicraft/odoo,BT-fgarbely/odoo,datenbetrieb/odoo,abdellatifkarroum/odoo,Nick-OpusVL/odoo,lgscofield/odoo,csrocha/OpenUpgrade,bplancher/odoo,ShineFan/odoo,rowemoore/odoo,chiragjogi/odoo,sv-dev1/odoo,datenbetrieb/odoo,ramadhane/odoo,dariemp/odoo,ThinkOpen-Solutions/odoo,sebalix/OpenUpgrade,doomsterinc/odoo,sinbazhou/odoo,funkring/fdoo,OpenPymeMx/OCB,ygol/odoo,Danisan/odoo-1,stonegithubs/odoo,elmerdpadilla/iv,dsfsdgsbngfggb/odoo,odoo-turkiye/odoo,aviciimaxwell/odoo,VitalPet/odoo,leoliujie/odoo,grap/OpenUpgrade,kybriainfotech/iSocioCRM,xujb/odoo,ubic135/odoo-design,fevxie/odoo,apanju/odoo,stonegithubs/odoo,sinbazhou/odoo,glovebx/odoo,avoinsystems/odoo,ChanduERP/odoo,gvb/odoo,kifcaliph/odoo,Adel-Magebinary/odoo,cedk/odoo,BT-rmartin/odoo,odooindia/odoo,oasiswork/odoo,arthru/OpenUpgrade,nitinitprof/odoo,grap/OCB,SAM-IT-SA/odoo,joariasl/odoo,Nick-OpusVL/odoo,christophlsa/odoo,shivam1111/odoo,rowemoore/odoo,takis/odoo,tvtsoft/odoo8,JGarcia-Panach/odoo,cedk/odoo,waytai/odoo,oasiswork/odoo,oihane/odoo,tangyiyong/odoo,gavin-feng/odoo,hopeall/odoo,JGarcia-Panach/odoo,slevenhagen/odoo-npg,bkirui/odoo,Endika/OpenUpgrade,abenzbiria/clients_odoo,sergio-incaser/odoo,glovebx/odoo,ramitalat/odoo,GauravSahu/odoo,Bachaco-ve/odoo,nhomar/odoo,janocat/odoo,odootr/odoo,ApuliaSoftware/odoo,makinacorpus/odoo,NeovaHealth/odoo,PongPi/isl-odoo,fevxie/odoo,CubicERP/odoo,Endika/OpenUpgrade,arthru/OpenUpgrade,ApuliaSoftware/odoo,shingonoide/odoo,hoatle/odoo,brijeshkesariya/odoo,matrixise/odoo,joariasl/odoo,rahuldhote/odoo,frouty/odoogoeen,wangjun/odoo,patmcb/odoo,tarzan0820/odoo,PongPi/isl-odoo,odoo-turkiye/odoo,diagramsoftware/odoo,ApuliaSoftware/odoo,damdam-s/OpenUpgrade,omprakasha/odoo,rgeleta/odoo,guerrerocarlos/odoo,alqfahad/odoo,nhomar/odoo,RafaelTorrealba/odoo,lombritz/odoo,realsaiko/odoo,AuyaJackie/odoo,ingadhoc/odoo,dalegregory/odoo,cpyou/odoo,colinnewell/odoo,numerigraphe/odoo,funkring/fdoo,cedk/odoo,csrocha/OpenUpgrade,charbeljc/OCB,tinkerthaler/odoo,salaria/odoo,jpshort/odoo,provaleks/o8,sebalix/OpenUpgrade,jfpla/odoo,RafaelTorrealba/odoo,dgzurita/odoo,vnsofthe/odoo,nexiles/odoo,xzYue/odoo,nexiles/odoo,kirca/OpenUpgrade,hbrunn/OpenUpgrade,klunwebale/odoo,christophlsa/odoo,JonathanStein/odoo,sve-odoo/odoo,janocat/odoo,srimai/odoo,makinacorpus/odoo,javierTerry/odoo,luistorresm/odoo,inspyration/odoo,jusdng/odoo,Adel-Magebinary/odoo,realsaiko/odoo,QianBIG/odoo,hip-odoo/odoo,ramadhane/odoo,jolevq/odoopub,GauravSahu/odoo,frouty/odoo_oph,alhashash/odoo,QianBIG/odoo,arthru/OpenUpgrade,andreparames/odoo,Danisan/odoo-1,cpyou/odoo,dllsf/odootest,Endika/odoo,draugiskisprendimai/odoo,dezynetechnologies/odoo,markeTIC/OCB,mustafat/odoo-1,JGarcia-Panach/odoo,OpusVL/odoo,tinkhaven-organization/odoo,OSSESAC/odoopubarquiluz,RafaelTorrealba/odoo,fuselock/odoo,OpenPymeMx/OCB,tarzan0820/odoo,rahuldhote/odoo,credativUK/OCB,hbrunn/OpenUpgrade,ujjwalwahi/odoo,frouty/odoogoeen,ShineFan/odoo,goliveirab/odoo,sv-dev1/odoo,jeasoft/odoo,steedos/odoo,Codefans-fan/odoo,TRESCLOUD/odoopub,hifly/OpenUpgrade,ecosoft-odoo/odoo,acshan/odoo,dsfsdgsbngfggb/odoo,nhomar/odoo-mirror,thanhacun/odoo,brijeshkesariya/odoo,lsinfo/odoo,jaxkodex/odoo,ihsanudin/odoo,nhomar/odoo-mirror,dfang/odoo,Daniel-CA/odoo,havt/odoo,slevenhagen/odoo,hbrunn/OpenUpgrade,Daniel-CA/odoo,andreparames/odoo,fuselock/odoo,VitalPet/odoo,rgeleta/odoo,credativUK/OCB,erkrishna9/odoo,odoo-turkiye/odoo,Endika/odoo,florentx/OpenUpgrade,nuuuboo/odoo,OpenUpgrade/OpenUpgrade,guewen/OpenUpgrade,sergio-incaser/odoo,x111ong/odoo,VielSoft/odoo,abdellatifkarroum/odoo,abenzbiria/clients_odoo,camptocamp/ngo-addons-backport,tvtsoft/odoo8,BT-astauder/odoo,massot/odoo,sebalix/OpenUpgrade,joariasl/odoo,acshan/odoo,tarzan0820/odoo,lsinfo/odoo,JGarcia-Panach/odoo,dgzurita/odoo,chiragjogi/odoo,BT-rmartin/odoo,zchking/odoo,funkring/fdoo,bwrsandman/OpenUpgrade,bwrsandman/OpenUpgrade,rdeheele/odoo,bealdav/OpenUpgrade,0k/odoo,synconics/odoo,massot/odoo,blaggacao/OpenUpgrade,vrenaville/ngo-addons-backport,NeovaHealth/odoo,OpenPymeMx/OCB,bguillot/OpenUpgrade,stephen144/odoo,Adel-Magebinary/odoo,mszewczy/odoo,QianBIG/odoo,fossoult/odoo,odooindia/odoo,sadleader/odoo,abdellatifkarroum/odoo,Ernesto99/odoo,alexteodor/odoo,vrenaville/ngo-addons-backport,brijeshkesariya/odoo,hifly/OpenUpgrade,hubsaysnuaa/odoo,Endika/odoo,Ichag/odoo,luistorresm/odoo,kittiu/odoo,leorochael/odoo,vnsofthe/odoo,OpenPymeMx/OCB,AuyaJackie/odoo,ramadhane/odoo,patmcb/odoo,VielSoft/odoo,waytai/odoo,OpusVL/odoo,jiachenning/odoo,CatsAndDogsbvba/odoo,bplancher/odoo,credativUK/OCB,avoinsystems/odoo,mlaitinen/odoo,nexiles/odoo,BT-fgarbely/odoo,nitinitprof/odoo,tinkerthaler/odoo,makinacorpus/odoo,jaxkodex/odoo,camptocamp/ngo-addons-backport,luiseduardohdbackup/odoo,tvibliani/odoo,bobisme/odoo,oliverhr/odoo,ChanduERP/odoo,FlorianLudwig/odoo,christophlsa/odoo,waytai/odoo,pedrobaeza/OpenUpgrade,eino-makitalo/odoo,mmbtba/odoo,papouso/odoo,gvb/odoo,hubsaysnuaa/odoo,sinbazhou/odoo,NL66278/OCB,poljeff/odoo,KontorConsulting/odoo,savoirfairelinux/odoo,abstract-open-solutions/OCB,hmen89/odoo,rowemoore/odoo,shivam1111/odoo,numerigraphe/odoo,BT-rmartin/odoo,prospwro/odoo,FlorianLudwig/odoo,n0m4dz/odoo,fevxie/odoo,spadae22/odoo,kifcaliph/odoo,bplancher/odoo,pedrobaeza/odoo,tvtsoft/odoo8,ingadhoc/odoo,massot/odoo,datenbetrieb/odoo,slevenhagen/odoo-npg,alqfahad/odoo,odootr/odoo,havt/odoo,BT-rmartin/odoo,0k/OpenUpgrade,bwrsandman/OpenUpgrade,draugiskisprendimai/odoo,prospwro/odoo,mustafat/odoo-1,sinbazhou/odoo,jusdng/odoo,sergio-incaser/odoo,papouso/odoo,cloud9UG/odoo,rdeheele/odoo,nuuuboo/odoo,ClearCorp-dev/odoo,luistorresm/odoo,srimai/odoo,syci/OCB,simongoffin/website_version,ramitalat/odoo,steedos/odoo,ccomb/OpenUpgrade,agrista/odoo-saas,colinnewell/odoo,hopeall/odoo,addition-it-solutions/project-all,oliverhr/odoo,waytai/odoo,Nick-OpusVL/odoo,abdellatifkarroum/odoo,klunwebale/odoo,abdellatifkarroum/odoo,cloud9UG/odoo,juanalfonsopr/odoo,shaufi/odoo,rschnapka/odoo,oihane/odoo,Codefans-fan/odoo,lombritz/odoo,oasiswork/odoo,OpenUpgrade/OpenUpgrade,mustafat/odoo-1,jusdng/odoo,virgree/odoo,tarzan0820/odoo,fuselock/odoo,tvibliani/odoo,ramadhane/odoo,joshuajan/odoo,matrixise/odoo,jesramirez/odoo,shivam1111/odoo,credativUK/OCB,VitalPet/odoo,MarcosCommunity/odoo,jeasoft/odoo,windedge/odoo,dllsf/odootest,NL66278/OCB,hoatle/odoo,lgscofield/odoo,kybriainfotech/iSocioCRM,arthru/OpenUpgrade,optima-ict/odoo,hanicker/odoo,blaggacao/OpenUpgrade,goliveirab/odoo,provaleks/o8,hassoon3/odoo,charbeljc/OCB,frouty/odoogoeen,Grirrane/odoo,dsfsdgsbngfggb/odoo,OpenPymeMx/OCB,Antiun/odoo,janocat/odoo,x111ong/odoo,sinbazhou/odoo,gavin-feng/odoo,Kilhog/odoo,alexcuellar/odoo,waytai/odoo,sadleader/odoo,srimai/odoo,sergio-incaser/odoo,Elico-Corp/odoo_OCB,nhomar/odoo,bakhtout/odoo-educ,storm-computers/odoo,abenzbiria/clients_odoo,jfpla/odoo,joshuajan/odoo,odootr/odoo,apanju/GMIO_Odoo,srimai/odoo,OpenUpgrade-dev/OpenUpgrade,tarzan0820/odoo,tvibliani/odoo,abdellatifkarroum/odoo,0k/odoo,zchking/odoo,tinkerthaler/odoo,xujb/odoo,hopeall/odoo,hassoon3/odoo,Ichag/odoo,aviciimaxwell/odoo,inspyration/odoo,srsman/odoo,fgesora/odoo,TRESCLOUD/odoopub,bobisme/odoo,bakhtout/odoo-educ,virgree/odoo,bkirui/odoo,savoirfairelinux/OpenUpgrade,rowemoore/odoo,grap/OpenUpgrade,gdgellatly/OCB1,grap/OCB,hmen89/odoo,havt/odoo,KontorConsulting/odoo,NeovaHealth/odoo,nitinitprof/odoo,salaria/odoo,SerpentCS/odoo,pplatek/odoo,realsaiko/odoo,tarzan0820/odoo,KontorConsulting/odoo,xujb/odoo,codekaki/odoo,stephen144/odoo,x111ong/odoo,funkring/fdoo,idncom/odoo,cysnake4713/odoo,ramitalat/odoo,jiangzhixiao/odoo,hoatle/odoo,kittiu/odoo,hip-odoo/odoo,Drooids/odoo,ApuliaSoftware/odoo,jeasoft/odoo,oliverhr/odoo,omprakasha/odoo,aviciimaxwell/odoo,realsaiko/odoo,jiachenning/odoo,stephen144/odoo,rgeleta/odoo,dllsf/odootest,odooindia/odoo,0k/OpenUpgrade,sebalix/OpenUpgrade,NeovaHealth/odoo,JGarcia-Panach/odoo,OpenUpgrade/OpenUpgrade,Ernesto99/odoo,factorlibre/OCB,csrocha/OpenUpgrade,mszewczy/odoo,pedrobaeza/odoo,lightcn/odoo,hopeall/odoo,fuhongliang/odoo,elmerdpadilla/iv,Bachaco-ve/odoo,dkubiak789/odoo,xzYue/odoo,doomsterinc/odoo,Antiun/odoo,odoousers2014/odoo,xujb/odoo,OSSESAC/odoopubarquiluz,idncom/odoo,Elico-Corp/odoo_OCB,Adel-Magebinary/odoo,cdrooom/odoo,Gitlab11/odoo,PongPi/isl-odoo,pedrobaeza/OpenUpgrade,nitinitprof/odoo,synconics/odoo,apanju/GMIO_Odoo,vnsofthe/odoo,fossoult/odoo,Maspear/odoo,makinacorpus/odoo,nuncjo/odoo,FlorianLudwig/odoo,dfang/odoo,zchking/odoo,minhtuancn/odoo,csrocha/OpenUpgrade,gorjuce/odoo,sinbazhou/odoo,grap/OpenUpgrade,leoliujie/odoo,pedrobaeza/OpenUpgrade,feroda/odoo,acshan/odoo,ApuliaSoftware/odoo,vrenaville/ngo-addons-backport,sebalix/OpenUpgrade,nuuuboo/odoo,gorjuce/odoo,fgesora/odoo,camptocamp/ngo-addons-backport,bkirui/odoo,rschnapka/odoo,ygol/odoo,dkubiak789/odoo,odoousers2014/odoo,cloud9UG/odoo,hmen89/odoo,pplatek/odoo,bobisme/odoo,luistorresm/odoo,aviciimaxwell/odoo,n0m4dz/odoo,lgscofield/odoo,cysnake4713/odoo,CopeX/odoo,thanhacun/odoo,JCA-Developpement/Odoo,apanju/GMIO_Odoo,shingonoide/odoo,Antiun/odoo,hifly/OpenUpgrade,stephen144/odoo,highco-groupe/odoo,nagyistoce/odoo-dev-odoo,oliverhr/odoo,podemos-info/odoo,SAM-IT-SA/odoo,jolevq/odoopub,colinnewell/odoo,colinnewell/odoo,OpenUpgrade-dev/OpenUpgrade,markeTIC/OCB,sadleader/odoo,apocalypsebg/odoo,Gitlab11/odoo,fuhongliang/odoo,cysnake4713/odoo,x111ong/odoo,bwrsandman/OpenUpgrade,realsaiko/odoo,datenbetrieb/odoo,alexcuellar/odoo,fdvarela/odoo8,Adel-Magebinary/odoo,klunwebale/odoo,pedrobaeza/odoo,codekaki/odoo,xzYue/odoo,odoo-turkiye/odoo,Noviat/odoo,ChanduERP/odoo,AuyaJackie/odoo,gvb/odoo,jfpla/odoo,sysadminmatmoz/OCB,papouso/odoo,rubencabrera/odoo,jiachenning/odoo,eino-makitalo/odoo,camptocamp/ngo-addons-backport,sve-odoo/odoo,osvalr/odoo,janocat/odoo,virgree/odoo,Antiun/odoo,SAM-IT-SA/odoo,tvtsoft/odoo8,nitinitprof/odoo,JGarcia-Panach/odoo,spadae22/odoo,Codefans-fan/odoo,christophlsa/odoo,collex100/odoo,gorjuce/odoo,spadae22/odoo,guewen/OpenUpgrade,goliveirab/odoo,shaufi10/odoo,incaser/odoo-odoo,bealdav/OpenUpgrade,idncom/odoo,microcom/odoo,osvalr/odoo,ojengwa/odoo,alexcuellar/odoo,klunwebale/odoo,funkring/fdoo,highco-groupe/odoo,ccomb/OpenUpgrade,brijeshkesariya/odoo,ramitalat/odoo,idncom/odoo,makinacorpus/odoo,savoirfairelinux/OpenUpgrade,hopeall/odoo,gdgellatly/OCB1,hifly/OpenUpgrade,nexiles/odoo,doomsterinc/odoo,Kilhog/odoo,jesramirez/odoo,jolevq/odoopub,luiseduardohdbackup/odoo,Codefans-fan/odoo,steedos/odoo,fgesora/odoo,charbeljc/OCB,prospwro/odoo,ecosoft-odoo/odoo,BT-ojossen/odoo,storm-computers/odoo,jfpla/odoo,CopeX/odoo,jiangzhixiao/odoo,VitalPet/odoo,n0m4dz/odoo,fuhongliang/odoo,laslabs/odoo,grap/OpenUpgrade,tinkhaven-organization/odoo,cloud9UG/odoo,ecosoft-odoo/odoo,provaleks/o8,mszewczy/odoo,OpenUpgrade/OpenUpgrade,wangjun/odoo,ihsanudin/odoo,slevenhagen/odoo-npg,zchking/odoo,JCA-Developpement/Odoo,janocat/odoo,thanhacun/odoo,dfang/odoo,CatsAndDogsbvba/odoo,fjbatresv/odoo,oihane/odoo,eino-makitalo/odoo,sv-dev1/odoo,spadae22/odoo,joariasl/odoo,BT-rmartin/odoo,bobisme/odoo,eino-makitalo/odoo,hbrunn/OpenUpgrade,doomsterinc/odoo,frouty/odoogoeen,minhtuancn/odoo,abstract-open-solutions/OCB,gavin-feng/odoo,grap/OCB,dezynetechnologies/odoo,jolevq/odoopub,GauravSahu/odoo,tangyiyong/odoo,gorjuce/odoo,feroda/odoo,optima-ict/odoo,Bachaco-ve/odoo,mkieszek/odoo,ehirt/odoo,salaria/odoo,odoo-turkiye/odoo,Bachaco-ve/odoo,csrocha/OpenUpgrade,luiseduardohdbackup/odoo,frouty/odoo_oph,ccomb/OpenUpgrade,BT-astauder/odoo,steedos/odoo,jpshort/odoo,chiragjogi/odoo,Elico-Corp/odoo_OCB,leoliujie/odoo,janocat/odoo,acshan/odoo,demon-ru/iml-crm,JonathanStein/odoo,oasiswork/odoo,syci/OCB,gvb/odoo,Ichag/odoo,srsman/odoo,n0m4dz/odoo,dariemp/odoo,nuncjo/odoo,mustafat/odoo-1,shingonoide/odoo,odootr/odoo,jaxkodex/odoo,stephen144/odoo,dariemp/odoo,csrocha/OpenUpgrade,papouso/odoo,rgeleta/odoo,Maspear/odoo,GauravSahu/odoo,xzYue/odoo,OpusVL/odoo,Danisan/odoo-1,gsmartway/odoo,fuselock/odoo,srsman/odoo,odoo-turkiye/odoo,mustafat/odoo-1,alhashash/odoo,dariemp/odoo,hmen89/odoo,lgscofield/odoo,juanalfonsopr/odoo,grap/OpenUpgrade,pplatek/odoo,slevenhagen/odoo,wangjun/odoo,Danisan/odoo-1,frouty/odoogoeen,Ichag/odoo,CubicERP/odoo,damdam-s/OpenUpgrade,damdam-s/OpenUpgrade,nhomar/odoo-mirror,kirca/OpenUpgrade,tangyiyong/odoo,arthru/OpenUpgrade,joariasl/odoo,ehirt/odoo,pedrobaeza/OpenUpgrade,VielSoft/odoo,odootr/odoo,florentx/OpenUpgrade,florian-dacosta/OpenUpgrade,ojengwa/odoo,zchking/odoo,glovebx/odoo,gavin-feng/odoo,Endika/OpenUpgrade,RafaelTorrealba/odoo,mvaled/OpenUpgrade,nhomar/odoo,Noviat/odoo,SAM-IT-SA/odoo,jaxkodex/odoo,nhomar/odoo,codekaki/odoo,podemos-info/odoo,guewen/OpenUpgrade,factorlibre/OCB,colinnewell/odoo,shaufi10/odoo,charbeljc/OCB,odootr/odoo,hoatle/odoo,bplancher/odoo,ubic135/odoo-design,ApuliaSoftware/odoo,draugiskisprendimai/odoo,fjbatresv/odoo,osvalr/odoo,joshuajan/odoo,leorochael/odoo,eino-makitalo/odoo,rgeleta/odoo,arthru/OpenUpgrade,srimai/odoo,fgesora/odoo,gorjuce/odoo,Gitlab11/odoo,guewen/OpenUpgrade,joariasl/odoo,windedge/odoo,poljeff/odoo,apocalypsebg/odoo,nitinitprof/odoo,hoatle/odoo,Endika/OpenUpgrade,jesramirez/odoo,NL66278/OCB,lightcn/odoo,christophlsa/odoo,Codefans-fan/odoo,ThinkOpen-Solutions/odoo,ramitalat/odoo,hanicker/odoo,JonathanStein/odoo,gvb/odoo,poljeff/odoo,dllsf/odootest,mlaitinen/odoo,matrixise/odoo,sergio-incaser/odoo,bobisme/odoo,Danisan/odoo-1,kifcaliph/odoo,lightcn/odoo,shingonoide/odoo,hassoon3/odoo,guewen/OpenUpgrade,camptocamp/ngo-addons-backport,abstract-open-solutions/OCB,codekaki/odoo,Maspear/odoo,andreparames/odoo,laslabs/odoo,codekaki/odoo,nagyistoce/odoo-dev-odoo,juanalfonsopr/odoo,shaufi/odoo,cloud9UG/odoo,sebalix/OpenUpgrade,hifly/OpenUpgrade,odooindia/odoo,BT-ojossen/odoo,bkirui/odoo,ingadhoc/odoo,ovnicraft/odoo,jfpla/odoo,Grirrane/odoo,Daniel-CA/odoo,jiangzhixiao/odoo,javierTerry/odoo,kittiu/odoo,nuuuboo/odoo,shaufi/odoo,luistorresm/odoo,srsman/odoo,mvaled/OpenUpgrade,naousse/odoo,simongoffin/website_version,tinkhaven-organization/odoo,bguillot/OpenUpgrade,apanju/GMIO_Odoo,FlorianLudwig/odoo,nhomar/odoo-mirror,AuyaJackie/odoo,dkubiak789/odoo,mszewczy/odoo,draugiskisprendimai/odoo,highco-groupe/odoo,markeTIC/OCB,doomsterinc/odoo,ecosoft-odoo/odoo,eino-makitalo/odoo,ThinkOpen-Solutions/odoo,OpenPymeMx/OCB,alhashash/odoo,Gitlab11/odoo,podemos-info/odoo,kybriainfotech/iSocioCRM,frouty/odoogoeen,OSSESAC/odoopubarquiluz,gdgellatly/OCB1,erkrishna9/odoo,ovnicraft/odoo,mmbtba/odoo,OpenUpgrade-dev/OpenUpgrade,jusdng/odoo,avoinsystems/odoo,naousse/odoo,elmerdpadilla/iv,dsfsdgsbngfggb/odoo,fuselock/odoo,pedrobaeza/OpenUpgrade,luiseduardohdbackup/odoo,JonathanStein/odoo,hanicker/odoo,ujjwalwahi/odoo,nuuuboo/odoo,Noviat/odoo,luiseduardohdbackup/odoo,Elico-Corp/odoo_OCB,jiangzhixiao/odoo,windedge/odoo,Antiun/odoo,xujb/odoo,minhtuancn/odoo,erkrishna9/odoo,Nowheresly/odoo,mszewczy/odoo,klunwebale/odoo,rahuldhote/odoo,cdrooom/odoo,andreparames/odoo,idncom/odoo,VitalPet/odoo,Daniel-CA/odoo,demon-ru/iml-crm,guerrerocarlos/odoo,guewen/OpenUpgrade,luistorresm/odoo,Endika/odoo,klunwebale/odoo,gavin-feng/odoo,dariemp/odoo,shaufi10/odoo,highco-groupe/odoo,MarcosCommunity/odoo,nexiles/odoo,0k/OpenUpgrade,slevenhagen/odoo-npg,poljeff/odoo,makinacorpus/odoo,CubicERP/odoo,hip-odoo/odoo,ShineFan/odoo,ChanduERP/odoo,KontorConsulting/odoo,grap/OpenUpgrade,oihane/odoo,gsmartway/odoo,juanalfonsopr/odoo,Endika/OpenUpgrade,dsfsdgsbngfggb/odoo,abstract-open-solutions/OCB,jiachenning/odoo,funkring/fdoo,kirca/OpenUpgrade,Maspear/odoo,hubsaysnuaa/odoo,havt/odoo,gorjuce/odoo,sv-dev1/odoo,dgzurita/odoo,draugiskisprendimai/odoo,javierTerry/odoo,rowemoore/odoo,abenzbiria/clients_odoo,stonegithubs/odoo,Bachaco-ve/odoo,rdeheele/odoo,zchking/odoo,sergio-incaser/odoo,ccomb/OpenUpgrade,alexcuellar/odoo,ChanduERP/odoo,glovebx/odoo,avoinsystems/odoo,demon-ru/iml-crm,slevenhagen/odoo-npg,shaufi/odoo,0k/OpenUpgrade,nexiles/odoo,mkieszek/odoo,lightcn/odoo,alhashash/odoo,factorlibre/OCB,optima-ict/odoo,avoinsystems/odoo,rschnapka/odoo,dsfsdgsbngfggb/odoo,fuhongliang/odoo,cedk/odoo,fjbatresv/odoo,shaufi/odoo,bguillot/OpenUpgrade,ecosoft-odoo/odoo,Maspear/odoo,dkubiak789/odoo,kirca/OpenUpgrade,frouty/odoogoeen,steedos/odoo,takis/odoo,Endika/odoo,fossoult/odoo,MarcosCommunity/odoo,poljeff/odoo,bobisme/odoo,nuncjo/odoo,lgscofield/odoo,sysadminmatmoz/OCB,ChanduERP/odoo,apanju/odoo,sv-dev1/odoo,dezynetechnologies/odoo,dkubiak789/odoo,SAM-IT-SA/odoo,collex100/odoo,0k/odoo,tvibliani/odoo,Nick-OpusVL/odoo,gvb/odoo,blaggacao/OpenUpgrade,FlorianLudwig/odoo,gdgellatly/OCB1,virgree/odoo,Eric-Zhong/odoo,cpyou/odoo,alqfahad/odoo,Maspear/odoo,minhtuancn/odoo,mustafat/odoo-1,acshan/odoo,mkieszek/odoo,MarcosCommunity/odoo,Ernesto99/odoo,Ichag/odoo,virgree/odoo,feroda/odoo,hassoon3/odoo,sebalix/OpenUpgrade,spadae22/odoo,javierTerry/odoo,lightcn/odoo,apanju/GMIO_Odoo,Nowheresly/odoo,credativUK/OCB,ramadhane/odoo,kirca/OpenUpgrade,prospwro/odoo,provaleks/o8,dalegregory/odoo,n0m4dz/odoo,hifly/OpenUpgrade,0k/odoo,Ernesto99/odoo,ehirt/odoo,guerrerocarlos/odoo,SAM-IT-SA/odoo,leoliujie/odoo,Danisan/odoo-1,dalegregory/odoo,cpyou/odoo,havt/odoo,Adel-Magebinary/odoo,ujjwalwahi/odoo,Ernesto99/odoo,n0m4dz/odoo,KontorConsulting/odoo,Endika/odoo,rschnapka/odoo,apanju/GMIO_Odoo,apocalypsebg/odoo,FlorianLudwig/odoo,vrenaville/ngo-addons-backport,bakhtout/odoo-educ,florian-dacosta/OpenUpgrade,blaggacao/OpenUpgrade,lightcn/odoo,rschnapka/odoo,tinkerthaler/odoo,gavin-feng/odoo,dalegregory/odoo,hbrunn/OpenUpgrade,alexcuellar/odoo,BT-fgarbely/odoo,jeasoft/odoo,slevenhagen/odoo,damdam-s/OpenUpgrade,camptocamp/ngo-addons-backport,VielSoft/odoo,camptocamp/ngo-addons-backport,codekaki/odoo,juanalfonsopr/odoo,ehirt/odoo,apocalypsebg/odoo,tangyiyong/odoo,mmbtba/odoo,fevxie/odoo,ingadhoc/odoo,alqfahad/odoo,jpshort/odoo,ShineFan/odoo,cloud9UG/odoo,pedrobaeza/OpenUpgrade,synconics/odoo,tinkhaven-organization/odoo,syci/OCB,slevenhagen/odoo,ujjwalwahi/odoo,Codefans-fan/odoo,ehirt/odoo,jpshort/odoo,Ernesto99/odoo,factorlibre/OCB,christophlsa/odoo,NL66278/OCB,ShineFan/odoo,fdvarela/odoo8,bakhtout/odoo-educ,jolevq/odoopub,incaser/odoo-odoo,Endika/OpenUpgrade,vrenaville/ngo-addons-backport,deKupini/erp,waytai/odoo,SerpentCS/odoo,pplatek/odoo,tvibliani/odoo,florentx/OpenUpgrade,alqfahad/odoo,srimai/odoo,gdgellatly/OCB1,feroda/odoo,shaufi10/odoo,addition-it-solutions/project-all,sve-odoo/odoo,thanhacun/odoo,tarzan0820/odoo,sve-odoo/odoo,chiragjogi/odoo,damdam-s/OpenUpgrade,Noviat/odoo,mlaitinen/odoo,Bachaco-ve/odoo,ThinkOpen-Solutions/odoo,CopeX/odoo,papouso/odoo,CopeX/odoo,rgeleta/odoo,frouty/odoo_oph,oihane/odoo,SerpentCS/odoo,kittiu/odoo,microcom/odoo,QianBIG/odoo,addition-it-solutions/project-all,Drooids/odoo,KontorConsulting/odoo,pplatek/odoo,joshuajan/odoo,naousse/odoo,0k/OpenUpgrade,ehirt/odoo,SerpentCS/odoo,nuuuboo/odoo,storm-computers/odoo,pedrobaeza/odoo,fgesora/odoo,savoirfairelinux/odoo,bealdav/OpenUpgrade,QianBIG/odoo,savoirfairelinux/OpenUpgrade,bguillot/OpenUpgrade,GauravSahu/odoo,hanicker/odoo,lgscofield/odoo,JGarcia-Panach/odoo,alexteodor/odoo,poljeff/odoo,jusdng/odoo,dezynetechnologies/odoo,hubsaysnuaa/odoo,BT-fgarbely/odoo,lsinfo/odoo,inspyration/odoo,leorochael/odoo,BT-astauder/odoo,ubic135/odoo-design,MarcosCommunity/odoo,abstract-open-solutions/OCB,lsinfo/odoo,naousse/odoo,ojengwa/odoo,fjbatresv/odoo,avoinsystems/odoo,abstract-open-solutions/OCB,christophlsa/odoo,virgree/odoo,elmerdpadilla/iv,rubencabrera/odoo,BT-fgarbely/odoo,highco-groupe/odoo,Drooids/odoo,minhtuancn/odoo,mkieszek/odoo,odootr/odoo,deKupini/erp,feroda/odoo,windedge/odoo,bwrsandman/OpenUpgrade,CatsAndDogsbvba/odoo,fgesora/odoo,oasiswork/odoo,havt/odoo,simongoffin/website_version,acshan/odoo,Gitlab11/odoo,leorochael/odoo,apanju/odoo,diagramsoftware/odoo,jpshort/odoo,Gitlab11/odoo,podemos-info/odoo,ThinkOpen-Solutions/odoo,steedos/odoo,mszewczy/odoo,nuncjo/odoo,havt/odoo,shivam1111/odoo,jiangzhixiao/odoo,kybriainfotech/iSocioCRM,takis/odoo,demon-ru/iml-crm,goliveirab/odoo,collex100/odoo,dgzurita/odoo,ClearCorp-dev/odoo,jaxkodex/odoo,hanicker/odoo,nhomar/odoo-mirror,rdeheele/odoo,cpyou/odoo,xzYue/odoo,bealdav/OpenUpgrade,alexteodor/odoo,mszewczy/odoo,nuuuboo/odoo,slevenhagen/odoo-npg,laslabs/odoo,podemos-info/odoo,juanalfonsopr/odoo,patmcb/odoo,frouty/odoogoeen,jiachenning/odoo,javierTerry/odoo,tinkhaven-organization/odoo,0k/OpenUpgrade,collex100/odoo,MarcosCommunity/odoo,frouty/odoo_oph,simongoffin/website_version,fossoult/odoo,goliveirab/odoo,florentx/OpenUpgrade,agrista/odoo-saas,PongPi/isl-odoo,jpshort/odoo,alexteodor/odoo,jeasoft/odoo,synconics/odoo,GauravSahu/odoo,kirca/OpenUpgrade,rahuldhote/odoo,dariemp/odoo,Eric-Zhong/odoo,grap/OCB,Endika/OpenUpgrade,fdvarela/odoo8,stonegithubs/odoo,ihsanudin/odoo,osvalr/odoo,microcom/odoo,OpenUpgrade/OpenUpgrade,collex100/odoo,microcom/odoo,pedrobaeza/OpenUpgrade,0k/odoo,cdrooom/odoo,VielSoft/odoo,numerigraphe/odoo,ShineFan/odoo,wangjun/odoo,n0m4dz/odoo,sysadminmatmoz/OCB,alhashash/odoo,florian-dacosta/OpenUpgrade,x111ong/odoo,salaria/odoo,NeovaHealth/odoo,cdrooom/odoo,OpusVL/odoo,grap/OCB,rubencabrera/odoo,Noviat/odoo,stonegithubs/odoo,ThinkOpen-Solutions/odoo,diagramsoftware/odoo,ccomb/OpenUpgrade,JCA-Developpement/Odoo,NeovaHealth/odoo,tvibliani/odoo,JCA-Developpement/Odoo,blaggacao/OpenUpgrade,grap/OCB,oasiswork/odoo,Noviat/odoo,credativUK/OCB,fossoult/odoo,hanicker/odoo,odooindia/odoo,shivam1111/odoo,MarcosCommunity/odoo,nhomar/odoo,tvtsoft/odoo8,mlaitinen/odoo,glovebx/odoo,vrenaville/ngo-addons-backport,glovebx/odoo,naousse/odoo,sadleader/odoo,hubsaysnuaa/odoo,leoliujie/odoo,tinkhaven-organization/odoo,wangjun/odoo,Endika/odoo,ramitalat/odoo,jesramirez/odoo,odoo-turkiye/odoo,kybriainfotech/iSocioCRM,srimai/odoo,CubicERP/odoo,pplatek/odoo,bobisme/odoo,rowemoore/odoo,incaser/odoo-odoo,guewen/OpenUpgrade,vrenaville/ngo-addons-backport,simongoffin/website_version,OpenPymeMx/OCB,osvalr/odoo,feroda/odoo,ujjwalwahi/odoo,glovebx/odoo,nexiles/odoo,Eric-Zhong/odoo,prospwro/odoo,nagyistoce/odoo-dev-odoo,bwrsandman/OpenUpgrade,ecosoft-odoo/odoo,patmcb/odoo,Kilhog/odoo,charbeljc/OCB,CatsAndDogsbvba/odoo,dalegregory/odoo,draugiskisprendimai/odoo,charbeljc/OCB,florentx/OpenUpgrade,VitalPet/odoo,AuyaJackie/odoo,draugiskisprendimai/odoo,ecosoft-odoo/odoo,abstract-open-solutions/OCB,fdvarela/odoo8,KontorConsulting/odoo,wangjun/odoo,addition-it-solutions/project-all,dgzurita/odoo,ApuliaSoftware/odoo,damdam-s/OpenUpgrade,Kilhog/odoo,lombritz/odoo,provaleks/o8,rahuldhote/odoo,Codefans-fan/odoo,BT-ojossen/odoo,bkirui/odoo,gsmartway/odoo,Eric-Zhong/odoo,collex100/odoo,jaxkodex/odoo,frouty/odoo_oph,NL66278/OCB,ovnicraft/odoo,savoirfairelinux/odoo,sadleader/odoo,Danisan/odoo-1,dalegregory/odoo,Antiun/odoo,dsfsdgsbngfggb/odoo,lsinfo/odoo,jeasoft/odoo,cedk/odoo,hopeall/odoo,TRESCLOUD/odoopub,kifcaliph/odoo,dfang/odoo,factorlibre/OCB,hoatle/odoo,bguillot/OpenUpgrade,codekaki/odoo,gsmartway/odoo,numerigraphe/odoo,ehirt/odoo,nuncjo/odoo,laslabs/odoo,makinacorpus/odoo,ygol/odoo,Daniel-CA/odoo,incaser/odoo-odoo,thanhacun/odoo,oihane/odoo,gdgellatly/OCB1,leoliujie/odoo,Ernesto99/odoo,apocalypsebg/odoo,fuselock/odoo,dezynetechnologies/odoo,CubicERP/odoo,alqfahad/odoo,wangjun/odoo,omprakasha/odoo,markeTIC/OCB,andreparames/odoo,RafaelTorrealba/odoo,idncom/odoo,shaufi10/odoo,takis/odoo,agrista/odoo-saas,ccomb/OpenUpgrade,jpshort/odoo,lombritz/odoo,odoousers2014/odoo,spadae22/odoo,rgeleta/odoo,CubicERP/odoo,nagyistoce/odoo-dev-odoo,VitalPet/odoo,savoirfairelinux/odoo,JonathanStein/odoo,deKupini/erp,hip-odoo/odoo,rschnapka/odoo,BT-fgarbely/odoo,leorochael/odoo,provaleks/o8,takis/odoo,fjbatresv/odoo,cloud9UG/odoo,mvaled/OpenUpgrade,jaxkodex/odoo,idncom/odoo,datenbetrieb/odoo,hubsaysnuaa/odoo,mlaitinen/odoo,rschnapka/odoo,sv-dev1/odoo,AuyaJackie/odoo,rubencabrera/odoo,dgzurita/odoo,grap/OpenUpgrade,aviciimaxwell/odoo,provaleks/o8,gdgellatly/OCB1,odoousers2014/odoo,Grirrane/odoo,Daniel-CA/odoo,joariasl/odoo,luistorresm/odoo,deKupini/erp,osvalr/odoo,BT-astauder/odoo,tvtsoft/odoo8,ygol/odoo,hbrunn/OpenUpgrade,bguillot/OpenUpgrade,ClearCorp-dev/odoo,nuncjo/odoo,lgscofield/odoo,ubic135/odoo-design,inspyration/odoo,guerrerocarlos/odoo,pedrobaeza/odoo,nuncjo/odoo,rowemoore/odoo,demon-ru/iml-crm,goliveirab/odoo
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], - "update_xml" : ["hr_contract_view.xml"], + "update_xml" : [ + "hr_contract_view.xml", + "hr_contract_security.xml" + ], "active": False, "installable": True }
Add hr_contract_security.xml file entry in update_xml section
## Code Before: { "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], "update_xml" : ["hr_contract_view.xml"], "active": False, "installable": True } ## Instruction: Add hr_contract_security.xml file entry in update_xml section ## Code After: { "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], "update_xml" : [ "hr_contract_view.xml", "hr_contract_security.xml" ], "active": False, "installable": True }
{ "name" : "Human Resources Contracts", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "depends" : ["hr"], "module": "", "description": """ Add all information on the employee form to manage contracts: * Martial status, * Security number, * Place of birth, birth date, ... You can assign several contracts per employee. """, "init_xml" : ["hr_contract_data.xml"], "demo_xml" : [], - "update_xml" : ["hr_contract_view.xml"], + "update_xml" : [ + "hr_contract_view.xml", + "hr_contract_security.xml" + ], "active": False, "installable": True }
cacbc6825be010f6b839c8d21392a43b8b7b938d
setup.py
setup.py
from distutils.core import setup setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], )
from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', long_description=read('README.rst'), author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], )
INclude README as long description.
INclude README as long description.
Python
bsd-3-clause
AugustH/pandocfilters,infotroph/pandocfilters,silvio/pandocfilters,alycosta/pandocfilters,timtylin/scholdoc-filters,jgm/pandocfilters
from distutils.core import setup + + def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', + long_description=read('README.rst'), author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], )
INclude README as long description.
## Code Before: from distutils.core import setup setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], ) ## Instruction: INclude README as long description. ## Code After: from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', long_description=read('README.rst'), author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], )
from distutils.core import setup + + def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + setup(name='pandocfilters', version='1.0', description='Utilities for writing pandoc filters in python', + long_description=read('README.rst'), author='John MacFarlane', author_email='[email protected]', url='http://github.com/jgm/pandocfilters', py_modules=['pandocfilters'], keywords=['pandoc'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters' ], )
ef4c9f6a2e6fc1db01d93d937d24e444b0bb0ede
tests/memory_profiling.py
tests/memory_profiling.py
import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): # Skip the first half to get rid of the build up period and the last since it seems # a little less precise samples = samples[int(len(samples)/2):len(samples)-1] return not samples.count(samples[0]) > len(samples) - 2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests()
import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): # Skip the first samples to get rid of the build up period and the last sample since it seems # a little less precise rising = 0 for i in range(5, len(samples)-1): if samples[i] < samples[i+1]: rising += 1 return (rising / float(len(samples) - 6)) > 0.2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests()
Improve memory error detection for less false positives
Improve memory error detection for less false positives
Python
mit
tobgu/pyrsistent,jkbjh/pyrsistent,Futrell/pyrsistent,tobgu/pyrsistent,jml/pyrsistent,jml/pyrsistent,tobgu/pyrsistent,jkbjh/pyrsistent,Futrell/pyrsistent,jkbjh/pyrsistent,Futrell/pyrsistent,jml/pyrsistent
import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): - # Skip the first half to get rid of the build up period and the last since it seems + # Skip the first samples to get rid of the build up period and the last sample since it seems # a little less precise - samples = samples[int(len(samples)/2):len(samples)-1] - return not samples.count(samples[0]) > len(samples) - 2 + rising = 0 + for i in range(5, len(samples)-1): + if samples[i] < samples[i+1]: + rising += 1 + + return (rising / float(len(samples) - 6)) > 0.2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests()
Improve memory error detection for less false positives
## Code Before: import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): # Skip the first half to get rid of the build up period and the last since it seems # a little less precise samples = samples[int(len(samples)/2):len(samples)-1] return not samples.count(samples[0]) > len(samples) - 2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests() ## Instruction: Improve memory error detection for less false positives ## Code After: import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): # Skip the first samples to get rid of the build up period and the last sample since it seems # a little less precise rising = 0 for i in range(5, len(samples)-1): if samples[i] < samples[i+1]: rising += 1 return (rising / float(len(samples) - 6)) > 0.2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests()
import inspect import sys import time import memory_profiler import vector_test try: from pvectorc import pvector except ImportError: print("No C implementation of PVector available, terminating") sys.exit() PROFILING_DURATION = 2.0 def run_function(fn): stop = time.time() + PROFILING_DURATION while time.time() < stop: fn(pvector) def detect_memory_leak(samples): - # Skip the first half to get rid of the build up period and the last since it seems ? ^ ^ + # Skip the first samples to get rid of the build up period and the last sample since it seems ? ^ ++ ^^ +++++++ # a little less precise - samples = samples[int(len(samples)/2):len(samples)-1] - return not samples.count(samples[0]) > len(samples) - 2 + rising = 0 + for i in range(5, len(samples)-1): + if samples[i] < samples[i+1]: + rising += 1 + + return (rising / float(len(samples) - 6)) > 0.2 def profile_tests(): test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction) if fn[0].startswith('test_')] for name, fn in test_functions: # There are a couple of tests that are not run for the C implementation, skip those fn_args = inspect.getargspec(fn)[0] if 'pvector' in fn_args: print('Executing %s' % name) result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1) assert not detect_memory_leak(result), (name, result) if __name__ == "__main__": profile_tests()
052905dbff6f91740c8f8b9cb5e06aa07b06a186
tests/test_spicedham.py
tests/test_spicedham.py
import unittest from spicedham import spicedham class TestSpicedham(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main()
import os import json import tarfile import unittest from spicedham import SpicedHam class TestSpicedham(unittest.TestCase): def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'): if os.path.exists(test_data_dir): pass elif os.path.exists(tarball) : tarfile.open(tarball) tarfile.extractall() tarfile.close() else: raise 'No test data found' self.sh = SpicedHam() dir_name = os.path.join(test_data_dir, 'train', 'ham') for file_name in os.listdir(dir_name): data = json.load(open(os.path.join(dir_name, file_name))) self.sh.train(data, False) def test_on_training_data(self, test_data_dir='corpus'): self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True) self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False) def test_on_control_data(self, test_data_dir='corpus'): self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True) self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False) def _test_all_files_in_dir(self, data_dir, should_be_spam): tuning_factor = 0.5 for filename in os.listdir(data_dir): f = open(os.path.join(data_dir, filename), 'r') probability = self.sh.is_spam(json.load(f)) self.assertGreaterEqual(probability, 0.0) self.assertLessEqual(probability, 1.0) if should_be_spam: self.assertGreaterEqual(tuning_factor, 0.5) else: self.assertLessEqual(tuning_factor, 0.5) if __name__ == '__main__': unittest.main()
Add tests based off of the corpus.
Add tests based off of the corpus.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
- + import os + import json + import tarfile import unittest - from spicedham import spicedham + from spicedham import SpicedHam class TestSpicedham(unittest.TestCase): - def setUp(self): + def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'): + if os.path.exists(test_data_dir): - pass + pass + elif os.path.exists(tarball) : + tarfile.open(tarball) + tarfile.extractall() + tarfile.close() + else: + raise 'No test data found' + self.sh = SpicedHam() + dir_name = os.path.join(test_data_dir, 'train', 'ham') + for file_name in os.listdir(dir_name): + data = json.load(open(os.path.join(dir_name, file_name))) + self.sh.train(data, False) - def test_something(self): + def test_on_training_data(self, test_data_dir='corpus'): + self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True) + self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False) - pass + + def test_on_control_data(self, test_data_dir='corpus'): + self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True) + self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False) - def tearDown(self): - pass + def _test_all_files_in_dir(self, data_dir, should_be_spam): + tuning_factor = 0.5 + for filename in os.listdir(data_dir): + f = open(os.path.join(data_dir, filename), 'r') + probability = self.sh.is_spam(json.load(f)) + self.assertGreaterEqual(probability, 0.0) + self.assertLessEqual(probability, 1.0) + if should_be_spam: + self.assertGreaterEqual(tuning_factor, 0.5) + else: + self.assertLessEqual(tuning_factor, 0.5) if __name__ == '__main__': unittest.main() +
Add tests based off of the corpus.
## Code Before: import unittest from spicedham import spicedham class TestSpicedham(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main() ## Instruction: Add tests based off of the corpus. ## Code After: import os import json import tarfile import unittest from spicedham import SpicedHam class TestSpicedham(unittest.TestCase): def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'): if os.path.exists(test_data_dir): pass elif os.path.exists(tarball) : tarfile.open(tarball) tarfile.extractall() tarfile.close() else: raise 'No test data found' self.sh = SpicedHam() dir_name = os.path.join(test_data_dir, 'train', 'ham') for file_name in os.listdir(dir_name): data = json.load(open(os.path.join(dir_name, file_name))) self.sh.train(data, False) def test_on_training_data(self, test_data_dir='corpus'): self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True) self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False) def test_on_control_data(self, test_data_dir='corpus'): self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True) self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False) def _test_all_files_in_dir(self, data_dir, should_be_spam): tuning_factor = 0.5 for filename in os.listdir(data_dir): f = open(os.path.join(data_dir, filename), 'r') probability = self.sh.is_spam(json.load(f)) self.assertGreaterEqual(probability, 0.0) self.assertLessEqual(probability, 1.0) if should_be_spam: self.assertGreaterEqual(tuning_factor, 0.5) else: self.assertLessEqual(tuning_factor, 0.5) if __name__ == '__main__': unittest.main()
- + import os + import json + import tarfile import unittest - from spicedham import spicedham ? ^ ^ + from spicedham import SpicedHam ? ^ ^ class TestSpicedham(unittest.TestCase): - def setUp(self): + def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'): + if os.path.exists(test_data_dir): - pass + pass ? ++++ + elif os.path.exists(tarball) : + tarfile.open(tarball) + tarfile.extractall() + tarfile.close() + else: + raise 'No test data found' + self.sh = SpicedHam() + dir_name = os.path.join(test_data_dir, 'train', 'ham') + for file_name in os.listdir(dir_name): + data = json.load(open(os.path.join(dir_name, file_name))) + self.sh.train(data, False) - def test_something(self): + def test_on_training_data(self, test_data_dir='corpus'): + self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True) + self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False) - pass ? ---- + + def test_on_control_data(self, test_data_dir='corpus'): + self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True) + self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False) - def tearDown(self): - pass + def _test_all_files_in_dir(self, data_dir, should_be_spam): + tuning_factor = 0.5 + for filename in os.listdir(data_dir): + f = open(os.path.join(data_dir, filename), 'r') + probability = self.sh.is_spam(json.load(f)) + self.assertGreaterEqual(probability, 0.0) + self.assertLessEqual(probability, 1.0) + if should_be_spam: + self.assertGreaterEqual(tuning_factor, 0.5) + else: + self.assertLessEqual(tuning_factor, 0.5) if __name__ == '__main__': unittest.main()
a9c53bc97c0e62a959c1115ec61d0a28d71aac68
devtools/ci/update-versions.py
devtools/ci/update-versions.py
from __future__ import print_function import os import boto from boto.s3.key import Key import msmbuilder.version if msmbuilder.version.release: # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] BUCKET_NAME = 'msmbuilder.org' bucket_name = AWS_ACCESS_KEY_ID.lower() + '-' + BUCKET_NAME conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(BUCKET_NAME) root = 'doc/_build' versions = json.load(urllib2.urlopen('http://www.msmbuilder.org/versions.json')) # new release so all the others are now old for i in xrange(len(versions)): versions[i]['latest'] = False versions.append({'version' : msmbuilder.version.short_version, 'latest' : True}) k = Key(bucket) k.key = 'versions.json' k.set_contents_from_string(json.dumps(versions)) else: print("This is not a release.")
from __future__ import print_function import os import pip import json from tempfile import NamedTemporaryFile import subprocess from msmbuilder import version from six.moves.urllib.request import urlopen if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') URL = 'http://www.msmbuilder.org/versions.json' BUCKET_NAME = 'msmbuilder.org' if not version.release: print("This is not a release.") exit(0) versions = json.load(urlopen(URL)) # new release so all the others are now old for i in xrange(len(versions)): versions[i]['latest'] = False versions.append({ 'version': version.short_version, 'latest': True}) # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. with NamedTemporaryFile('w') as config, NamedTemporaryFile('w') as v: config.write('''[default] access_key = {AWS_ACCESS_KEY_ID} secret_key = {AWS_SECRET_ACCESS_KEY} '''.format(**os.environ)) json.dump(versions, v) config.flush() v.flush() template = ('s3cmd --config {config} ' 'put {vfile} s3://{bucket}/versions.json') cmd = template.format( config=config.name, vfile=v.name, bucket=BUCKET_NAME) subprocess.call(cmd.split())
Fix script for updating version dropdown
Fix script for updating version dropdown
Python
lgpl-2.1
mpharrigan/mixtape,brookehus/msmbuilder,peastman/msmbuilder,peastman/msmbuilder,rafwiewiora/msmbuilder,dr-nate/msmbuilder,dr-nate/msmbuilder,msmbuilder/msmbuilder,peastman/msmbuilder,Eigenstate/msmbuilder,Eigenstate/msmbuilder,msultan/msmbuilder,msultan/msmbuilder,rmcgibbo/msmbuilder,msmbuilder/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,rmcgibbo/msmbuilder,Eigenstate/msmbuilder,stephenliu1989/msmbuilder,dotsdl/msmbuilder,peastman/msmbuilder,cxhernandez/msmbuilder,stephenliu1989/msmbuilder,rafwiewiora/msmbuilder,mpharrigan/mixtape,rafwiewiora/msmbuilder,brookehus/msmbuilder,rmcgibbo/msmbuilder,mpharrigan/mixtape,Eigenstate/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,cxhernandez/msmbuilder,peastman/msmbuilder,msmbuilder/msmbuilder,rafwiewiora/msmbuilder,dotsdl/msmbuilder,cxhernandez/msmbuilder,msultan/msmbuilder,brookehus/msmbuilder,dotsdl/msmbuilder,mpharrigan/mixtape,dotsdl/msmbuilder,rmcgibbo/msmbuilder,rafwiewiora/msmbuilder,stephenliu1989/msmbuilder,stephenliu1989/msmbuilder,msmbuilder/msmbuilder,dr-nate/msmbuilder,Eigenstate/msmbuilder,mpharrigan/mixtape,dr-nate/msmbuilder,brookehus/msmbuilder,dr-nate/msmbuilder,msmbuilder/msmbuilder,brookehus/msmbuilder
from __future__ import print_function import os - import boto - from boto.s3.key import Key - import msmbuilder.version + import pip + import json + from tempfile import NamedTemporaryFile + import subprocess + from msmbuilder import version + from six.moves.urllib.request import urlopen + if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): + raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') + URL = 'http://www.msmbuilder.org/versions.json' - if msmbuilder.version.release: - # The secret key is available as a secure environment variable - # on travis-ci to push the build documentation to Amazon S3. - AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] - AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] - BUCKET_NAME = 'msmbuilder.org' + BUCKET_NAME = 'msmbuilder.org' + if not version.release: + print("This is not a release.") + exit(0) - bucket_name = AWS_ACCESS_KEY_ID.lower() + '-' + BUCKET_NAME - conn = boto.connect_s3(AWS_ACCESS_KEY_ID, - AWS_SECRET_ACCESS_KEY) - bucket = conn.get_bucket(BUCKET_NAME) - root = 'doc/_build' - versions = json.load(urllib2.urlopen('http://www.msmbuilder.org/versions.json')) + versions = json.load(urlopen(URL)) - # new release so all the others are now old + # new release so all the others are now old - for i in xrange(len(versions)): + for i in xrange(len(versions)): - versions[i]['latest'] = False + versions[i]['latest'] = False - versions.append({'version' : msmbuilder.version.short_version, 'latest' : True}) + versions.append({ + 'version': version.short_version, + 'latest': True}) - k = Key(bucket) - k.key = 'versions.json' - k.set_contents_from_string(json.dumps(versions)) - - else: - print("This is not a release.") + # The secret key is available as a secure environment variable + # on travis-ci to push the build documentation to Amazon S3. + with NamedTemporaryFile('w') as config, NamedTemporaryFile('w') as v: + config.write('''[default] + access_key = {AWS_ACCESS_KEY_ID} + secret_key = {AWS_SECRET_ACCESS_KEY} + '''.format(**os.environ)) + json.dump(versions, v) + config.flush() + v.flush() + template = ('s3cmd --config {config} ' + 'put {vfile} s3://{bucket}/versions.json') + cmd = template.format( + config=config.name, + vfile=v.name, + bucket=BUCKET_NAME) + subprocess.call(cmd.split()) +
Fix script for updating version dropdown
## Code Before: from __future__ import print_function import os import boto from boto.s3.key import Key import msmbuilder.version if msmbuilder.version.release: # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] BUCKET_NAME = 'msmbuilder.org' bucket_name = AWS_ACCESS_KEY_ID.lower() + '-' + BUCKET_NAME conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(BUCKET_NAME) root = 'doc/_build' versions = json.load(urllib2.urlopen('http://www.msmbuilder.org/versions.json')) # new release so all the others are now old for i in xrange(len(versions)): versions[i]['latest'] = False versions.append({'version' : msmbuilder.version.short_version, 'latest' : True}) k = Key(bucket) k.key = 'versions.json' k.set_contents_from_string(json.dumps(versions)) else: print("This is not a release.") ## Instruction: Fix script for updating version dropdown ## Code After: from __future__ import print_function import os import pip import json from tempfile import NamedTemporaryFile import subprocess from msmbuilder import version from six.moves.urllib.request import urlopen if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') URL = 'http://www.msmbuilder.org/versions.json' BUCKET_NAME = 'msmbuilder.org' if not version.release: print("This is not a release.") exit(0) versions = json.load(urlopen(URL)) # new release so all the others are now old for i in xrange(len(versions)): versions[i]['latest'] = False versions.append({ 'version': version.short_version, 'latest': True}) # The secret key is available as a secure environment variable # on travis-ci to push the build documentation to Amazon S3. with NamedTemporaryFile('w') as config, NamedTemporaryFile('w') as v: config.write('''[default] access_key = {AWS_ACCESS_KEY_ID} secret_key = {AWS_SECRET_ACCESS_KEY} '''.format(**os.environ)) json.dump(versions, v) config.flush() v.flush() template = ('s3cmd --config {config} ' 'put {vfile} s3://{bucket}/versions.json') cmd = template.format( config=config.name, vfile=v.name, bucket=BUCKET_NAME) subprocess.call(cmd.split())
from __future__ import print_function import os - import boto - from boto.s3.key import Key - import msmbuilder.version + import pip + import json + from tempfile import NamedTemporaryFile + import subprocess + from msmbuilder import version + from six.moves.urllib.request import urlopen + if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()): + raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd') + URL = 'http://www.msmbuilder.org/versions.json' - if msmbuilder.version.release: - # The secret key is available as a secure environment variable - # on travis-ci to push the build documentation to Amazon S3. - AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] - AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] - BUCKET_NAME = 'msmbuilder.org' ? ---- + BUCKET_NAME = 'msmbuilder.org' + if not version.release: + print("This is not a release.") + exit(0) - bucket_name = AWS_ACCESS_KEY_ID.lower() + '-' + BUCKET_NAME - conn = boto.connect_s3(AWS_ACCESS_KEY_ID, - AWS_SECRET_ACCESS_KEY) - bucket = conn.get_bucket(BUCKET_NAME) - root = 'doc/_build' - versions = json.load(urllib2.urlopen('http://www.msmbuilder.org/versions.json')) + versions = json.load(urlopen(URL)) - # new release so all the others are now old ? ---- + # new release so all the others are now old - for i in xrange(len(versions)): ? ---- + for i in xrange(len(versions)): - versions[i]['latest'] = False ? ---- + versions[i]['latest'] = False - versions.append({'version' : msmbuilder.version.short_version, 'latest' : True}) + versions.append({ + 'version': version.short_version, + 'latest': True}) - k = Key(bucket) - k.key = 'versions.json' - k.set_contents_from_string(json.dumps(versions)) - - else: - print("This is not a release.") + # The secret key is available as a secure environment variable + # on travis-ci to push the build documentation to Amazon S3. + with NamedTemporaryFile('w') as config, NamedTemporaryFile('w') as v: + config.write('''[default] + access_key = {AWS_ACCESS_KEY_ID} + secret_key = {AWS_SECRET_ACCESS_KEY} + '''.format(**os.environ)) + json.dump(versions, v) + config.flush() + v.flush() + + template = ('s3cmd --config {config} ' + 'put {vfile} s3://{bucket}/versions.json') + cmd = template.format( + config=config.name, + vfile=v.name, + bucket=BUCKET_NAME) + subprocess.call(cmd.split())
23501afd09b13d1e5f33bdd60614fd9ac7210108
oratioignoreparser.py
oratioignoreparser.py
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def extend_list(self, ignored_paths_list): self.ignored_paths.extend(ignored_paths_list) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
Add extend_list method to OratioIgnoreParser
Add extend_list method to OratioIgnoreParser To make oratioignoreparser.py easily testable using unit tests.
Python
mit
oratio-io/oratio-cli,oratio-io/oratio-cli
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) + + def extend_list(self, ignored_paths_list): + self.ignored_paths.extend(ignored_paths_list) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
Add extend_list method to OratioIgnoreParser
## Code Before: import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files ## Instruction: Add extend_list method to OratioIgnoreParser ## Code After: import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def extend_list(self, ignored_paths_list): self.ignored_paths.extend(ignored_paths_list) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) + + def extend_list(self, ignored_paths_list): + self.ignored_paths.extend(ignored_paths_list) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
a58e035027c732f519791fe587ddd509c7013344
mail/tests/handlers/react_tests.py
mail/tests/handlers/react_tests.py
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly")
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly") def test_react_for_user_project(): """ Then make sure that project react messages for existing user queued properly. """ dest_addr = "docs.index@test_user2.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing user queued properly")
Add tests for sending messages to "user" projects
Add tests for sending messages to "user" projects
Python
apache-2.0
heiths/allura,leotrubach/sourceforge-allura,lym/allura-git,lym/allura-git,apache/allura,leotrubach/sourceforge-allura,apache/incubator-allura,apache/allura,apache/incubator-allura,Bitergia/allura,Bitergia/allura,heiths/allura,lym/allura-git,apache/allura,lym/allura-git,leotrubach/sourceforge-allura,apache/incubator-allura,apache/allura,Bitergia/allura,leotrubach/sourceforge-allura,heiths/allura,Bitergia/allura,Bitergia/allura,apache/allura,apache/incubator-allura,heiths/allura,lym/allura-git,heiths/allura
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly") + def test_react_for_user_project(): + """ + Then make sure that project react messages for existing user queued properly. + """ + dest_addr = "docs.index@test_user2.%s" % host + client.begin() + client.say(dest_addr, "Test project react messages for existing user queued properly")
Add tests for sending messages to "user" projects
## Code Before: from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly") ## Instruction: Add tests for sending messages to "user" projects ## Code After: from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly") def test_react_for_user_project(): """ Then make sure that project react messages for existing user queued properly. """ dest_addr = "docs.index@test_user2.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing user queued properly")
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_project(): """ Then make sure that project react messages for existing project queued properly. """ dest_addr = "docs.index@test.%s" % host client.begin() client.say(dest_addr, "Test project react messages for existing project queued properly") def test_react_for_bad_project(): """ Then make sure that project react messages for non-existing project dropped properly. """ dest_addr = "docs.index@badproject.%s" % host client.begin() client.say(dest_addr, "Test project react messages for non-existing project dropped properly") + def test_react_for_user_project(): + """ + Then make sure that project react messages for existing user queued properly. + """ + dest_addr = "docs.index@test_user2.%s" % host + client.begin() + client.say(dest_addr, "Test project react messages for existing user queued properly")
65b7d1f1eafd32d3895e3ec15a559dca608b5c23
addons/sale_coupon/models/mail_compose_message.py
addons/sale_coupon/models/mail_compose_message.py
from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: self.env[wizard.model].browse(wizard.res_id).state = 'sent' return super().send_mail(**kwargs)
from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: # Mark coupon as sent in sudo, as helpdesk users don't have the right to write on coupons self.env[wizard.model].sudo().browse(wizard.res_id).state = 'sent' return super().send_mail(**kwargs)
Allow helpdesk users to send coupon by email
[IMP] sale_coupon: Allow helpdesk users to send coupon by email Purpose ======= Helpdesk users don't have the right to write on a coupon. When sending a coupon by email, the coupon is marked as 'sent'. Allow users to send coupons by executing the state change in sudo. closes odoo/odoo#45091 Taskid: 2179609 Related: odoo/enterprise#8143 Signed-off-by: Yannick Tivisse (yti) <[email protected]>
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: + # Mark coupon as sent in sudo, as helpdesk users don't have the right to write on coupons - self.env[wizard.model].browse(wizard.res_id).state = 'sent' + self.env[wizard.model].sudo().browse(wizard.res_id).state = 'sent' return super().send_mail(**kwargs)
Allow helpdesk users to send coupon by email
## Code Before: from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: self.env[wizard.model].browse(wizard.res_id).state = 'sent' return super().send_mail(**kwargs) ## Instruction: Allow helpdesk users to send coupon by email ## Code After: from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: # Mark coupon as sent in sudo, as helpdesk users don't have the right to write on coupons self.env[wizard.model].sudo().browse(wizard.res_id).state = 'sent' return super().send_mail(**kwargs)
from odoo import models class MailComposeMessage(models.TransientModel): _inherit = 'mail.compose.message' def send_mail(self, **kwargs): for wizard in self: if self._context.get('mark_coupon_as_sent') and wizard.model == 'sale.coupon' and wizard.partner_ids: + # Mark coupon as sent in sudo, as helpdesk users don't have the right to write on coupons - self.env[wizard.model].browse(wizard.res_id).state = 'sent' + self.env[wizard.model].sudo().browse(wizard.res_id).state = 'sent' ? +++++++ return super().send_mail(**kwargs)
8be551ad39f3aedff5ea0ceb536378ea0e851864
src/waldur_auth_openid/management/commands/import_openid_accounts.py
src/waldur_auth_openid/management/commands/import_openid_accounts.py
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() if not dry_run: for user in users: user.civil_number = '%s%s' % (country_code, user.civil_number) user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() for user in users: new_civil_number = '%s%s' % (country_code, user.civil_number) self.stdout.write('Username: %s, before: %s, after: %s' % ( user.username, user.civil_number, new_civil_number)) if not dry_run: user.civil_number = new_civil_number user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))
Print out civil_number before and after
Print out civil_number before and after [WAL-2172]
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() - if not dry_run: - for user in users: + for user in users: - user.civil_number = '%s%s' % (country_code, user.civil_number) + new_civil_number = '%s%s' % (country_code, user.civil_number) + self.stdout.write('Username: %s, before: %s, after: %s' % ( + user.username, user.civil_number, new_civil_number)) + if not dry_run: + user.civil_number = new_civil_number user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))
Print out civil_number before and after
## Code Before: from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() if not dry_run: for user in users: user.civil_number = '%s%s' % (country_code, user.civil_number) user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count)) ## Instruction: Print out civil_number before and after ## Code After: from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() for user in users: new_civil_number = '%s%s' % (country_code, user.civil_number) self.stdout.write('Username: %s, before: %s, after: %s' % ( user.username, user.civil_number, new_civil_number)) if not dry_run: user.civil_number = new_civil_number user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from waldur_core.core.utils import DryRunCommand User = get_user_model() class Command(DryRunCommand): help_text = 'Append civil number with country code for OpenID users.' def handle(self, dry_run, *args, **options): conf = settings.WALDUR_AUTH_OPENID country_code = conf['COUNTRY_CODE'] registration_method = conf['NAME'] with transaction.atomic(): users = User.objects.filter(registration_method=registration_method)\ .exclude(civil_number__startswith=country_code)\ .exclude(civil_number='') \ .exclude(civil_number=None) count = users.count() - if not dry_run: - for user in users: ? ---- + for user in users: - user.civil_number = '%s%s' % (country_code, user.civil_number) ? ^^^^^^ ^^ + new_civil_number = '%s%s' % (country_code, user.civil_number) ? ^ ^^ + self.stdout.write('Username: %s, before: %s, after: %s' % ( + user.username, user.civil_number, new_civil_number)) + if not dry_run: + user.civil_number = new_civil_number user.save(update_fields=['civil_number']) self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))
e7962ec34a86fe464862ab81ec8cc8da14a732f6
models/weather.py
models/weather.py
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())) except: update.message.reply_text('Location fucking not found')
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())+' 天氣狀況:'+str(w.get_status())) except: update.message.reply_text('Location fucking not found')
Add Info to Weather Check
Add Info to Weather Check Add current weather status to weather check features.
Python
mit
iGene/igene_bot
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ - ' 濕度:'+str(w.get_humidity())) + ' 濕度:'+str(w.get_humidity())+' 天氣狀況:'+str(w.get_status())) except: update.message.reply_text('Location fucking not found')
Add Info to Weather Check
## Code Before: from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())) except: update.message.reply_text('Location fucking not found') ## Instruction: Add Info to Weather Check ## Code After: from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())+' 天氣狀況:'+str(w.get_status())) except: update.message.reply_text('Location fucking not found')
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ - ' 濕度:'+str(w.get_humidity())) + ' 濕度:'+str(w.get_humidity())+' 天氣狀況:'+str(w.get_status())) ? +++++++++++++++++++++++++++++ ++ except: update.message.reply_text('Location fucking not found')
381ad771134a68f8b83277c2c91aeb199ba6ff96
telemetry/telemetry/web_perf/timeline_based_page_test.py
telemetry/telemetry/web_perf/timeline_based_page_test.py
from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__('RunPageInteractions') self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__() self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
Fix browser restart in TimelineBasedPageTest
[Telemetry] Fix browser restart in TimelineBasedPageTest The TimelineBasedPageTest constructor was passing in error a string where its parent constructor expects a Boolean value for the needs_browser_restart_after_each_page option. BUG=504368 Review URL: https://codereview.chromium.org/1206323002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#336188}
Python
bsd-3-clause
SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult
from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): - super(TimelineBasedPageTest, self).__init__('RunPageInteractions') + super(TimelineBasedPageTest, self).__init__() self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
Fix browser restart in TimelineBasedPageTest
## Code Before: from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__('RunPageInteractions') self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller) ## Instruction: Fix browser restart in TimelineBasedPageTest ## Code After: from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): super(TimelineBasedPageTest, self).__init__() self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
from telemetry.page import page_test class TimelineBasedPageTest(page_test.PageTest): """Page test that collects metrics with TimelineBasedMeasurement.""" def __init__(self, tbm): - super(TimelineBasedPageTest, self).__init__('RunPageInteractions') ? --------------------- + super(TimelineBasedPageTest, self).__init__() self._measurement = tbm @property def measurement(self): return self._measurement def WillNavigateToPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.WillRunUserStory( tracing_controller, page.GetSyntheticDelayCategories()) def ValidateAndMeasurePage(self, page, tab, results): """Collect all possible metrics and added them to results.""" tracing_controller = tab.browser.platform.tracing_controller self._measurement.Measure(tracing_controller, results) def CleanUpAfterPage(self, page, tab): tracing_controller = tab.browser.platform.tracing_controller self._measurement.DidRunUserStory(tracing_controller)
4420eb020d96004c5373584781c7b130de7b90e9
reg/__init__.py
reg/__init__.py
from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply
from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply from .sentinel import Sentinel
Make sentinel available to outside.
Make sentinel available to outside.
Python
bsd-3-clause
taschini/reg,morepath/reg
from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply + from .sentinel import Sentinel
Make sentinel available to outside.
## Code Before: from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply ## Instruction: Make sentinel available to outside. ## Code After: from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply from .sentinel import Sentinel
from .implicit import implicit, NoImplicitLookupError from .registry import ClassRegistry, Registry, IRegistry, IClassLookup from .lookup import Lookup, ComponentLookupError, Matcher from .predicate import (PredicateRegistry, Predicate, KeyIndex, PredicateRegistryError) from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup from .generic import generic from .mapply import mapply + from .sentinel import Sentinel
edec252d9a050ead0084280f9772f05a2a3d7608
preferences/forms.py
preferences/forms.py
from registration.forms import RegistrationFormUniqueEmail class RegistrationUserForm(RegistrationFormUniqueEmail): class Meta: model = User fields = ("email")
from django import forms from registration.forms import RegistrationFormUniqueEmail from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm(forms.ModelForm): class Meta: model = Preferences fields = ['representitive', 'senator', 'street_line1', 'street_line2', 'zipcode', 'city', 'state']
Add preferences form built off model
Add preferences form built off model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
+ from django import forms from registration.forms import RegistrationFormUniqueEmail - class RegistrationUserForm(RegistrationFormUniqueEmail): + from preferences.models import Preferences + # from django.forms import ModelForm + + # class RegistrationUserForm(RegistrationFormUniqueEmail): + + # class Meta: + # model = User + # fields = ("email") + + + class PreferencesForm(forms.ModelForm): class Meta: - model = User + model = Preferences - fields = ("email") + fields = ['representitive', 'senator', 'street_line1', 'street_line2', + 'zipcode', 'city', 'state']
Add preferences form built off model
## Code Before: from registration.forms import RegistrationFormUniqueEmail class RegistrationUserForm(RegistrationFormUniqueEmail): class Meta: model = User fields = ("email") ## Instruction: Add preferences form built off model ## Code After: from django import forms from registration.forms import RegistrationFormUniqueEmail from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm(forms.ModelForm): class Meta: model = Preferences fields = ['representitive', 'senator', 'street_line1', 'street_line2', 'zipcode', 'city', 'state']
+ from django import forms from registration.forms import RegistrationFormUniqueEmail - class RegistrationUserForm(RegistrationFormUniqueEmail): + from preferences.models import Preferences + # from django.forms import ModelForm + + # class RegistrationUserForm(RegistrationFormUniqueEmail): + + # class Meta: + # model = User + # fields = ("email") + + + class PreferencesForm(forms.ModelForm): class Meta: - model = User ? ^^ + model = Preferences ? ^^^^ +++++ - fields = ("email") + fields = ['representitive', 'senator', 'street_line1', 'street_line2', + 'zipcode', 'city', 'state']
09fa23adfb76f052473ee38de94ce4bdfdcc48e1
src/nodeconductor_assembly_waldur/packages/perms.py
src/nodeconductor_assembly_waldur/packages/perms.py
from nodeconductor.core.permissions import StaffPermissionLogic PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), ('packages.OpenStackPackage', StaffPermissionLogic(any_permission=True)), )
from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic from nodeconductor.structure import models as structure_models PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), ('packages.OpenStackPackage', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__service__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__service__customer__roles__role_type': structure_models.CustomerRole.OWNER}, ], any_permission=True, )), )
Allow customer owner to create packages
Allow customer owner to create packages - wal-26
Python
mit
opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur
- from nodeconductor.core.permissions import StaffPermissionLogic + from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic - + from nodeconductor.structure import models as structure_models PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), - ('packages.OpenStackPackage', StaffPermissionLogic(any_permission=True)), + ('packages.OpenStackPackage', FilteredCollaboratorsPermissionLogic( + collaborators_query=[ + 'tenant__service_project_link__service__customer__roles__permission_group__user', + ], + collaborators_filter=[ + {'tenant__service_project_link__service__customer__roles__role_type': structure_models.CustomerRole.OWNER}, + ], + any_permission=True, + )), )
Allow customer owner to create packages
## Code Before: from nodeconductor.core.permissions import StaffPermissionLogic PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), ('packages.OpenStackPackage', StaffPermissionLogic(any_permission=True)), ) ## Instruction: Allow customer owner to create packages ## Code After: from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic from nodeconductor.structure import models as structure_models PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), ('packages.OpenStackPackage', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__service__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__service__customer__roles__role_type': structure_models.CustomerRole.OWNER}, ], any_permission=True, )), )
- from nodeconductor.core.permissions import StaffPermissionLogic + from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic ? ++++++++++++++++++++++++++++++++++++++ - + from nodeconductor.structure import models as structure_models PERMISSION_LOGICS = ( ('packages.PackageTemplate', StaffPermissionLogic(any_permission=True)), ('packages.PackageComponent', StaffPermissionLogic(any_permission=True)), - ('packages.OpenStackPackage', StaffPermissionLogic(any_permission=True)), + ('packages.OpenStackPackage', FilteredCollaboratorsPermissionLogic( + collaborators_query=[ + 'tenant__service_project_link__service__customer__roles__permission_group__user', + ], + collaborators_filter=[ + {'tenant__service_project_link__service__customer__roles__role_type': structure_models.CustomerRole.OWNER}, + ], + any_permission=True, + )), )
32994f27d1644415e8cd4a22f1b47d4938d3620c
fulfil_client/oauth.py
fulfil_client/oauth.py
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain def create_authorization_url(self, redirect_uri, scope): self.redirect_uri = redirect_uri self.scope = scope return self.authorization_url(self.base_url + 'oauth/authorize') def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code )
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain def create_authorization_url(self, redirect_uri, scope, **kwargs): self.redirect_uri = redirect_uri self.scope = scope return self.authorization_url( self.base_url + 'oauth/authorize', **kwargs) def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code )
Add provision to pass extra args in auth url
Add provision to pass extra args in auth url
Python
isc
fulfilio/fulfil-python-api,sharoonthomas/fulfil-python-api
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain - def create_authorization_url(self, redirect_uri, scope): + def create_authorization_url(self, redirect_uri, scope, **kwargs): self.redirect_uri = redirect_uri self.scope = scope - return self.authorization_url(self.base_url + 'oauth/authorize') + return self.authorization_url( + self.base_url + 'oauth/authorize', **kwargs) def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code )
Add provision to pass extra args in auth url
## Code Before: from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain def create_authorization_url(self, redirect_uri, scope): self.redirect_uri = redirect_uri self.scope = scope return self.authorization_url(self.base_url + 'oauth/authorize') def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code ) ## Instruction: Add provision to pass extra args in auth url ## Code After: from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain def create_authorization_url(self, redirect_uri, scope, **kwargs): self.redirect_uri = redirect_uri self.scope = scope return self.authorization_url( self.base_url + 'oauth/authorize', **kwargs) def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code )
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and client_secret): raise Exception('Missing client_id or client_secret.') super(Session, self).__init__(client_id=client_id, **kwargs) @classmethod def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret @property def base_url(self): if self.fulfil_subdomain == 'localhost': return 'http://localhost:8000/' else: return 'https://%s.fulfil.io/' % self.fulfil_subdomain - def create_authorization_url(self, redirect_uri, scope): + def create_authorization_url(self, redirect_uri, scope, **kwargs): ? ++++++++++ self.redirect_uri = redirect_uri self.scope = scope - return self.authorization_url(self.base_url + 'oauth/authorize') + return self.authorization_url( + self.base_url + 'oauth/authorize', **kwargs) def get_token(self, code): token_url = self.base_url + 'oauth/token' return self.fetch_token( token_url, client_secret=self.client_secret, code=code )
5adc4a0637b31de518b30bbc662c3d50bc523a5a
airtravel.py
airtravel.py
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
Add seating plan to aircraft
Add seating plan to aircraft
Python
mit
kentoj/python-fundamentals
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model + def seating_plan(self): + return (range(1, self._num_rows + 1), + "ABCDEFGHJKLMNOP"[:self._num_seats_per_row]) +
Add seating plan to aircraft
## Code Before: """Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model ## Instruction: Add seating plan to aircraft ## Code After: """Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model + + def seating_plan(self): + return (range(1, self._num_rows + 1), + "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
8dae2049c96932855cc0162437d799e258f94a53
test/absolute_import/local_module.py
test/absolute_import/local_module.py
from __future__ import absolute_import import unittest # this is stdlib unittest, but jedi gets the local one class Assertions(unittest.TestCase): pass
from __future__ import absolute_import import unittest class Assertions(unittest.TestCase): pass
Fix inaccuracy in test comment, since jedi now does the right thing
Fix inaccuracy in test comment, since jedi now does the right thing
Python
mit
dwillmer/jedi,flurischt/jedi,mfussenegger/jedi,tjwei/jedi,flurischt/jedi,jonashaag/jedi,jonashaag/jedi,mfussenegger/jedi,tjwei/jedi,WoLpH/jedi,WoLpH/jedi,dwillmer/jedi
from __future__ import absolute_import - import unittest # this is stdlib unittest, but jedi gets the local one + import unittest class Assertions(unittest.TestCase): pass
Fix inaccuracy in test comment, since jedi now does the right thing
## Code Before: from __future__ import absolute_import import unittest # this is stdlib unittest, but jedi gets the local one class Assertions(unittest.TestCase): pass ## Instruction: Fix inaccuracy in test comment, since jedi now does the right thing ## Code After: from __future__ import absolute_import import unittest class Assertions(unittest.TestCase): pass
from __future__ import absolute_import - import unittest # this is stdlib unittest, but jedi gets the local one + import unittest class Assertions(unittest.TestCase): pass
ea6a84cee4f452f4503c6ce0fdd04b77d9017bdd
tinyblog/management/commands/import_tinyblog.py
tinyblog/management/commands/import_tinyblog.py
from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] r = requests.get(url) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n')
from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests from requests import exceptions from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] try: r = requests.get(url) except exceptions.MissingSchema as e: raise CommandError(e.message) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n')
Fix for bad URL schemes
Fix for bad URL schemes
Python
bsd-3-clause
dominicrodger/tinyblog,dominicrodger/tinyblog
from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests + from requests import exceptions from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] + try: - r = requests.get(url) + r = requests.get(url) + except exceptions.MissingSchema as e: + raise CommandError(e.message) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n')
Fix for bad URL schemes
## Code Before: from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] r = requests.get(url) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n') ## Instruction: Fix for bad URL schemes ## Code After: from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests from requests import exceptions from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] try: r = requests.get(url) except exceptions.MissingSchema as e: raise CommandError(e.message) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n')
from django.core.management.base import BaseCommand, CommandError from django.core import serializers import requests + from requests import exceptions from tinyblog.models import Post class Command(BaseCommand): args = 'url' help = u'Fetches blog entries from <url>, and loads them into tinyblog.' def handle(self, *args, **options): if not args: raise CommandError(u"You must provide a URL.") url = args[0] + try: - r = requests.get(url) + r = requests.get(url) ? ++++ + except exceptions.MissingSchema as e: + raise CommandError(e.message) if r.status_code != 200: raise CommandError(u"Received status {0} from {1}, expected 200.".format(r.status_code, url)) for obj in serializers.deserialize("json", r.content): self.stdout.write(u'Processing "{0}"...\n'.format(obj.object.title)) try: Post.objects.get(slug=obj.object.slug) self.stdout.write(u'Already had existing object with the slug "{0}".\n'.format(obj.object.slug)) except Post.DoesNotExist: obj.save() self.stdout.write(u'Saved new object.\n')
b8792d9164f669133032eb26ab78281acb17c9c5
appengine/standard/conftest.py
appengine/standard/conftest.py
import os import six # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): """Skip App Engine tests in python 3 and if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
import os # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) import six (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): """Skip App Engine tests in python 3 or if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
Fix lint issue and review comments
Fix lint issue and review comments Change-Id: I02a53961b6411247ef06d84dad7b533cb97d89f7
Python
apache-2.0
canglade/NLP,hashems/Mobile-Cloud-Development-Projects,sharbison3/python-docs-samples,JavaRabbit/CS496_capstone,GoogleCloudPlatform/python-docs-samples,sharbison3/python-docs-samples,sharbison3/python-docs-samples,sharbison3/python-docs-samples,hashems/Mobile-Cloud-Development-Projects,JavaRabbit/CS496_capstone,BrandonY/python-docs-samples,BrandonY/python-docs-samples,BrandonY/python-docs-samples,canglade/NLP,GoogleCloudPlatform/python-docs-samples,canglade/NLP,hashems/Mobile-Cloud-Development-Projects,BrandonY/python-docs-samples,GoogleCloudPlatform/python-docs-samples,canglade/NLP,hashems/Mobile-Cloud-Development-Projects,JavaRabbit/CS496_capstone,JavaRabbit/CS496_capstone,GoogleCloudPlatform/python-docs-samples
import os - - import six - # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) + import six (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): - """Skip App Engine tests in python 3 and if no SDK is available.""" + """Skip App Engine tests in python 3 or if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
Fix lint issue and review comments
## Code Before: import os import six # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): """Skip App Engine tests in python 3 and if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False ## Instruction: Fix lint issue and review comments ## Code After: import os # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) import six (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): """Skip App Engine tests in python 3 or if no SDK is available.""" if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
import os - - import six - # Import py.test hooks and fixtures for App Engine from gcp.testing.appengine import ( login, pytest_configure, pytest_runtest_call, run_tasks, testbed) + import six (login) (pytest_configure) (pytest_runtest_call) (run_tasks) (testbed) def pytest_ignore_collect(path, config): - """Skip App Engine tests in python 3 and if no SDK is available.""" ? ^^^ + """Skip App Engine tests in python 3 or if no SDK is available.""" ? ^^ if 'appengine/standard' in str(path): if six.PY3: return True if 'GAE_SDK_PATH' not in os.environ: return True return False
3b01b6b67e8cf05c31f2c30a3e45a59ffbb31adb
djangae/fields/computed.py
djangae/fields/computed.py
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs def from_db_value(self, value, expression, connection, context): return self.to_python(value) class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
Add from_db_value instead of removed SubfieldBase fields
Add from_db_value instead of removed SubfieldBase fields
Python
bsd-3-clause
kirberich/djangae,asendecka/djangae,kirberich/djangae,potatolondon/djangae,kirberich/djangae,potatolondon/djangae,grzes/djangae,asendecka/djangae,grzes/djangae,grzes/djangae,asendecka/djangae
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs + def from_db_value(self, value, expression, connection, context): + return self.to_python(value) + class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
Add from_db_value instead of removed SubfieldBase fields
## Code Before: from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass ## Instruction: Add from_db_value instead of removed SubfieldBase fields ## Code After: from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs def from_db_value(self, value, expression, connection, context): return self.to_python(value) class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs + def from_db_value(self, value, expression, connection, context): + return self.to_python(value) + class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
9548c4411938397b4f2d8a7b49b46cdc6aca0a3b
powerline/segments/i3wm.py
powerline/segments/i3wm.py
from powerline.theme import requires_segment_info import i3 def calcgrp( w ): group = ["workspace"] if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) if w['focused']: return "w_focused" return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ]
from powerline.theme import requires_segment_info import i3 def calcgrp( w ): group = [] if w['focused']: group.append( 'w_focused' ) if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) group.append( 'workspace' ) return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ]
Fix highlighting groups for workspaces segment
Fix highlighting groups for workspaces segment
Python
mit
Luffin/powerline,Luffin/powerline,areteix/powerline,cyrixhero/powerline,darac/powerline,russellb/powerline,bezhermoso/powerline,QuLogic/powerline,xfumihiro/powerline,prvnkumar/powerline,lukw00/powerline,bartvm/powerline,wfscheper/powerline,xxxhycl2010/powerline,s0undt3ch/powerline,blindFS/powerline,areteix/powerline,kenrachynski/powerline,blindFS/powerline,IvanAli/powerline,s0undt3ch/powerline,seanfisk/powerline,magus424/powerline,s0undt3ch/powerline,EricSB/powerline,IvanAli/powerline,Liangjianghao/powerline,russellb/powerline,wfscheper/powerline,xxxhycl2010/powerline,xxxhycl2010/powerline,QuLogic/powerline,wfscheper/powerline,bezhermoso/powerline,seanfisk/powerline,darac/powerline,prvnkumar/powerline,cyrixhero/powerline,junix/powerline,kenrachynski/powerline,Luffin/powerline,bezhermoso/powerline,blindFS/powerline,firebitsbr/powerline,dragon788/powerline,S0lll0s/powerline,dragon788/powerline,russellb/powerline,kenrachynski/powerline,Liangjianghao/powerline,magus424/powerline,cyrixhero/powerline,EricSB/powerline,dragon788/powerline,keelerm84/powerline,firebitsbr/powerline,lukw00/powerline,bartvm/powerline,lukw00/powerline,EricSB/powerline,junix/powerline,S0lll0s/powerline,bartvm/powerline,DoctorJellyface/powerline,xfumihiro/powerline,seanfisk/powerline,keelerm84/powerline,firebitsbr/powerline,junix/powerline,Liangjianghao/powerline,S0lll0s/powerline,DoctorJellyface/powerline,areteix/powerline,QuLogic/powerline,DoctorJellyface/powerline,magus424/powerline,IvanAli/powerline,prvnkumar/powerline,xfumihiro/powerline,darac/powerline
from powerline.theme import requires_segment_info import i3 def calcgrp( w ): - group = ["workspace"] + group = [] + if w['focused']: group.append( 'w_focused' ) if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) - if w['focused']: return "w_focused" + group.append( 'workspace' ) return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ]
Fix highlighting groups for workspaces segment
## Code Before: from powerline.theme import requires_segment_info import i3 def calcgrp( w ): group = ["workspace"] if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) if w['focused']: return "w_focused" return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ] ## Instruction: Fix highlighting groups for workspaces segment ## Code After: from powerline.theme import requires_segment_info import i3 def calcgrp( w ): group = [] if w['focused']: group.append( 'w_focused' ) if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) group.append( 'workspace' ) return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ]
from powerline.theme import requires_segment_info import i3 def calcgrp( w ): - group = ["workspace"] + group = [] + if w['focused']: group.append( 'w_focused' ) if w['urgent']: group.append( 'w_urgent' ) if w['visible']: group.append( 'w_visible' ) - if w['focused']: return "w_focused" + group.append( 'workspace' ) return group def workspaces( pl ): '''Return workspace list Highlight groups used: ``workspace``, ``w_visible``, ``w_focused``, ``w_urgent`` ''' return [ {'contents': w['name'], 'highlight_group': calcgrp( w )} for w in i3.get_workspaces() ]
ce3028f29e40ce72693394798ca0a8daa98c1a4a
data/make_hash_dict.py
data/make_hash_dict.py
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict if __name__ == "__main__": hash_dict = make_hash_dict("ds005") with open("ds005_hashes.json", "x", newline = "\n") as outfile: json.dump(hash_dict, outfile)
Make JSON containing paths and hashs
WIP: Make JSON containing paths and hashs
Python
bsd-3-clause
berkeley-stat159/project-delta
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict + + if __name__ == "__main__": + hash_dict = make_hash_dict("ds005") + with open("ds005_hashes.json", "x", newline = "\n") as outfile: + json.dump(hash_dict, outfile)
Make JSON containing paths and hashs
## Code Before: import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict ## Instruction: Make JSON containing paths and hashs ## Code After: import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict if __name__ == "__main__": hash_dict = make_hash_dict("ds005") with open("ds005_hashes.json", "x", newline = "\n") as outfile: json.dump(hash_dict, outfile)
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file paths as keys and hashes as values. """ paths = [os.path.join(root, files) for root, dirs, files in os.walk(top)] # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict + + if __name__ == "__main__": + hash_dict = make_hash_dict("ds005") + with open("ds005_hashes.json", "x", newline = "\n") as outfile: + json.dump(hash_dict, outfile)
211972701d8dbd39e42ec5a8d10b9c56be858d3e
tests/conftest.py
tests/conftest.py
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) return identity_store
Remove fixture teardown since nothing should be saved (tmpdir)
Remove fixture teardown since nothing should be saved (tmpdir)
Python
mit
nocarryr/AWS-Identity-Manager
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) - def fin(): - identity_store.identities.clear() - identity_store.save_to_config() return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) - def fin(): - identity_store.identities.clear() - identity_store.save_to_config() return identity_store
Remove fixture teardown since nothing should be saved (tmpdir)
## Code Before: import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store ## Instruction: Remove fixture teardown since nothing should be saved (tmpdir) ## Code After: import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) return identity_store
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) - def fin(): - identity_store.identities.clear() - identity_store.save_to_config() return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) - def fin(): - identity_store.identities.clear() - identity_store.save_to_config() return identity_store
ae4af32bf5ca21b2c7d80e2034560ed23f6a2ea7
src/main-rpython.py
src/main-rpython.py
import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os try: import rpython.rlib except ImportError: print("Failed to load RPython library. Please make sure it is on PYTHONPATH") sys.exit(1) # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
Add error to make sure we have RPython when using the RPython main
Add error to make sure we have RPython when using the RPython main Signed-off-by: Stefan Marr <[email protected]>
Python
mit
SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,SOM-st/PySOM,SOM-st/RPySOM,SOM-st/PySOM
import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os + + try: + import rpython.rlib + except ImportError: + print("Failed to load RPython library. Please make sure it is on PYTHONPATH") + sys.exit(1) # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
Add error to make sure we have RPython when using the RPython main
## Code Before: import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv)) ## Instruction: Add error to make sure we have RPython when using the RPython main ## Code After: import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os try: import rpython.rlib except ImportError: print("Failed to load RPython library. Please make sure it is on PYTHONPATH") sys.exit(1) # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
import sys from som.compiler.parse_error import ParseError from som.interp_type import is_ast_interpreter, is_bytecode_interpreter from som.vm.universe import main, Exit import os + + try: + import rpython.rlib + except ImportError: + print("Failed to load RPython library. Please make sure it is on PYTHONPATH") + sys.exit(1) # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit as e: return e.code except ParseError as e: os.write(2, str(e)) return 1 except Exception as e: os.write(2, "ERROR: %s thrown during execution.\n" % e) return 1 return 1 # _____ Define and setup target ___ def target(driver, args): exe_name = 'som-' if is_ast_interpreter(): exe_name += 'ast-' elif is_bytecode_interpreter(): exe_name += 'bc-' if driver.config.translation.jit: exe_name += 'jit' else: exe_name += 'interp' driver.exe_name = exe_name return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
ef6c29b6ebd8e3b536dcd63cfce683a6b69897d7
nyuki/workflow/tasks/python_script.py
nyuki/workflow/tasks/python_script.py
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): eval(self.config.get('script')) return event.data
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): # Compile string into python statement (allow multi-line) cc = compile(self.config['script'], 'dummy', 'exec') # Eval the compiled string eval(cc) return event.data
Improve script task to allow multiline
Improve script task to allow multiline
Python
apache-2.0
optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): - eval(self.config.get('script')) + # Compile string into python statement (allow multi-line) + cc = compile(self.config['script'], 'dummy', 'exec') + # Eval the compiled string + eval(cc) return event.data
Improve script task to allow multiline
## Code Before: import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): eval(self.config.get('script')) return event.data ## Instruction: Improve script task to allow multiline ## Code After: import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): # Compile string into python statement (allow multi-line) cc = compile(self.config['script'], 'dummy', 'exec') # Eval the compiled string eval(cc) return event.data
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'script': {'type': 'string', 'maxLength': 16384} } } async def execute(self, event): if self.config.get('script'): - eval(self.config.get('script')) + # Compile string into python statement (allow multi-line) + cc = compile(self.config['script'], 'dummy', 'exec') + # Eval the compiled string + eval(cc) return event.data
cd3c1f1fbacd4d1a113249af0faf298d5afa540f
wikifork-convert.py
wikifork-convert.py
from geojson import Feature, Point, FeatureCollection, dumps wikitext = open('wiki-fork', 'r') output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) wikitext.close() output.close()
import urllib.request from geojson import Feature, Point, FeatureCollection, dumps wiki = urllib.request.urlopen("https://wiki.archlinux.org/index.php/ArchMap/List") wiki_source = wiki.read() wikitext_start = wiki_source.find(b'<pre>', wiki_source.find(b'<pre>') + 1) + 5 wikitext_end = wiki_source.find(b'</pre>', wiki_source.find(b'</pre>') + 1) wikitext = wiki_source[wikitext_start:wikitext_end] output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) output.close()
Switch to parsing the wiki - UNTESTED
Switch to parsing the wiki - UNTESTED
Python
unlicense
guyfawcus/ArchMap,maelstrom59/ArchMap,guyfawcus/ArchMap,guyfawcus/ArchMap,maelstrom59/ArchMap
+ import urllib.request from geojson import Feature, Point, FeatureCollection, dumps - wikitext = open('wiki-fork', 'r') + wiki = urllib.request.urlopen("https://wiki.archlinux.org/index.php/ArchMap/List") + + wiki_source = wiki.read() + + wikitext_start = wiki_source.find(b'<pre>', wiki_source.find(b'<pre>') + 1) + 5 + wikitext_end = wiki_source.find(b'</pre>', wiki_source.find(b'</pre>') + 1) + wikitext = wiki_source[wikitext_start:wikitext_end] + output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) - wikitext.close() output.close() - -
Switch to parsing the wiki - UNTESTED
## Code Before: from geojson import Feature, Point, FeatureCollection, dumps wikitext = open('wiki-fork', 'r') output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) wikitext.close() output.close() ## Instruction: Switch to parsing the wiki - UNTESTED ## Code After: import urllib.request from geojson import Feature, Point, FeatureCollection, dumps wiki = urllib.request.urlopen("https://wiki.archlinux.org/index.php/ArchMap/List") wiki_source = wiki.read() wikitext_start = wiki_source.find(b'<pre>', wiki_source.find(b'<pre>') + 1) + 5 wikitext_end = wiki_source.find(b'</pre>', wiki_source.find(b'</pre>') + 1) wikitext = wiki_source[wikitext_start:wikitext_end] output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) output.close()
+ import urllib.request from geojson import Feature, Point, FeatureCollection, dumps - wikitext = open('wiki-fork', 'r') + wiki = urllib.request.urlopen("https://wiki.archlinux.org/index.php/ArchMap/List") + + wiki_source = wiki.read() + + wikitext_start = wiki_source.find(b'<pre>', wiki_source.find(b'<pre>') + 1) + 5 + wikitext_end = wiki_source.find(b'</pre>', wiki_source.find(b'</pre>') + 1) + wikitext = wiki_source[wikitext_start:wikitext_end] + output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() point = Point((float(coord[1]), float(coord[0]))) feature = Feature(geometry=point, properties={"Name": name}) geo_output.append(feature) output.write(dumps(FeatureCollection(geo_output))) - wikitext.close() output.close() - -
26a53141e844c11e7ff904af2620b7ee125b011d
diana/tracking.py
diana/tracking.py
from . import packet as p class Tracker: def __init__(self): self.objects = {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
from . import packet as p class Tracker: def __init__(self): self.objects = {} @property def player_ship(self): for _obj in self.objects.values(): if _obj['type'] == p.ObjectType.player_vessel: return _obj return {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
Add a convenience method to get the player ship
Add a convenience method to get the player ship
Python
mit
prophile/libdiana
from . import packet as p class Tracker: def __init__(self): self.objects = {} + + @property + def player_ship(self): + for _obj in self.objects.values(): + if _obj['type'] == p.ObjectType.player_vessel: + return _obj + return {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
Add a convenience method to get the player ship
## Code Before: from . import packet as p class Tracker: def __init__(self): self.objects = {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object) ## Instruction: Add a convenience method to get the player ship ## Code After: from . import packet as p class Tracker: def __init__(self): self.objects = {} @property def player_ship(self): for _obj in self.objects.values(): if _obj['type'] == p.ObjectType.player_vessel: return _obj return {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
from . import packet as p class Tracker: def __init__(self): self.objects = {} + + @property + def player_ship(self): + for _obj in self.objects.values(): + if _obj['type'] == p.ObjectType.player_vessel: + return _obj + return {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
c6fbba9da9d1cf2a5a0007a56d192e267d19fcff
flexget/utils/database.py
flexget/utils/database.py
from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): passed_session = kwargs.get('session') if not passed_session: session = Session(autoflush=True) try: return func(*args, session=session, **kwargs) finally: session.close() else: return func(*args, **kwargs) return wrapper
from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): if not kwargs.get('session'): kwargs['session'] = Session(autoflush=True) try: return func(*args, **kwargs) finally: kwargs['session'].close() else: return func(*args, **kwargs) return wrapper
Fix with_session decorator for python 2.5
Fix with_session decorator for python 2.5 git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1957 3942dd89-8c5d-46d7-aeed-044bccf3e60c
Python
mit
vfrc2/Flexget,tobinjt/Flexget,Pretagonist/Flexget,oxc/Flexget,Danfocus/Flexget,jacobmetrick/Flexget,Flexget/Flexget,spencerjanssen/Flexget,ianstalk/Flexget,xfouloux/Flexget,malkavi/Flexget,asm0dey/Flexget,v17al/Flexget,camon/Flexget,ZefQ/Flexget,cvium/Flexget,jacobmetrick/Flexget,crawln45/Flexget,camon/Flexget,OmgOhnoes/Flexget,tvcsantos/Flexget,spencerjanssen/Flexget,JorisDeRieck/Flexget,gazpachoking/Flexget,LynxyssCZ/Flexget,jacobmetrick/Flexget,patsissons/Flexget,JorisDeRieck/Flexget,patsissons/Flexget,qvazzler/Flexget,lildadou/Flexget,xfouloux/Flexget,sean797/Flexget,patsissons/Flexget,gazpachoking/Flexget,JorisDeRieck/Flexget,lildadou/Flexget,offbyone/Flexget,malkavi/Flexget,drwyrm/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,v17al/Flexget,dsemi/Flexget,poulpito/Flexget,sean797/Flexget,jawilson/Flexget,antivirtel/Flexget,asm0dey/Flexget,antivirtel/Flexget,poulpito/Flexget,ZefQ/Flexget,antivirtel/Flexget,ianstalk/Flexget,qk4l/Flexget,LynxyssCZ/Flexget,ratoaq2/Flexget,crawln45/Flexget,drwyrm/Flexget,drwyrm/Flexget,ibrahimkarahan/Flexget,ZefQ/Flexget,lildadou/Flexget,oxc/Flexget,sean797/Flexget,ianstalk/Flexget,tarzasai/Flexget,malkavi/Flexget,tarzasai/Flexget,vfrc2/Flexget,crawln45/Flexget,tsnoam/Flexget,voriux/Flexget,qvazzler/Flexget,xfouloux/Flexget,spencerjanssen/Flexget,malkavi/Flexget,qk4l/Flexget,Danfocus/Flexget,ibrahimkarahan/Flexget,tobinjt/Flexget,dsemi/Flexget,OmgOhnoes/Flexget,v17al/Flexget,qvazzler/Flexget,Flexget/Flexget,jawilson/Flexget,LynxyssCZ/Flexget,tsnoam/Flexget,dsemi/Flexget,tobinjt/Flexget,thalamus/Flexget,grrr2/Flexget,thalamus/Flexget,cvium/Flexget,tsnoam/Flexget,grrr2/Flexget,LynxyssCZ/Flexget,oxc/Flexget,Danfocus/Flexget,X-dark/Flexget,vfrc2/Flexget,tarzasai/Flexget,thalamus/Flexget,qk4l/Flexget,Pretagonist/Flexget,ratoaq2/Flexget,offbyone/Flexget,JorisDeRieck/Flexget,Flexget/Flexget,ibrahimkarahan/Flexget,cvium/Flexget,poulpito/Flexget,crawln45/Flexget,offbyone/Flexget,X-dark/Flexget,grrr2/Flexget,Flexget/Flexget,Pretagonist/Flexget,Danfocus/Flexget,X-dark/Flexget,voriux/Flexget,jawilson/Flexget,tvcsantos/Flexget,ratoaq2/Flexget,tobinjt/Flexget,asm0dey/Flexget
from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): - passed_session = kwargs.get('session') - if not passed_session: + if not kwargs.get('session'): - session = Session(autoflush=True) + kwargs['session'] = Session(autoflush=True) try: - return func(*args, session=session, **kwargs) + return func(*args, **kwargs) finally: - session.close() + kwargs['session'].close() else: return func(*args, **kwargs) return wrapper
Fix with_session decorator for python 2.5
## Code Before: from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): passed_session = kwargs.get('session') if not passed_session: session = Session(autoflush=True) try: return func(*args, session=session, **kwargs) finally: session.close() else: return func(*args, **kwargs) return wrapper ## Instruction: Fix with_session decorator for python 2.5 ## Code After: from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): if not kwargs.get('session'): kwargs['session'] = Session(autoflush=True) try: return func(*args, **kwargs) finally: kwargs['session'].close() else: return func(*args, **kwargs) return wrapper
from flexget.manager import Session def with_session(func): """"Creates a session if one was not passed via keyword argument to the function""" def wrapper(*args, **kwargs): - passed_session = kwargs.get('session') - if not passed_session: ? ^ ^ ^^ + if not kwargs.get('session'): ? ^^ ++ ^^ ^^^ ++ - session = Session(autoflush=True) + kwargs['session'] = Session(autoflush=True) ? ++++++++ ++ try: - return func(*args, session=session, **kwargs) ? ----------------- + return func(*args, **kwargs) finally: - session.close() + kwargs['session'].close() ? ++++++++ ++ else: return func(*args, **kwargs) return wrapper
0a6078f5d0537cea9f36894b736fa274c3fa3e47
molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py
molo/core/cookiecutter/scaffold/{{cookiecutter.directory}}/{{cookiecutter.app_name}}/forms.py
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_data_file(self): file = self.cleaned_data['data_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file ''' def process_data(self): print("I am processing the form") file = self.cleaned_data['data_file'].file # delete root media file # unzip file in root folder (make sure it's called 'media') '''
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_zip_file(self): file = self.cleaned_data['zip_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file
Fix upload form to only accept .zip files
Fix upload form to only accept .zip files
Python
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") - def clean_data_file(self): + def clean_zip_file(self): - file = self.cleaned_data['data_file'] + file = self.cleaned_data['zip_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file - ''' - def process_data(self): - print("I am processing the form") - file = self.cleaned_data['data_file'].file - - # delete root media file - # unzip file in root folder (make sure it's called 'media') - ''' -
Fix upload form to only accept .zip files
## Code Before: from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_data_file(self): file = self.cleaned_data['data_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file ''' def process_data(self): print("I am processing the form") file = self.cleaned_data['data_file'].file # delete root media file # unzip file in root folder (make sure it's called 'media') ''' ## Instruction: Fix upload form to only accept .zip files ## Code After: from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") def clean_zip_file(self): file = self.cleaned_data['zip_file'] if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file
from django import forms class MediaForm(forms.Form): zip_file = forms.FileField(label="Zipped Media File") - def clean_data_file(self): ? ^^^^ + def clean_zip_file(self): ? ^^^ - file = self.cleaned_data['data_file'] ? ^^^^ + file = self.cleaned_data['zip_file'] ? ^^^ if file: extension = file.name.split('.')[-1] if extension != 'zip': raise forms.ValidationError('File Type Is Not .zip') return file - ''' - - def process_data(self): - print("I am processing the form") - file = self.cleaned_data['data_file'].file - - # delete root media file - # unzip file in root folder (make sure it's called 'media') - '''
eaa99e12ef4b868e825ffe01f4eb9319e439827b
examples/face_detection/face_detect.py
examples/face_detection/face_detect.py
from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( [('example', util.download_video())], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( db, input_table, lambda t: t.all(), 'example_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) job = Job(columns = [out_frame], name = 'example_bboxes_overlay') out_table = db.run(job, force=True) out_table.column('frame').save_mp4('example_faces') print('Successfully generated example_faces.mp4')
from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util movie_path = util.download_video() if len(sys.argv) <= 1 else sys.argv[1] print('Detecting faces in movie {}'.format(movie_path)) movie_name = os.path.splitext(os.path.basename(movie_path))[0] with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( [(movie_name, movie_path)], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( db, input_table, lambda t: t.all(), movie_name + '_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) job = Job(columns = [out_frame], name = movie_name + '_bboxes_overlay') out_table = db.run(job, force=True) out_table.column('frame').save_mp4(movie_name + '_faces') print('Successfully generated {:s}_faces.mp4'.format(movie_name))
Update face detect example to take a path argument
Update face detect example to take a path argument
Python
apache-2.0
scanner-research/scanner,scanner-research/scanner,scanner-research/scanner,scanner-research/scanner
from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util + movie_path = util.download_video() if len(sys.argv) <= 1 else sys.argv[1] + print('Detecting faces in movie {}'.format(movie_path)) + movie_name = os.path.splitext(os.path.basename(movie_path))[0] + with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( - [('example', util.download_video())], force=True) + [(movie_name, movie_path)], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( - db, input_table, lambda t: t.all(), 'example_bboxes') + db, input_table, lambda t: t.all(), + movie_name + '_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) - job = Job(columns = [out_frame], name = 'example_bboxes_overlay') + job = Job(columns = [out_frame], name = movie_name + '_bboxes_overlay') out_table = db.run(job, force=True) - out_table.column('frame').save_mp4('example_faces') + out_table.column('frame').save_mp4(movie_name + '_faces') - print('Successfully generated example_faces.mp4') + print('Successfully generated {:s}_faces.mp4'.format(movie_name))
Update face detect example to take a path argument
## Code Before: from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( [('example', util.download_video())], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( db, input_table, lambda t: t.all(), 'example_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) job = Job(columns = [out_frame], name = 'example_bboxes_overlay') out_table = db.run(job, force=True) out_table.column('frame').save_mp4('example_faces') print('Successfully generated example_faces.mp4') ## Instruction: Update face detect example to take a path argument ## Code After: from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util movie_path = util.download_video() if len(sys.argv) <= 1 else sys.argv[1] print('Detecting faces in movie {}'.format(movie_path)) movie_name = os.path.splitext(os.path.basename(movie_path))[0] with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( [(movie_name, movie_path)], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( db, input_table, lambda t: t.all(), movie_name + '_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) job = Job(columns = [out_frame], name = movie_name + '_bboxes_overlay') out_table = db.run(job, force=True) out_table.column('frame').save_mp4(movie_name + '_faces') print('Successfully generated {:s}_faces.mp4'.format(movie_name))
from scannerpy import Database, DeviceType, Job from scannerpy.stdlib import pipelines import subprocess import cv2 import sys import os.path sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import util + movie_path = util.download_video() if len(sys.argv) <= 1 else sys.argv[1] + print('Detecting faces in movie {}'.format(movie_path)) + movie_name = os.path.splitext(os.path.basename(movie_path))[0] + with Database() as db: print('Ingesting video into Scanner ...') [input_table], _ = db.ingest_videos( - [('example', util.download_video())], force=True) + [(movie_name, movie_path)], force=True) print('Detecting faces...') bboxes_table = pipelines.detect_faces( - db, input_table, lambda t: t.all(), 'example_bboxes') ? ------------------ + db, input_table, lambda t: t.all(), + movie_name + '_bboxes') print('Drawing faces onto video...') frame = input_table.as_op().all() bboxes = bboxes_table.as_op().all() out_frame = db.ops.DrawBox(frame = frame, bboxes = bboxes) - job = Job(columns = [out_frame], name = 'example_bboxes_overlay') ? ^ ^ -- + job = Job(columns = [out_frame], name = movie_name + '_bboxes_overlay') ? ^^^^ ^^ ++++ out_table = db.run(job, force=True) - out_table.column('frame').save_mp4('example_faces') ? ^ ^ -- + out_table.column('frame').save_mp4(movie_name + '_faces') ? ^^^^ ^^ ++++ - print('Successfully generated example_faces.mp4') ? ^^^^^^^ + print('Successfully generated {:s}_faces.mp4'.format(movie_name)) ? ^^^^ ++++++++++++++++++ +
ea6c57de01f420bdd344194e5529a0e91036c634
greenfan/management/commands/create-job-from-testspec.py
greenfan/management/commands/create-job-from-testspec.py
from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) job = ts.create_job() return 'Created job %d' % job.pk
from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) physical = 'physical' in options job = ts.create_job(physical=physical) return 'Created job %d' % job.pk
Allow us to create both virtual and physical jobs
Allow us to create both virtual and physical jobs
Python
apache-2.0
sorenh/python-django-greenfan,sorenh/python-django-greenfan
from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) + physical = 'physical' in options - job = ts.create_job() + job = ts.create_job(physical=physical) - return 'Created job %d' % job.pk
Allow us to create both virtual and physical jobs
## Code Before: from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) job = ts.create_job() return 'Created job %d' % job.pk ## Instruction: Allow us to create both virtual and physical jobs ## Code After: from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) physical = 'physical' in options job = ts.create_job(physical=physical) return 'Created job %d' % job.pk
from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) + physical = 'physical' in options - job = ts.create_job() + job = ts.create_job(physical=physical) ? +++++++++++++++++ - return 'Created job %d' % job.pk
a3570205c90dd8757a833aed4f4069fbd33028e0
course/views.py
course/views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory from django.contrib.auth.models import User # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] owner = User.objects.get(username='nut') newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory})
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] owner = req.user newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory})
Remove fixed owner and make loged in user instead
Remove fixed owner and make loged in user instead
Python
apache-2.0
PNNutkung/Coursing-Field,PNNutkung/Coursing-Field,PNNutkung/Coursing-Field
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory - from django.contrib.auth.models import User # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] - owner = User.objects.get(username='nut') + owner = req.user newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory})
Remove fixed owner and make loged in user instead
## Code Before: from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory from django.contrib.auth.models import User # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] owner = User.objects.get(username='nut') newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory}) ## Instruction: Remove fixed owner and make loged in user instead ## Code After: from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] owner = req.user newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory})
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Category, Course, CourseInCategory - from django.contrib.auth.models import User # Create your views here. def createCourse(req): if req.method == 'POST': try: courseName = req.POST['courseName'] courseCategory = req.POST['courseCategory'] courseDesc = req.POST['courseDesc'] courseThumbnail = req.FILES['courseThumbnail'] coursePrice = req.POST['coursePrice'] - owner = User.objects.get(username='nut') + owner = req.user newCourse = Course(courseName=courseName, courseDesc=courseDesc,courseThumbnail=courseThumbnail, owner=owner, coursePrice=coursePrice, isDelete=False) newCourse.save() category = Category.objects.get(categoryID=courseCategory) newCourseCategory = CourseInCategory(category=category, course=newCourse) newCourseCategory.save() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': True, 'message': 'Create course successfully.'}) except: return render(req, 'course/createCourse.html', {'courseCategory':courseCategory, 'success': False, 'message': 'Create course failed.'}) else: courseCategory = Category.objects.all() return render(req, 'course/createCourse.html', {'courseCategory':courseCategory})
c434cf202de60d052f61f8608e48b5d7645be1c0
dear_astrid/test/test_rtm_importer.py
dear_astrid/test/test_rtm_importer.py
from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import Importer as rtmimp class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = rtmimp(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # assert that it is our mock object assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # test calling other methods imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # not used this time assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = rtmimp(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import * class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = Importer(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # Assert that it is in fact our mock object. assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # Test chaining method calls. imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # Not used this time. assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = Importer(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
Clean up names and comments for consistency
Clean up names and comments for consistency
Python
mit
rwstauner/dear_astrid,rwstauner/dear_astrid
from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * - from dear_astrid.rtm.importer import Importer as rtmimp + from dear_astrid.rtm.importer import * class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): - imp = rtmimp(['task']) + imp = Importer(['task']) imp._rtm = Mock() assert not self.mocks['time'].called - # assert that it is our mock object + # Assert that it is in fact our mock object. assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) - # test calling other methods + # Test chaining method calls. imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) - # not used this time + # Not used this time. assert not self.mocks['rtm'].called def test_deobfuscator(self): - imp = rtmimp(['task']) + imp = Importer(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
Clean up names and comments for consistency
## Code Before: from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import Importer as rtmimp class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = rtmimp(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # assert that it is our mock object assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # test calling other methods imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # not used this time assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = rtmimp(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667' ## Instruction: Clean up names and comments for consistency ## Code After: from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import * class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = Importer(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # Assert that it is in fact our mock object. assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # Test chaining method calls. imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # Not used this time. assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = Importer(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * - from dear_astrid.rtm.importer import Importer as rtmimp ? ^^^^^^^^^^^^^^^^^^ + from dear_astrid.rtm.importer import * ? ^ class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): - imp = rtmimp(['task']) ? ^^^^ + imp = Importer(['task']) ? ++++ ^^ imp._rtm = Mock() assert not self.mocks['time'].called - # assert that it is our mock object ? ^ + # Assert that it is in fact our mock object. ? ^ ++++++++ + assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) - # test calling other methods + # Test chaining method calls. imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) - # not used this time ? ^ + # Not used this time. ? ^ + assert not self.mocks['rtm'].called def test_deobfuscator(self): - imp = rtmimp(['task']) ? ^^^^ + imp = Importer(['task']) ? ++++ ^^ imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
32cc988e81bbbecf09f7e7a801e92c6cfc281e75
docs/autogen_config.py
docs/autogen_config.py
from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') generated = join(options, 'generated.rst') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) with open(generated, 'a') as f: f.write(filename + '\n') if __name__ == '__main__': # create empty file with open(generated, 'w'): pass write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), )
from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) if __name__ == '__main__': write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), )
Remove generation of unnecessary generated.rst file
Remove generation of unnecessary generated.rst file
Python
bsd-3-clause
ipython/ipython,ipython/ipython
from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') - generated = join(options, 'generated.rst') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) - with open(generated, 'a') as f: - f.write(filename + '\n') if __name__ == '__main__': - # create empty file - with open(generated, 'w'): - pass write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), ) -
Remove generation of unnecessary generated.rst file
## Code Before: from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') generated = join(options, 'generated.rst') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) with open(generated, 'a') as f: f.write(filename + '\n') if __name__ == '__main__': # create empty file with open(generated, 'w'): pass write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), ) ## Instruction: Remove generation of unnecessary generated.rst file ## Code After: from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) if __name__ == '__main__': write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), )
from os.path import join, dirname, abspath from IPython.terminal.ipapp import TerminalIPythonApp from ipykernel.kernelapp import IPKernelApp here = abspath(dirname(__file__)) options = join(here, 'source', 'config', 'options') - generated = join(options, 'generated.rst') def write_doc(name, title, app, preamble=None): filename = '%s.rst' % name with open(join(options, filename), 'w') as f: f.write(title + '\n') f.write(('=' * len(title)) + '\n') f.write('\n') if preamble is not None: f.write(preamble + '\n\n') f.write(app.document_config_options()) - with open(generated, 'a') as f: - f.write(filename + '\n') if __name__ == '__main__': - # create empty file - with open(generated, 'w'): - pass write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp()) write_doc('kernel', 'IPython kernel options', IPKernelApp(), preamble=("These options can be used in :file:`ipython_kernel_config.py`. " "The kernel also respects any options in `ipython_config.py`"), ) -
c84f14d33f9095f2d9d8919a9b6ba11e17acd4ca
txspinneret/test/util.py
txspinneret/test/util.py
from twisted.web import http from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
from twisted.web import http from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def __init__(self, *a, **kw): DummyRequest.__init__(self, *a, **kw) # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do # this so our tests pass on older versions of Twisted. self.requestHeaders = Headers() def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
Make `InMemoryRequest` work on Twisted<14.0.0
Make `InMemoryRequest` work on Twisted<14.0.0
Python
mit
jonathanj/txspinneret,mithrandi/txspinneret
from twisted.web import http + from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ + def __init__(self, *a, **kw): + DummyRequest.__init__(self, *a, **kw) + # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do + # this so our tests pass on older versions of Twisted. + self.requestHeaders = Headers() + + def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
Make `InMemoryRequest` work on Twisted<14.0.0
## Code Before: from twisted.web import http from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url) ## Instruction: Make `InMemoryRequest` work on Twisted<14.0.0 ## Code After: from twisted.web import http from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def __init__(self, *a, **kw): DummyRequest.__init__(self, *a, **kw) # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do # this so our tests pass on older versions of Twisted. self.requestHeaders = Headers() def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
from twisted.web import http + from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ + def __init__(self, *a, **kw): + DummyRequest.__init__(self, *a, **kw) + # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do + # this so our tests pass on older versions of Twisted. + self.requestHeaders = Headers() + + def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
721015d5a7ea9745094f06dfcea3625c20555992
inidiff/tests/test_diff.py
inidiff/tests/test_diff.py
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0)
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
Check number is the field that is different
Check number is the field that is different
Python
mit
kragniz/inidiff
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) + def test_number_is_different(self): + diffs = inidiff.diff(INI_1, INI_2) + first, second = diffs[0] + self.assertEqual('number', first[1]) +
Check number is the field that is different
## Code Before: import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) ## Instruction: Check number is the field that is different ## Code After: import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) + + def test_number_is_different(self): + diffs = inidiff.diff(INI_1, INI_2) + first, second = diffs[0] + self.assertEqual('number', first[1])
66503b8d59a8bb5128bd05966c81fa949b4e5097
__init__.py
__init__.py
from __future__ import absolute_import from . import energyHisto from . import para_temp_setup from . import CoordinateAnalysis
from __future__ import absolute_import import sys from . import para_temp_setup if sys.version_info.major == 2: # These (at this point) require python 2 because of gromacs and MDAnalysis from . import energyHisto from . import CoordinateAnalysis
Check python version and possibly only import some things
Check python version and possibly only import some things
Python
apache-2.0
theavey/ParaTemp,theavey/ParaTemp
from __future__ import absolute_import - from . import energyHisto + import sys from . import para_temp_setup + if sys.version_info.major == 2: + # These (at this point) require python 2 because of gromacs and MDAnalysis + from . import energyHisto - from . import CoordinateAnalysis + from . import CoordinateAnalysis
Check python version and possibly only import some things
## Code Before: from __future__ import absolute_import from . import energyHisto from . import para_temp_setup from . import CoordinateAnalysis ## Instruction: Check python version and possibly only import some things ## Code After: from __future__ import absolute_import import sys from . import para_temp_setup if sys.version_info.major == 2: # These (at this point) require python 2 because of gromacs and MDAnalysis from . import energyHisto from . import CoordinateAnalysis
from __future__ import absolute_import - from . import energyHisto + import sys from . import para_temp_setup + if sys.version_info.major == 2: + # These (at this point) require python 2 because of gromacs and MDAnalysis + from . import energyHisto - from . import CoordinateAnalysis + from . import CoordinateAnalysis ? ++++
dd4015874d6e7ab377795177876fe46a934bf741
testinfra/mon/test_ossec_ruleset.py
testinfra/mon/test_ossec_ruleset.py
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7"
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7" def test_overloaded_tor_guard_does_not_produce_alert(Command, Sudo): """Check that using an overloaded guard does not produce an OSSEC alert""" test_alert = ("Aug 16 21:54:44 app-staging Tor[26695]: [warn] Your Guard " "<name> (<fingerprint>) is failing a very large amount of " "circuits. Most likely this means the Tor network is " "overloaded, but it could also mean an attack against you " "or potentially the guard itself.") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) assert "Alert to be generated" not in c.stderr
Add test to reproduce overloaded Tor guard OSSEC alert
Add test to reproduce overloaded Tor guard OSSEC alert A Tor log event indicating that a Tor guard in use is overloaded currently produces an OSSEC alert. While this alert is an excellent candidate to be sent upstream to FPF for analysis, there is no action that a SecureDrop administrator is expected to take, making this a spurious OSSEC alert. This test reproduces this spurious alert and is a regression test for an OSSEC rule patch.
Python
agpl-3.0
garrettr/securedrop,ehartsuyker/securedrop,micahflee/securedrop,heartsucker/securedrop,conorsch/securedrop,garrettr/securedrop,micahflee/securedrop,conorsch/securedrop,ehartsuyker/securedrop,micahflee/securedrop,conorsch/securedrop,conorsch/securedrop,micahflee/securedrop,heartsucker/securedrop,conorsch/securedrop,garrettr/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,garrettr/securedrop
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7" + + def test_overloaded_tor_guard_does_not_produce_alert(Command, Sudo): + """Check that using an overloaded guard does not produce an OSSEC alert""" + test_alert = ("Aug 16 21:54:44 app-staging Tor[26695]: [warn] Your Guard " + "<name> (<fingerprint>) is failing a very large amount of " + "circuits. Most likely this means the Tor network is " + "overloaded, but it could also mean an attack against you " + "or potentially the guard itself.") + + with Sudo(): + c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( + test_alert)) + + assert "Alert to be generated" not in c.stderr +
Add test to reproduce overloaded Tor guard OSSEC alert
## Code Before: import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7" ## Instruction: Add test to reproduce overloaded Tor guard OSSEC alert ## Code After: import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7" def test_overloaded_tor_guard_does_not_produce_alert(Command, Sudo): """Check that using an overloaded guard does not produce an OSSEC alert""" test_alert = ("Aug 16 21:54:44 app-staging Tor[26695]: [warn] Your Guard " "<name> (<fingerprint>) is failing a very large amount of " "circuits. Most likely this means the Tor network is " "overloaded, but it could also mean an attack against you " "or potentially the guard itself.") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) assert "Alert to be generated" not in c.stderr
import re alert_level_regex = re.compile(r"Level: '(\d+)'") def test_grsec_denied_rwx_mapping_produces_alert(Command, Sudo): """Check that a denied RWX mmaping produces an OSSEC alert""" test_alert = ("Feb 10 23:34:40 app kernel: [ 124.188641] grsec: denied " "RWX mmap of <anonymous mapping> by /usr/sbin/apache2" "[apache2:1328] uid/euid:33/33 gid/egid:33/33, parent " "/usr/sbin/apache2[apache2:1309] uid/euid:0/0 gid/egid:0/0") with Sudo(): c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( test_alert)) # Level 7 alert should be triggered by rule 100101 assert "Alert to be generated" in c.stderr alert_level = alert_level_regex.findall(c.stderr)[0] assert alert_level == "7" + + + def test_overloaded_tor_guard_does_not_produce_alert(Command, Sudo): + """Check that using an overloaded guard does not produce an OSSEC alert""" + test_alert = ("Aug 16 21:54:44 app-staging Tor[26695]: [warn] Your Guard " + "<name> (<fingerprint>) is failing a very large amount of " + "circuits. Most likely this means the Tor network is " + "overloaded, but it could also mean an attack against you " + "or potentially the guard itself.") + + with Sudo(): + c = Command('echo "{}" | /var/ossec/bin/ossec-logtest'.format( + test_alert)) + + assert "Alert to be generated" not in c.stderr
8528beef5d10355af07f641b4987df3cd64a7b0f
sprockets/mixins/metrics/__init__.py
sprockets/mixins/metrics/__init__.py
from .influxdb import InfluxDBMixin from .statsd import StatsdMixin version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin']
try: from .influxdb import InfluxDBMixin from .statsd import StatsdMixin except ImportError as error: def InfluxDBMixin(*args, **kwargs): raise error def StatsdMixin(*args, **kwargs): raise error version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin']
Make it safe to import __version__.
Make it safe to import __version__.
Python
bsd-3-clause
sprockets/sprockets.mixins.metrics
+ try: - from .influxdb import InfluxDBMixin + from .influxdb import InfluxDBMixin - from .statsd import StatsdMixin + from .statsd import StatsdMixin + except ImportError as error: + def InfluxDBMixin(*args, **kwargs): + raise error + + def StatsdMixin(*args, **kwargs): + raise error version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin']
Make it safe to import __version__.
## Code Before: from .influxdb import InfluxDBMixin from .statsd import StatsdMixin version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin'] ## Instruction: Make it safe to import __version__. ## Code After: try: from .influxdb import InfluxDBMixin from .statsd import StatsdMixin except ImportError as error: def InfluxDBMixin(*args, **kwargs): raise error def StatsdMixin(*args, **kwargs): raise error version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin']
+ try: - from .influxdb import InfluxDBMixin + from .influxdb import InfluxDBMixin ? ++++ - from .statsd import StatsdMixin + from .statsd import StatsdMixin ? ++++ + except ImportError as error: + def InfluxDBMixin(*args, **kwargs): + raise error + + def StatsdMixin(*args, **kwargs): + raise error version_info = (1, 0, 0) __version__ = '.'.join(str(v) for v in version_info) __all__ = ['InfluxDBMixin', 'StatsdMixin']
df7e834b8418aeeeaee7fb90b953468c2490b93d
pypiup/cli.py
pypiup/cli.py
import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli()
import __init__ import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ print("\n ______ __ __ ______ __ __ __ ______ ") print("/\ == \ /\ \_\ \ /\ == \ /\ \ /\ \/\ \ /\ == \ ") print("\ \ _-/ \ \____ \ \ \ _-/ \ \ \ \ \ \_\ \ \ \ _-/ ") print(" \ \_\ \/\_____\ \ \_\ \ \_\ \ \_____\ \ \_\ ") print(" \/_/ \/_____/ \/_/ \/_/ \/_____/ \/_/ ") print("\nhttps://github.com/ekonstantinidis/pypiup") print("Version %s" % __init__.__version__) if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli()
Add Ascii Art & Version Number
Add Ascii Art & Version Number
Python
bsd-2-clause
ekonstantinidis/pypiup
+ import __init__ import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ + + print("\n ______ __ __ ______ __ __ __ ______ ") + print("/\ == \ /\ \_\ \ /\ == \ /\ \ /\ \/\ \ /\ == \ ") + print("\ \ _-/ \ \____ \ \ \ _-/ \ \ \ \ \ \_\ \ \ \ _-/ ") + print(" \ \_\ \/\_____\ \ \_\ \ \_\ \ \_____\ \ \_\ ") + print(" \/_/ \/_____/ \/_/ \/_/ \/_____/ \/_/ ") + print("\nhttps://github.com/ekonstantinidis/pypiup") + print("Version %s" % __init__.__version__) + if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli()
Add Ascii Art & Version Number
## Code Before: import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli() ## Instruction: Add Ascii Art & Version Number ## Code After: import __init__ import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ print("\n ______ __ __ ______ __ __ __ ______ ") print("/\ == \ /\ \_\ \ /\ == \ /\ \ /\ \/\ \ /\ == \ ") print("\ \ _-/ \ \____ \ \ \ _-/ \ \ \ \ \ \_\ \ \ \ _-/ ") print(" \ \_\ \/\_____\ \ \_\ \ \_\ \ \_____\ \ \_\ ") print(" \/_/ \/_____/ \/_/ \/_/ \/_____/ \/_/ ") print("\nhttps://github.com/ekonstantinidis/pypiup") print("Version %s" % __init__.__version__) if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli()
+ import __init__ import os import click from pypiup.requirements import Requirements BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @click.command() @click.option('--requirement', '-r', default='requirements.txt', type=click.STRING, help='Specify the path of the requirements file. Defaults to "requirements.txt".') @click.option('--demo', '-d', is_flag=True, help='Load the demo requirements.txt file that comes with the package.') def cli(requirement, demo): """ PyPIup\n Check whether your PyPI requirements are up to date. """ + + print("\n ______ __ __ ______ __ __ __ ______ ") + print("/\ == \ /\ \_\ \ /\ == \ /\ \ /\ \/\ \ /\ == \ ") + print("\ \ _-/ \ \____ \ \ \ _-/ \ \ \ \ \ \_\ \ \ \ _-/ ") + print(" \ \_\ \/\_____\ \ \_\ \ \_\ \ \_____\ \ \_\ ") + print(" \/_/ \/_____/ \/_/ \/_/ \/_____/ \/_/ ") + print("\nhttps://github.com/ekonstantinidis/pypiup") + print("Version %s" % __init__.__version__) + if demo: demo_path = os.path.join(BASE_DIR, 'requirements/requirements-demo.txt') return Requirements(demo_path) Requirements(requirement) if __name__ == '__main__': cli()
9ab7efa44a8e7267b2902b6e23ff61381d31692c
profile_collection/startup/85-robot.py
profile_collection/startup/85-robot.py
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C class Robot(Device): robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') robot_execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') robot_status = C(EpicsSignal, 'Sts-Sts') robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.utils import set_and_wait class Robot(Device): sample_number = C(EpicsSignal, 'ID:Tgt-SP') load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') status = C(EpicsSignal, 'Sts-Sts') TH_POS = {'capilary':{'load':0, 'measure': 0}, 'flat': {'load': 0, 'measure': 0}, '':{}} DIFF_POS = {'capilary': (1,2),} def __init__(self, theta, diff): self.theta = theta self.diff = diff def load_sample(sample_number, sample_type): # self.theta.move(self.TH_POS[sample_type]['load'], wait=True) set_and_wait(self.sample_number, sample_number) set_and_wait(self.load_cmd, 1) self.execute_cmd.put(1) while self.status.get() != 'Idle': time.sleep(.1) # self.theta.move(self.TH_POS[sample_type]['measure'], wait=True) robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py
Add sample loading logic to Robot.
WIP: Add sample loading logic to Robot.
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C - + from ophyd.utils import set_and_wait class Robot(Device): - robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') + sample_number = C(EpicsSignal, 'ID:Tgt-SP') - robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') + load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') - robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') + unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') - robot_execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') + execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') - robot_status = C(EpicsSignal, 'Sts-Sts') + status = C(EpicsSignal, 'Sts-Sts') + + TH_POS = {'capilary':{'load':0, 'measure': 0}, + 'flat': {'load': 0, 'measure': 0}, + '':{}} + + DIFF_POS = {'capilary': (1,2),} + + def __init__(self, theta, diff): + self.theta = theta + self.diff = diff + + def load_sample(sample_number, sample_type): + # self.theta.move(self.TH_POS[sample_type]['load'], wait=True) + set_and_wait(self.sample_number, sample_number) + set_and_wait(self.load_cmd, 1) + self.execute_cmd.put(1) + + while self.status.get() != 'Idle': + time.sleep(.1) + # self.theta.move(self.TH_POS[sample_type]['measure'], wait=True) + + robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py
Add sample loading logic to Robot.
## Code Before: from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C class Robot(Device): robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') robot_execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') robot_status = C(EpicsSignal, 'Sts-Sts') robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py ## Instruction: Add sample loading logic to Robot. ## Code After: from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.utils import set_and_wait class Robot(Device): sample_number = C(EpicsSignal, 'ID:Tgt-SP') load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') status = C(EpicsSignal, 'Sts-Sts') TH_POS = {'capilary':{'load':0, 'measure': 0}, 'flat': {'load': 0, 'measure': 0}, '':{}} DIFF_POS = {'capilary': (1,2),} def __init__(self, theta, diff): self.theta = theta self.diff = diff def load_sample(sample_number, sample_type): # self.theta.move(self.TH_POS[sample_type]['load'], wait=True) set_and_wait(self.sample_number, sample_number) set_and_wait(self.load_cmd, 1) self.execute_cmd.put(1) while self.status.get() != 'Idle': time.sleep(.1) # self.theta.move(self.TH_POS[sample_type]['measure'], wait=True) robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py
from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd import Component as C - + from ophyd.utils import set_and_wait class Robot(Device): - robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP') ? ------ + sample_number = C(EpicsSignal, 'ID:Tgt-SP') - robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') ? ------ + load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC') - robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') ? ------ + unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC') - robot_execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') ? ------ + execute_cmd = C(EpicsSignal, 'Cmd:Exec-Cmd') - robot_status = C(EpicsSignal, 'Sts-Sts') ? ------ + status = C(EpicsSignal, 'Sts-Sts') + + TH_POS = {'capilary':{'load':0, 'measure': 0}, + 'flat': {'load': 0, 'measure': 0}, + '':{}} + + DIFF_POS = {'capilary': (1,2),} + + def __init__(self, theta, diff): + self.theta = theta + self.diff = diff + + def load_sample(sample_number, sample_type): + # self.theta.move(self.TH_POS[sample_type]['load'], wait=True) + set_and_wait(self.sample_number, sample_number) + set_and_wait(self.load_cmd, 1) + self.execute_cmd.put(1) + + while self.status.get() != 'Idle': + time.sleep(.1) + # self.theta.move(self.TH_POS[sample_type]['measure'], wait=True) + + robot = Robot('XF:28IDC-ES:1{SM}') # old RobotPositioner code is .ipython/profile_2015_collection/startup/robot.py
8496ba409b9a340858e4473157aab87593868db7
pytask/views.py
pytask/views.py
from django.shortcuts import render_to_response def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() can_create_task = True if profile.rights != "CT" else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html")
from django.shortcuts import render_to_response from pytask.profile import models as profile_models def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html")
Use the right name for the profile role's values.
Use the right name for the profile role's values.
Python
agpl-3.0
madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask
from django.shortcuts import render_to_response + + from pytask.profile import models as profile_models + def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() - can_create_task = True if profile.rights != "CT" else False + can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html")
Use the right name for the profile role's values.
## Code Before: from django.shortcuts import render_to_response def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() can_create_task = True if profile.rights != "CT" else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html") ## Instruction: Use the right name for the profile role's values. ## Code After: from django.shortcuts import render_to_response from pytask.profile import models as profile_models def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html")
from django.shortcuts import render_to_response + + from pytask.profile import models as profile_models + def show_msg(user, message, redirect_url=None, url_desc=None): """ simply redirect to homepage """ return render_to_response('show_msg.html',{'user': user, 'message': message, 'redirect_url': redirect_url, 'url_desc': url_desc}) def home_page(request): """ get the user and display info about the project if not logged in. if logged in, display info of their tasks. """ user = request.user if not user.is_authenticated(): return render_to_response("index.html") profile = user.get_profile() claimed_tasks = user.claimed_tasks.all() selected_tasks = user.selected_tasks.all() reviewing_tasks = user.reviewing_tasks.all() unpublished_tasks = user.created_tasks.filter(status="UP").all() - can_create_task = True if profile.rights != "CT" else False + can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False context = {"user": user, "profile": profile, "claimed_tasks": claimed_tasks, "selected_tasks": selected_tasks, "reviewing_tasks": reviewing_tasks, "unpublished_tasks": unpublished_tasks, "can_create_task": can_create_task } return render_to_response("index.html", context) def under_construction(request): return render_to_response("under_construction.html")
434b3e94f461c995a5e2f421acca29897495f0a8
setup.py
setup.py
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", packages = ['respite'] )
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", packages = ['respite', 'respite.lib', 'respite.serializers'] )
Add 'lib' and 'serializers' to packages
Add 'lib' and 'serializers' to packages
Python
mit
jgorset/django-respite,jgorset/django-respite,jgorset/django-respite
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", - packages = ['respite'] + packages = ['respite', 'respite.lib', 'respite.serializers'] )
Add 'lib' and 'serializers' to packages
## Code Before: from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", packages = ['respite'] ) ## Instruction: Add 'lib' and 'serializers' to packages ## Code After: from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", packages = ['respite', 'respite.lib', 'respite.serializers'] )
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "[email protected]", url = "http://github.com/jgorset/respite", - packages = ['respite'] + packages = ['respite', 'respite.lib', 'respite.serializers'] )
f1fedff9247b78120df7335b64cdf46c8f60ef03
test/test_fixtures.py
test/test_fixtures.py
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture class TestClass: @pytest.mark.gen_test def test_uses_pytestmark_fixtures(self, io_loop): assert (yield dummy(io_loop)) assert _used_fixture
Add some test for method signature inspection
Add some test for method signature inspection
Python
apache-2.0
eugeniy/pytest-tornado
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture + class TestClass: + @pytest.mark.gen_test + def test_uses_pytestmark_fixtures(self, io_loop): + assert (yield dummy(io_loop)) + assert _used_fixture +
Add some test for method signature inspection
## Code Before: import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture ## Instruction: Add some test for method signature inspection ## Code After: import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture class TestClass: @pytest.mark.gen_test def test_uses_pytestmark_fixtures(self, io_loop): assert (yield dummy(io_loop)) assert _used_fixture
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture + + class TestClass: + @pytest.mark.gen_test + def test_uses_pytestmark_fixtures(self, io_loop): + assert (yield dummy(io_loop)) + assert _used_fixture
9249dc161e9fdd64e15a42f644232c43cb6875b2
src/dependenpy/plugins.py
src/dependenpy/plugins.py
"""dependenpy plugins module.""" try: from archan import Provider, Argument, DSM as ArchanDSM from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' arguments = ( Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) def get_dsm(self, packages, enforce_init=True, depth=None): """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider."""
"""dependenpy plugins module.""" try: from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' argument_list = ( Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) def get_data(self, packages, enforce_init=True, depth=None): """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider."""
Update archan provider for archan 3.0
Update archan provider for archan 3.0
Python
isc
Pawamoy/dependenpy,Pawamoy/dependenpy
"""dependenpy plugins module.""" try: - from archan import Provider, Argument, DSM as ArchanDSM + from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' - arguments = ( + argument_list = ( Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) - def get_dsm(self, packages, enforce_init=True, depth=None): + def get_data(self, packages, enforce_init=True, depth=None): """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider."""
Update archan provider for archan 3.0
## Code Before: """dependenpy plugins module.""" try: from archan import Provider, Argument, DSM as ArchanDSM from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' arguments = ( Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) def get_dsm(self, packages, enforce_init=True, depth=None): """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider.""" ## Instruction: Update archan provider for archan 3.0 ## Code After: """dependenpy plugins module.""" try: from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' argument_list = ( Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) def get_data(self, packages, enforce_init=True, depth=None): """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider."""
"""dependenpy plugins module.""" try: - from archan import Provider, Argument, DSM as ArchanDSM + from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM ? +++++ ++++++++ +++++ from .dsm import DSM as DependenpyDSM from .helpers import guess_depth class InternalDependencies(Provider): """Dependenpy provider for Archan.""" identifier = 'dependenpy.InternalDependencies' name = 'Internal Dependencies' description = 'Provide matrix data about internal dependencies ' \ 'in a set of packages.' - arguments = ( + argument_list = ( ? +++ + Argument('packages', list, 'The list of packages to check for.'), Argument('enforce_init', bool, default=True, description='Whether to assert presence of ' '__init__.py files in directories.'), Argument('depth', int, 'The depth of the matrix to generate.'), ) - def get_dsm(self, packages, enforce_init=True, depth=None): ? ^^ + def get_data(self, packages, enforce_init=True, depth=None): ? ^^^ """ Provide matrix data for internal dependencies in a set of packages. Args: *packages (list): the list of packages to check for. enforce_init (bool): whether to assert presence of __init__.py files in directories. depth (int): the depth of the matrix to generate. Returns: archan.DSM: instance of archan DSM. """ dsm = DependenpyDSM(*packages, enforce_init=enforce_init) if depth is None: depth = guess_depth(packages) matrix = dsm.as_matrix(depth=depth) return ArchanDSM(data=matrix.data, entities=matrix.keys) except ImportError: class InternalDependencies(object): """Empty dependenpy provider."""
02cb413b8e6671cead4ec9af55acef2daf451fc0
contributr/contributr/wsgi.py
contributr/contributr/wsgi.py
import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local") # Cling is a simple way of serving static assets. # http://www.kennethreitz.org/essays/introducing-dj-static application = Cling(get_wsgi_application())
import os from django.core.wsgi import get_wsgi_application if os.environ.get("DJANGO_SETTINGS_MODULE") == "contributr.settings.production": # Cling is a simple way of serving static assets. # http://www.kennethreitz.org/essays/introducing-dj-static from dj_static import Cling application = Cling(get_wsgi_application()) else: application = get_wsgi_application() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
Move production Cling settings into production-only block
Move production Cling settings into production-only block The Cling import and call are moved into an if-block that is only executed when the server is run with production settings. This makes the server run locally again. Resolves: #42
Python
mit
SanketDG/contributr,iAmMrinal0/contributr,sofianugraha/contributr,nickpolet/contributr,Heasummn/contributr,JoshAddington/contributr,sofianugraha/contributr,troyleak/contributr,nickpolet/contributr,iAmMrinal0/contributr,SanketDG/contributr,planetirf/contributr,planetirf/contributr,planetirf/contributr,kakorrhaphio/contributr,abdullah2891/contributr,Heasummn/contributr,npaul2811/contributr,npaul2811/contributr,troyleak/contributr,sofianugraha/contributr,kakorrhaphio/contributr,Djenesis/contributr,jherrlin/contributr,abdullah2891/contributr,Heasummn/contributr,JoshAddington/contributr,jherrlin/contributr,jherrlin/contributr,iAmMrinal0/contributr,JoshAddington/contributr,kakorrhaphio/contributr,Djenesis/contributr,troyleak/contributr,SanketDG/contributr,abdullah2891/contributr,nickpolet/contributr,npaul2811/contributr,Djenesis/contributr
import os from django.core.wsgi import get_wsgi_application + + if os.environ.get("DJANGO_SETTINGS_MODULE") == "contributr.settings.production": + # Cling is a simple way of serving static assets. + # http://www.kennethreitz.org/essays/introducing-dj-static - from dj_static import Cling + from dj_static import Cling + application = Cling(get_wsgi_application()) + else: + application = get_wsgi_application() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local") - # Cling is a simple way of serving static assets. - # http://www.kennethreitz.org/essays/introducing-dj-static - application = Cling(get_wsgi_application()) -
Move production Cling settings into production-only block
## Code Before: import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local") # Cling is a simple way of serving static assets. # http://www.kennethreitz.org/essays/introducing-dj-static application = Cling(get_wsgi_application()) ## Instruction: Move production Cling settings into production-only block ## Code After: import os from django.core.wsgi import get_wsgi_application if os.environ.get("DJANGO_SETTINGS_MODULE") == "contributr.settings.production": # Cling is a simple way of serving static assets. # http://www.kennethreitz.org/essays/introducing-dj-static from dj_static import Cling application = Cling(get_wsgi_application()) else: application = get_wsgi_application() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
import os from django.core.wsgi import get_wsgi_application + + if os.environ.get("DJANGO_SETTINGS_MODULE") == "contributr.settings.production": + # Cling is a simple way of serving static assets. + # http://www.kennethreitz.org/essays/introducing-dj-static - from dj_static import Cling + from dj_static import Cling ? ++++ + application = Cling(get_wsgi_application()) + else: + application = get_wsgi_application() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local") - - # Cling is a simple way of serving static assets. - # http://www.kennethreitz.org/essays/introducing-dj-static - application = Cling(get_wsgi_application())
f497259869ba0f920d8a7eaac45bd320566c4808
examples/Interactivity/circlepainter.py
examples/Interactivity/circlepainter.py
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) circle(self.x, self.y, self.radius) # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
Use of circle() instead of oval()
Use of circle() instead of oval()
Python
mit
karstenw/nodebox-pyobjc,karstenw/nodebox-pyobjc
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) + circle(self.x, self.y, self.radius) - oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) + # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
Use of circle() instead of oval()
## Code Before: size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw() ## Instruction: Use of circle() instead of oval() ## Code After: size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) circle(self.x, self.y, self.radius) # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) + circle(self.x, self.y, self.radius) - oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) + # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) ? ++ def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
366937921cfb13fd83fb5964d0373be48e3c8564
cmsplugin_plain_text/models.py
cmsplugin_plain_text/models.py
from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body
from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body def __str__(self): return self.body
Add `__str__` method to support Python 3
Add `__str__` method to support Python 3
Python
bsd-3-clause
chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text
from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body + def __str__(self): + return self.body +
Add `__str__` method to support Python 3
## Code Before: from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body ## Instruction: Add `__str__` method to support Python 3 ## Code After: from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body def __str__(self): return self.body
from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ class Plaintext(CMSPlugin): body = models.TextField(_('Plaintext')) def __unicode__(self): return self.body + + def __str__(self): + return self.body
6a7a553dd51abbd6ade2e448bae0e4e2a8036f23
generate-data.py
generate-data.py
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): data = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) data[stimulus[1] * numx + stimulus[0]] = '1' return data, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): data, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(data, data) # duplicate for two eyes scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
Add separate left and right eye data generation
Add separate left and right eye data generation
Python
mit
jeffames-cs/nnot
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): - data = ['0' for i in range(numx * numy)] + ldata = ['0' for i in range(numx * numy)] + rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) - data[stimulus[1] * numx + stimulus[0]] = '1' + ldata[stimulus[1] * numx + stimulus[0]] = '1' + rdata[stimulus[1] * numx + stimulus[0]] = '1' - return data, stimulus + return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): - data, stimulus = generate_data(gridDim[0], gridDim[1]) + ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) - print_input(data, data) # duplicate for two eyes + print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
Add separate left and right eye data generation
## Code Before: import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): data = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) data[stimulus[1] * numx + stimulus[0]] = '1' return data, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): data, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(data, data) # duplicate for two eyes scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y)) ## Instruction: Add separate left and right eye data generation ## Code After: import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): - data = ['0' for i in range(numx * numy)] + ldata = ['0' for i in range(numx * numy)] ? + + rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) - data[stimulus[1] * numx + stimulus[0]] = '1' + ldata[stimulus[1] * numx + stimulus[0]] = '1' ? + + rdata[stimulus[1] * numx + stimulus[0]] = '1' - return data, stimulus + return ldata, rdata, stimulus ? ++++++++ def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): - data, stimulus = generate_data(gridDim[0], gridDim[1]) + ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) ? ++++++++ - print_input(data, data) # duplicate for two eyes + print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
90d7d5deabf9e55ce75da06a61088630c2a2d103
gallery/urls.py
gallery/urls.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import permission_required from . import views protect = permission_required('gallery.view') urlpatterns = patterns('', url(r'^$', protect(views.GalleryIndexView.as_view()), name='gallery-index'), url(r'^year/(?P<year>\d{4})/$', protect(views.GalleryYearView.as_view()), name='gallery-year'), url(r'^album/(?P<pk>\d+)/$', protect(views.AlbumView.as_view()), name='gallery-album'), url(r'^photo/(?P<pk>\d+)/$', protect(views.PhotoView.as_view()), name='gallery-photo'), url(r'^original/(?P<pk>\d+)/$', protect(views.original_photo), name='gallery-photo-original'), url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', protect(views.resized_photo), name='gallery-photo-resized'), )
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', url(r'^$', views.GalleryIndexView.as_view(), name='gallery-index'), url(r'^year/(?P<year>\d{4})/$', views.GalleryYearView.as_view(), name='gallery-year'), url(r'^album/(?P<pk>\d+)/$', views.AlbumView.as_view(), name='gallery-album'), url(r'^photo/(?P<pk>\d+)/$', views.PhotoView.as_view(), name='gallery-photo'), url(r'^original/(?P<pk>\d+)/$', views.original_photo, name='gallery-photo-original'), url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', views.resized_photo, name='gallery-photo-resized'), )
Remove blanket protection in preparation for granular access control.
Remove blanket protection in preparation for granular access control.
Python
bsd-3-clause
aaugustin/myks-gallery,aaugustin/myks-gallery
from django.conf.urls import patterns, url - from django.contrib.auth.decorators import permission_required from . import views - protect = permission_required('gallery.view') urlpatterns = patterns('', - url(r'^$', protect(views.GalleryIndexView.as_view()), name='gallery-index'), + url(r'^$', views.GalleryIndexView.as_view(), name='gallery-index'), - url(r'^year/(?P<year>\d{4})/$', protect(views.GalleryYearView.as_view()), name='gallery-year'), + url(r'^year/(?P<year>\d{4})/$', views.GalleryYearView.as_view(), name='gallery-year'), - url(r'^album/(?P<pk>\d+)/$', protect(views.AlbumView.as_view()), name='gallery-album'), + url(r'^album/(?P<pk>\d+)/$', views.AlbumView.as_view(), name='gallery-album'), - url(r'^photo/(?P<pk>\d+)/$', protect(views.PhotoView.as_view()), name='gallery-photo'), + url(r'^photo/(?P<pk>\d+)/$', views.PhotoView.as_view(), name='gallery-photo'), - url(r'^original/(?P<pk>\d+)/$', protect(views.original_photo), name='gallery-photo-original'), + url(r'^original/(?P<pk>\d+)/$', views.original_photo, name='gallery-photo-original'), - url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', protect(views.resized_photo), name='gallery-photo-resized'), + url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', views.resized_photo, name='gallery-photo-resized'), )
Remove blanket protection in preparation for granular access control.
## Code Before: from django.conf.urls import patterns, url from django.contrib.auth.decorators import permission_required from . import views protect = permission_required('gallery.view') urlpatterns = patterns('', url(r'^$', protect(views.GalleryIndexView.as_view()), name='gallery-index'), url(r'^year/(?P<year>\d{4})/$', protect(views.GalleryYearView.as_view()), name='gallery-year'), url(r'^album/(?P<pk>\d+)/$', protect(views.AlbumView.as_view()), name='gallery-album'), url(r'^photo/(?P<pk>\d+)/$', protect(views.PhotoView.as_view()), name='gallery-photo'), url(r'^original/(?P<pk>\d+)/$', protect(views.original_photo), name='gallery-photo-original'), url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', protect(views.resized_photo), name='gallery-photo-resized'), ) ## Instruction: Remove blanket protection in preparation for granular access control. ## Code After: from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', url(r'^$', views.GalleryIndexView.as_view(), name='gallery-index'), url(r'^year/(?P<year>\d{4})/$', views.GalleryYearView.as_view(), name='gallery-year'), url(r'^album/(?P<pk>\d+)/$', views.AlbumView.as_view(), name='gallery-album'), url(r'^photo/(?P<pk>\d+)/$', views.PhotoView.as_view(), name='gallery-photo'), url(r'^original/(?P<pk>\d+)/$', views.original_photo, name='gallery-photo-original'), url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', views.resized_photo, name='gallery-photo-resized'), )
from django.conf.urls import patterns, url - from django.contrib.auth.decorators import permission_required from . import views - protect = permission_required('gallery.view') urlpatterns = patterns('', - url(r'^$', protect(views.GalleryIndexView.as_view()), name='gallery-index'), ? -------- - + url(r'^$', views.GalleryIndexView.as_view(), name='gallery-index'), - url(r'^year/(?P<year>\d{4})/$', protect(views.GalleryYearView.as_view()), name='gallery-year'), ? -------- - + url(r'^year/(?P<year>\d{4})/$', views.GalleryYearView.as_view(), name='gallery-year'), - url(r'^album/(?P<pk>\d+)/$', protect(views.AlbumView.as_view()), name='gallery-album'), ? -------- - + url(r'^album/(?P<pk>\d+)/$', views.AlbumView.as_view(), name='gallery-album'), - url(r'^photo/(?P<pk>\d+)/$', protect(views.PhotoView.as_view()), name='gallery-photo'), ? -------- - + url(r'^photo/(?P<pk>\d+)/$', views.PhotoView.as_view(), name='gallery-photo'), - url(r'^original/(?P<pk>\d+)/$', protect(views.original_photo), name='gallery-photo-original'), ? -------- - + url(r'^original/(?P<pk>\d+)/$', views.original_photo, name='gallery-photo-original'), - url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', protect(views.resized_photo), name='gallery-photo-resized'), ? -------- - + url(r'^(?P<preset>\w+)/(?P<pk>\d+)/$', views.resized_photo, name='gallery-photo-resized'), )
116708c5458b68110e75a593a0edaa0298bb5586
cyder/core/fields.py
cyder/core/fields.py
from django.db.models import CharField from django.core.exceptions import ValidationError from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate for option in ['max_length', 'blank']: if option in kwargs: raise Exception('You cannot specify the {0} option.' .format(option)) kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value
from django.db.models import CharField, NOT_PROVIDED from django.core.exceptions import ValidationError from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value add_introspection_rules([ ( [MacAddrField], # model [], # args {'dhcp_enabled': ('dhcp_enabled', {})}, # kwargs ) ], [r'^cyder\.core\.fields\.MacAddrField'])
Add introspection rule; prevent South weirdness
Add introspection rule; prevent South weirdness
Python
bsd-3-clause
drkitty/cyder,murrown/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,zeeman/cyder,murrown/cyder,zeeman/cyder
- from django.db.models import CharField + from django.db.models import CharField, NOT_PROVIDED from django.core.exceptions import ValidationError + from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate - for option in ['max_length', 'blank']: - if option in kwargs: - raise Exception('You cannot specify the {0} option.' - .format(option)) - kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value + + add_introspection_rules([ + ( + [MacAddrField], # model + [], # args + {'dhcp_enabled': ('dhcp_enabled', {})}, # kwargs + ) + ], [r'^cyder\.core\.fields\.MacAddrField']) +
Add introspection rule; prevent South weirdness
## Code Before: from django.db.models import CharField from django.core.exceptions import ValidationError from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate for option in ['max_length', 'blank']: if option in kwargs: raise Exception('You cannot specify the {0} option.' .format(option)) kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value ## Instruction: Add introspection rule; prevent South weirdness ## Code After: from django.db.models import CharField, NOT_PROVIDED from django.core.exceptions import ValidationError from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value add_introspection_rules([ ( [MacAddrField], # model [], # args {'dhcp_enabled': ('dhcp_enabled', {})}, # kwargs ) ], [r'^cyder\.core\.fields\.MacAddrField'])
- from django.db.models import CharField + from django.db.models import CharField, NOT_PROVIDED ? ++++++++++++++ from django.core.exceptions import ValidationError + from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate - for option in ['max_length', 'blank']: - if option in kwargs: - raise Exception('You cannot specify the {0} option.' - .format(option)) - kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value + + + add_introspection_rules([ + ( + [MacAddrField], # model + [], # args + {'dhcp_enabled': ('dhcp_enabled', {})}, # kwargs + ) + ], [r'^cyder\.core\.fields\.MacAddrField'])
5493848ddca54a57a6dceb781bd417a9232cf1c4
tests/test_profile.py
tests/test_profile.py
import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" for record in caplog.records(): assert record.levelname == "CRITICAL" assert "No dodocs directory found" in caplog.text() @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split())
import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.fixture def profile_rm(): """Execute the command profile remove""" command_line = 'profile remove dodocs_pytest' dodocs.main(command_line.split()) @pytest.fixture def profile_edit(): """Execute the command profile edit""" command_line = 'profile edit dodocs_pytest' dodocs.main(command_line.split()) # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" record = caplog.records()[0] assert record.levelname == "CRITICAL" assert "No dodocs directory found" in record.message # profile removal def test_rm_no_exists(tmp_homedir, profile_rm, caplog): """Test that removing without a dodocs directory print a warning as first message""" record = caplog.records()[0] assert record.levelname == "WARNING" assert "Profile does not exist" in record.message # profile editing def test_edit_no_exists(tmp_homedir, profile_edit, caplog): """Test that removing without a dodocs directory print a warning as first message""" record = caplog.records()[0] assert record.levelname == "CRITICAL" assert "No dodocs directory found" in record.message @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split())
Add remove and edit on non existing dodocs directories
Add remove and edit on non existing dodocs directories
Python
mit
montefra/dodocs
import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) + @pytest.fixture + def profile_rm(): + """Execute the command profile remove""" + command_line = 'profile remove dodocs_pytest' + dodocs.main(command_line.split()) + + + @pytest.fixture + def profile_edit(): + """Execute the command profile edit""" + command_line = 'profile edit dodocs_pytest' + dodocs.main(command_line.split()) + + # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" - for record in caplog.records(): + record = caplog.records()[0] - assert record.levelname == "CRITICAL" + assert record.levelname == "CRITICAL" - assert "No dodocs directory found" in caplog.text() + assert "No dodocs directory found" in record.message + + + # profile removal + def test_rm_no_exists(tmp_homedir, profile_rm, caplog): + """Test that removing without a dodocs directory print a warning as first + message""" + record = caplog.records()[0] + assert record.levelname == "WARNING" + assert "Profile does not exist" in record.message + + + # profile editing + def test_edit_no_exists(tmp_homedir, profile_edit, caplog): + """Test that removing without a dodocs directory print a warning as first + message""" + record = caplog.records()[0] + assert record.levelname == "CRITICAL" + assert "No dodocs directory found" in record.message @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split())
Add remove and edit on non existing dodocs directories
## Code Before: import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" for record in caplog.records(): assert record.levelname == "CRITICAL" assert "No dodocs directory found" in caplog.text() @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split()) ## Instruction: Add remove and edit on non existing dodocs directories ## Code After: import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.fixture def profile_rm(): """Execute the command profile remove""" command_line = 'profile remove dodocs_pytest' dodocs.main(command_line.split()) @pytest.fixture def profile_edit(): """Execute the command profile edit""" command_line = 'profile edit dodocs_pytest' dodocs.main(command_line.split()) # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" record = caplog.records()[0] assert record.levelname == "CRITICAL" assert "No dodocs directory found" in record.message # profile removal def test_rm_no_exists(tmp_homedir, profile_rm, caplog): """Test that removing without a dodocs directory print a warning as first message""" record = caplog.records()[0] assert record.levelname == "WARNING" assert "Profile does not exist" in record.message # profile editing def test_edit_no_exists(tmp_homedir, profile_edit, caplog): """Test that removing without a dodocs directory print a warning as first message""" record = caplog.records()[0] assert record.levelname == "CRITICAL" assert "No dodocs directory found" in record.message @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split())
import pytest import dodocs # fixtures @pytest.fixture def profile_list(): """Execute the command profile list""" command_line = 'profile list' dodocs.main(command_line.split()) + @pytest.fixture + def profile_rm(): + """Execute the command profile remove""" + command_line = 'profile remove dodocs_pytest' + dodocs.main(command_line.split()) + + + @pytest.fixture + def profile_edit(): + """Execute the command profile edit""" + command_line = 'profile edit dodocs_pytest' + dodocs.main(command_line.split()) + + # profile listing def test_list_no_exist(tmp_homedir, profile_list, caplog): """Test that listing without a dodocs directory fails""" - for record in caplog.records(): ? ---- ^^ ^ + record = caplog.records()[0] ? ^ ^^^ - assert record.levelname == "CRITICAL" ? ---- + assert record.levelname == "CRITICAL" - assert "No dodocs directory found" in caplog.text() ? --- -- ---- + assert "No dodocs directory found" in record.message ? ++ ++++++++ + + + # profile removal + def test_rm_no_exists(tmp_homedir, profile_rm, caplog): + """Test that removing without a dodocs directory print a warning as first + message""" + record = caplog.records()[0] + assert record.levelname == "WARNING" + assert "Profile does not exist" in record.message + + + # profile editing + def test_edit_no_exists(tmp_homedir, profile_edit, caplog): + """Test that removing without a dodocs directory print a warning as first + message""" + record = caplog.records()[0] + assert record.levelname == "CRITICAL" + assert "No dodocs directory found" in record.message @pytest.mark.skipif("True") def test_list(): "List profiles" command_line = 'profile list' dodocs.main(command_line.split()) @pytest.mark.skipif("True") def test_create(): "List profiles" command_line = 'profile create' # dodocs.main(command_line.split())
3409aa543b4f0a4c574afd7ff4fdd59d1bd8a4b0
tests/date_tests.py
tests/date_tests.py
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
Revert "Progressing dots to show test is running"
Revert "Progressing dots to show test is running" Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150 This reverts commit 93379dbf499c58438917728b74862f282c15dba4. Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0
Python
mit
hasteur/g13bot_tools_new,smalyshev/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,npdoty/pywikibot,icyflame/batman,valhallasw/pywikibot-core,darthbhyrava/pywikibot-local,hasteur/g13bot_tools_new,xZise/pywikibot-core,npdoty/pywikibot,magul/pywikibot-core,happy5214/pywikibot-core,VcamX/pywikibot-core,h4ck3rm1k3/pywikibot-core,happy5214/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,Darkdadaah/pywikibot-core,hasteur/g13bot_tools_new,emijrp/pywikibot-core,wikimedia/pywikibot-core,jayvdb/pywikibot-core,trishnaguha/pywikibot-core,PersianWikipedia/pywikibot-core,magul/pywikibot-core,wikimedia/pywikibot-core
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" - def __init__(self, formatname): - super(TestDate, self).__init__() - self.formatname = formatname + def testMapEntry(self): + """Test the validity of the pywikibot.date format maps.""" + for formatName in date.formats: + step = 1 + if formatName in date.decadeFormats: + step = 10 + predicate, start, stop = date.formatLimits[formatName] - def testMapEntry(self, formatname): - """The test ported from date.py""" - step = 1 - if formatname in date.decadeFormats: - step = 10 - predicate, start, stop = date.formatLimits[formatname] + for code, convFunc in date.formats[formatName].items(): + for value in range(start, stop, step): + self.assertTrue( + predicate(value), + "date.formats['%(formatName)s']['%(code)s']:\n" + "invalid value %(value)d" % locals()) - for code, convFunc in date.formats[formatname].items(): - for value in range(start, stop, step): - self.assertTrue( - predicate(value), - "date.formats['%(formatname)s']['%(code)s']:\n" - "invalid value %(value)d" % locals()) - - newValue = convFunc(convFunc(value)) + newValue = convFunc(convFunc(value)) - self.assertEqual( + self.assertEqual( - newValue, value, + newValue, value, - "date.formats['%(formatname)s']['%(code)s']:\n" + "date.formats['%(formatName)s']['%(code)s']:\n" - "value %(newValue)d does not match %(value)s" + "value %(newValue)d does not match %(value)s" - % locals()) + % locals()) - - def runTest(self): - """method called by unittest""" - self.testMapEntry(self.formatname) - - - def suite(): - """Setup the test suite and register all test to different instances""" - suite = unittest.TestSuite() - suite.addTests(TestDate(formatname) for formatname in date.formats) - return suite if __name__ == '__main__': try: - unittest.TextTestRunner().run(suite()) + unittest.main() except SystemExit: pass
Revert "Progressing dots to show test is running"
## Code Before: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass ## Instruction: Revert "Progressing dots to show test is running" ## Code After: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" - def __init__(self, formatname): - super(TestDate, self).__init__() - self.formatname = formatname + def testMapEntry(self): + """Test the validity of the pywikibot.date format maps.""" + for formatName in date.formats: + step = 1 + if formatName in date.decadeFormats: + step = 10 + predicate, start, stop = date.formatLimits[formatName] - def testMapEntry(self, formatname): - """The test ported from date.py""" - step = 1 - if formatname in date.decadeFormats: - step = 10 - predicate, start, stop = date.formatLimits[formatname] + for code, convFunc in date.formats[formatName].items(): + for value in range(start, stop, step): + self.assertTrue( + predicate(value), + "date.formats['%(formatName)s']['%(code)s']:\n" + "invalid value %(value)d" % locals()) - for code, convFunc in date.formats[formatname].items(): - for value in range(start, stop, step): - self.assertTrue( - predicate(value), - "date.formats['%(formatname)s']['%(code)s']:\n" - "invalid value %(value)d" % locals()) - - newValue = convFunc(convFunc(value)) + newValue = convFunc(convFunc(value)) ? ++++ - self.assertEqual( + self.assertEqual( ? ++++ - newValue, value, + newValue, value, ? ++++ - "date.formats['%(formatname)s']['%(code)s']:\n" ? ^ + "date.formats['%(formatName)s']['%(code)s']:\n" ? ++++ ^ - "value %(newValue)d does not match %(value)s" + "value %(newValue)d does not match %(value)s" ? ++++ - % locals()) + % locals()) ? ++++ - - def runTest(self): - """method called by unittest""" - self.testMapEntry(self.formatname) - - - def suite(): - """Setup the test suite and register all test to different instances""" - suite = unittest.TestSuite() - suite.addTests(TestDate(formatname) for formatname in date.formats) - return suite if __name__ == '__main__': try: - unittest.TextTestRunner().run(suite()) + unittest.main() except SystemExit: pass
9516621f2b4cfc5b541c3328df95b62111e77463
app/main/__init__.py
app/main/__init__.py
from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists )
from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( crown_hosting, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists )
Delete reference to removed view
Delete reference to removed view
Python
mit
alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( - crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers, + crown_hosting, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists )
Delete reference to removed view
## Code Before: from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists ) ## Instruction: Delete reference to removed view ## Code After: from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( crown_hosting, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists )
from flask import Blueprint main = Blueprint('main', __name__) from . import errors from .views import ( - crown_hosting, digital_services_framework, g_cloud, login, marketplace, suppliers, ? ---------------------------- + crown_hosting, g_cloud, login, marketplace, suppliers, digital_outcomes_and_specialists )
fd2c03b2e6f48dac071b813b20cc2f70a2658f24
tests/test_path_paths.py
tests/test_path_paths.py
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False print "/".join(parts) assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ])
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ])
Print statement was breaking python 3 builds
Print statement was breaking python 3 builds
Python
mit
akesterson/dpath-python,calebcase/dpath-python,benthomasson/dpath-python,lexhung/dpath-python,pombredanne/dpath-python
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False - print "/".join(parts) assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ])
Print statement was breaking python 3 builds
## Code Before: import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False print "/".join(parts) assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ]) ## Instruction: Print statement was breaking python 3 builds ## Code After: import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ])
import nose from nose.tools import raises import dpath.path import dpath.exceptions import dpath.options @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_invalid_keyname(): tdict = { "I/contain/the/separator": 0 } for x in dpath.path.paths(tdict): pass @raises(dpath.exceptions.InvalidKeyName) def test_path_paths_empty_key_disallowed(): tdict = { "Empty": { "": { "Key": "" } } } for x in dpath.path.paths(tdict): pass def test_path_paths_empty_key_allowed(): tdict = { "Empty": { "": { "Key": "" } } } parts=[] dpath.options.ALLOW_EMPTY_STRING_KEYS=True for x in dpath.path.paths(tdict, dirs=False, leaves=True): path = x for x in path[:-1]: parts.append(x[0]) dpath.options.ALLOW_EMPTY_STRING_KEYS=False - print "/".join(parts) assert("/".join(parts) == "Empty//Key") def test_path_paths_int_keys(): dpath.path.validate([ ['I', dict], ['am', dict], ['path', dict], [0, dict], ['of', dict], [2, int] ])
09668c1818ef028e10669b9652e2f0ae255cc47e
src/pyscaffold/extensions/no_skeleton.py
src/pyscaffold/extensions/no_skeleton.py
from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = [opts['project'], 'src', opts['package'], 'skeleton.py'] struct = helpers.reject(struct, file) file = [opts['project'], 'tests', 'test_skeleton.py'] struct = helpers.reject(struct, file) return struct, opts
from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
Change extensions to use pathlib in helpers instead of lists
Change extensions to use pathlib in helpers instead of lists
Python
mit
blue-yonder/pyscaffold,blue-yonder/pyscaffold
+ + from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough - file = [opts['project'], 'src', opts['package'], 'skeleton.py'] + file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) - file = [opts['project'], 'tests', 'test_skeleton.py'] + file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
Change extensions to use pathlib in helpers instead of lists
## Code Before: from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = [opts['project'], 'src', opts['package'], 'skeleton.py'] struct = helpers.reject(struct, file) file = [opts['project'], 'tests', 'test_skeleton.py'] struct = helpers.reject(struct, file) return struct, opts ## Instruction: Change extensions to use pathlib in helpers instead of lists ## Code After: from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
+ + from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough - file = [opts['project'], 'src', opts['package'], 'skeleton.py'] ? ^ ^ + file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') ? ^^^^^ ^ struct = helpers.reject(struct, file) - file = [opts['project'], 'tests', 'test_skeleton.py'] ? ^ ^ + file = Path(opts['project'], 'tests', 'test_skeleton.py') ? ^^^^^ ^ struct = helpers.reject(struct, file) return struct, opts
923f6127eec0a6a576493f41d0f3b2fb9b6156d1
tests/Settings/TestContainerStack.py
tests/Settings/TestContainerStack.py
import UM.Settings def test_container_stack(): stack = UM.Settings.ContainerStack()
import pytest import uuid # For creating unique ID's for each container stack. import UM.Settings ## Creates a brand new container stack to test with. # # The container stack will get a new, unique ID. @pytest.fixture def container_stack(): return UM.Settings.ContainerStack(uuid.uuid4().int) def test_container_stack(container_stack): assert container_stack != None
Test creating container stack with fixture
Test creating container stack with fixture The fixture will automatically generate a unique ID. Contributes to issue CURA-1278.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
+ + import pytest + import uuid # For creating unique ID's for each container stack. import UM.Settings + ## Creates a brand new container stack to test with. + # + # The container stack will get a new, unique ID. + @pytest.fixture - def test_container_stack(): + def container_stack(): - stack = UM.Settings.ContainerStack() + return UM.Settings.ContainerStack(uuid.uuid4().int) + def test_container_stack(container_stack): + assert container_stack != None + +
Test creating container stack with fixture
## Code Before: import UM.Settings def test_container_stack(): stack = UM.Settings.ContainerStack() ## Instruction: Test creating container stack with fixture ## Code After: import pytest import uuid # For creating unique ID's for each container stack. import UM.Settings ## Creates a brand new container stack to test with. # # The container stack will get a new, unique ID. @pytest.fixture def container_stack(): return UM.Settings.ContainerStack(uuid.uuid4().int) def test_container_stack(container_stack): assert container_stack != None
+ + import pytest + import uuid # For creating unique ID's for each container stack. import UM.Settings + ## Creates a brand new container stack to test with. + # + # The container stack will get a new, unique ID. + @pytest.fixture - def test_container_stack(): ? ----- + def container_stack(): - stack = UM.Settings.ContainerStack() + return UM.Settings.ContainerStack(uuid.uuid4().int) + + def test_container_stack(container_stack): + assert container_stack != None +
5c8fd314dd89d8964cc5cb75c2b57ed32be275c5
plsync/users.py
plsync/users.py
user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), ('Matt', 'Mathis', '[email protected]')]
user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), ('Matt', 'Mathis', '[email protected]') ('Peter', 'Boothe', '[email protected]')]
Add pboothe temporarily for testing
Add pboothe temporarily for testing
Python
apache-2.0
jheretic/operator,stephen-soltesz/operator,nkinkade/operator,critzo/operator,critzo/operator,jheretic/operator,nkinkade/operator,m-lab/operator,salarcon215/operator,m-lab/operator,salarcon215/operator,stephen-soltesz/operator
user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), - ('Matt', 'Mathis', '[email protected]')] + ('Matt', 'Mathis', '[email protected]') + ('Peter', 'Boothe', '[email protected]')]
Add pboothe temporarily for testing
## Code Before: user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), ('Matt', 'Mathis', '[email protected]')] ## Instruction: Add pboothe temporarily for testing ## Code After: user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), ('Matt', 'Mathis', '[email protected]') ('Peter', 'Boothe', '[email protected]')]
user_list = [('Stephen', 'Stuart', '[email protected]'), ('Will', 'Hawkins', '[email protected]'), ('Jordan', 'McCarthy', '[email protected]'), ('Chris', 'Ritzo', '[email protected]'), ('Josh', 'Bailey', '[email protected]'), ('Steph', 'Alarcon', '[email protected]'), ('Nathan', 'Kinkade', '[email protected]'), - ('Matt', 'Mathis', '[email protected]')] ? - + ('Matt', 'Mathis', '[email protected]') + ('Peter', 'Boothe', '[email protected]')]
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312
ideascube/mediacenter/tests/factories.py
ideascube/mediacenter/tests/factories.py
from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
Allow DocumentFactory to handle preview field.
Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
from django.conf import settings import factory from ..models import Document + class EmptyFileField(factory.django.FileField): + DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() + preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
Allow DocumentFactory to handle preview field.
## Code Before: from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document ## Instruction: Allow DocumentFactory to handle preview field. ## Code After: from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
from django.conf import settings import factory from ..models import Document + class EmptyFileField(factory.django.FileField): + DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() + preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
fa191537e15dd0729deb94aaa91dbb7fa9295e04
mathdeck/loadproblem.py
mathdeck/loadproblem.py
import os import sys # Load problem file as def load_file_as_module(file): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_module',file) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader("prob_module",file) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
import os import sys # Load problem file as def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
Change package name in loadmodule call
Change package name in loadmodule call Not much reason to do this. It just happened.
Python
apache-2.0
patrickspencer/mathdeck,patrickspencer/mathdeck
import os import sys # Load problem file as - def load_file_as_module(file): + def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp - problem_module = imp.load_source('prob_module',file) + problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ - .SourceFileLoader("prob_module",file) \ + .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
Change package name in loadmodule call
## Code Before: import os import sys # Load problem file as def load_file_as_module(file): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_module',file) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader("prob_module",file) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module ## Instruction: Change package name in loadmodule call ## Code After: import os import sys # Load problem file as def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
import os import sys # Load problem file as - def load_file_as_module(file): + def load_file_as_module(file_path): ? +++++ """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp - problem_module = imp.load_source('prob_module',file) ? ^^^ + problem_module = imp.load_source('prob_mod_pkg',file_path) ? ^^^^ +++++ if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ - .SourceFileLoader("prob_module",file) \ ? ^ ^^^^ + .SourceFileLoader('prob_mod_pkg',file_path) \ ? ^ ^^^^^ +++++ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
096bd7e3357e85c57ec56695bfc16f0b4eab9c4d
pystil.py
pystil.py
from pystil import app, config import werkzeug.contrib import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = Application(werkzeug.contrib.fixers.ProxyFix(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
from pystil import app, config import werkzeug.contrib.fixers import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = werkzeug.contrib.fixers.ProxyFix(Application(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
Add the good old middleware
Add the good old middleware
Python
bsd-3-clause
Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil
from pystil import app, config - import werkzeug.contrib + import werkzeug.contrib.fixers import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi - application = Application(werkzeug.contrib.fixers.ProxyFix(app())) + application = werkzeug.contrib.fixers.ProxyFix(Application(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
Add the good old middleware
## Code Before: from pystil import app, config import werkzeug.contrib import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = Application(werkzeug.contrib.fixers.ProxyFix(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever() ## Instruction: Add the good old middleware ## Code After: from pystil import app, config import werkzeug.contrib.fixers import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi application = werkzeug.contrib.fixers.ProxyFix(Application(app())) ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
from pystil import app, config - import werkzeug.contrib + import werkzeug.contrib.fixers ? +++++++ import sys config.freeze() if 'soup' in sys.argv: from os import getenv from sqlalchemy import create_engine from sqlalchemy.ext.sqlsoup import SqlSoup import code engine = create_engine(config.CONFIG["DB_URL"], echo=True) db = SqlSoup(engine) Visit = db.visit Keys = db.keys class FunkyConsole(code.InteractiveConsole): def showtraceback(self): import pdb import sys code.InteractiveConsole.showtraceback(self) pdb.post_mortem(sys.exc_info()[2]) console = FunkyConsole(locals=globals()) if getenv("PYTHONSTARTUP"): execfile(getenv("PYTHONSTARTUP")) console.interact() else: from pystil.service.http import Application from gevent import monkey monkey.patch_all() import gevent.wsgi - application = Application(werkzeug.contrib.fixers.ProxyFix(app())) ? ------------ + application = werkzeug.contrib.fixers.ProxyFix(Application(app())) ? ++++++++++++ ws = gevent.wsgi.WSGIServer(('', 1789), application) ws.serve_forever()
215622e070860cb24c032186d768c6b341ad27fb
nemubot.py
nemubot.py
import sys import os import imp import traceback servers = dict() print ("Nemubot ready, my PID is %i!" % (os.getpid())) prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
import sys import os import imp import traceback servers = dict() prompt = __import__ ("prompt") if len(sys.argv) >= 2: for arg in sys.argv[1:]: prompt.load_file(arg, servers) print ("Nemubot ready, my PID is %i!" % (os.getpid())) while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
Load files given in arguments
Load files given in arguments
Python
agpl-3.0
nemunaire/nemubot,nbr23/nemubot,Bobobol/nemubot-1
import sys import os import imp import traceback servers = dict() + prompt = __import__ ("prompt") + + if len(sys.argv) >= 2: + for arg in sys.argv[1:]: + prompt.load_file(arg, servers) + print ("Nemubot ready, my PID is %i!" % (os.getpid())) - prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
Load files given in arguments
## Code Before: import sys import os import imp import traceback servers = dict() print ("Nemubot ready, my PID is %i!" % (os.getpid())) prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0) ## Instruction: Load files given in arguments ## Code After: import sys import os import imp import traceback servers = dict() prompt = __import__ ("prompt") if len(sys.argv) >= 2: for arg in sys.argv[1:]: prompt.load_file(arg, servers) print ("Nemubot ready, my PID is %i!" % (os.getpid())) while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
import sys import os import imp import traceback servers = dict() + prompt = __import__ ("prompt") + + if len(sys.argv) >= 2: + for arg in sys.argv[1:]: + prompt.load_file(arg, servers) + print ("Nemubot ready, my PID is %i!" % (os.getpid())) - prompt = __import__ ("prompt") while prompt.launch(servers): try: imp.reload(prompt) except: print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.") exc_type, exc_value, exc_traceback = sys.exc_info() sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0]) print ("Bye") sys.exit(0)
3cfa4f48c6bf28ed4273004d9a44173ecb4b195c
parliament/templatetags/parliament.py
parliament/templatetags/parliament.py
from django import template register = template.Library() @register.filter(name='governing') def governing(party, date): return party.is_governing(date)
from django import template from ..models import Party, Statement register = template.Library() @register.filter(name='governing') def governing(obj, date=None): if isinstance(obj, Party): assert date is not None, "Date must be supplied when 'govern' is called with a Party object" return obj.is_governing(date) elif isinstance(obj, Statement): if obj.member is None: if 'ministeri' in obj.speaker_role: return True else: return False if date is None: date = obj.item.plsess.date return obj.member.party.is_governing(date)
Allow governing templatetag to be called with a Statement object
Allow governing templatetag to be called with a Statement object
Python
agpl-3.0
kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu
from django import template + from ..models import Party, Statement register = template.Library() @register.filter(name='governing') - def governing(party, date): + def governing(obj, date=None): + if isinstance(obj, Party): + assert date is not None, "Date must be supplied when 'govern' is called with a Party object" - return party.is_governing(date) + return obj.is_governing(date) + elif isinstance(obj, Statement): + if obj.member is None: + if 'ministeri' in obj.speaker_role: + return True + else: + return False + if date is None: + date = obj.item.plsess.date + return obj.member.party.is_governing(date) -
Allow governing templatetag to be called with a Statement object
## Code Before: from django import template register = template.Library() @register.filter(name='governing') def governing(party, date): return party.is_governing(date) ## Instruction: Allow governing templatetag to be called with a Statement object ## Code After: from django import template from ..models import Party, Statement register = template.Library() @register.filter(name='governing') def governing(obj, date=None): if isinstance(obj, Party): assert date is not None, "Date must be supplied when 'govern' is called with a Party object" return obj.is_governing(date) elif isinstance(obj, Statement): if obj.member is None: if 'ministeri' in obj.speaker_role: return True else: return False if date is None: date = obj.item.plsess.date return obj.member.party.is_governing(date)
from django import template + from ..models import Party, Statement register = template.Library() @register.filter(name='governing') - def governing(party, date): ? ^^^^^ + def governing(obj, date=None): ? ^^^ +++++ + if isinstance(obj, Party): + assert date is not None, "Date must be supplied when 'govern' is called with a Party object" - return party.is_governing(date) ? ^^^^^ + return obj.is_governing(date) ? ++++ ^^^ - + elif isinstance(obj, Statement): + if obj.member is None: + if 'ministeri' in obj.speaker_role: + return True + else: + return False + if date is None: + date = obj.item.plsess.date + return obj.member.party.is_governing(date)
ef7910d259f3a7d025e95ad69345da457a777b90
myvoice/urls.py
myvoice/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use Django 1.7 syntax for URLs
Use Django 1.7 syntax for URLs
Python
bsd-2-clause
myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice
from django.conf import settings - from django.conf.urls import patterns, include, url + from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() - urlpatterns = patterns('', + urlpatterns = [ url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), - ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use Django 1.7 syntax for URLs
## Code Before: from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ## Instruction: Use Django 1.7 syntax for URLs ## Code After: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings - from django.conf.urls import patterns, include, url ? ---------- + from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() - urlpatterns = patterns('', + urlpatterns = [ url(r'^', include('myvoice.core.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^broadcast/', include('broadcast.urls')), url(r'^groups/', include('groups.urls')), url(r'^decisiontree/', include('decisiontree.urls')), url(r'^pbf/', include('myvoice.pbf.urls')), - ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ? ^ + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ? ^
5d6b384a2f1b8caa9421b428e5d81aaa1d9a82e1
tests/correct.py
tests/correct.py
"""Check ringtophat results against scipy.ndimage.convolve"""
"""Check ringtophat results against scipy.ndimage.convolve""" import unittest from numpy.testing import assert_equal, assert_almost_equal import numpy as np import ringtophat class TestKernels(unittest.TestCase): def test_binary_disk(self): actual = ringtophat.binary_disk(1) desired = np.array([[False, True, False], [ True, True, True], [False, True, False]]) assert_equal(actual, desired) def test_binary_ring(self): actual = ringtophat.binary_ring(1, 2) desired = np.array([[False, False, True, False, False], [False, True, True, True, False], [ True, True, False, True, True], [False, True, True, True, False], [False, False, True, False, False]]) assert_equal(actual, desired) if __name__ == '__main__': unittest.main()
Add first tests. disk and ring masks for simple cases.
Add first tests. disk and ring masks for simple cases.
Python
bsd-3-clause
gammapy/ringtophat,gammapy/ringtophat
"""Check ringtophat results against scipy.ndimage.convolve""" + import unittest + from numpy.testing import assert_equal, assert_almost_equal + import numpy as np + import ringtophat + + class TestKernels(unittest.TestCase): + def test_binary_disk(self): + actual = ringtophat.binary_disk(1) + desired = np.array([[False, True, False], + [ True, True, True], + [False, True, False]]) + assert_equal(actual, desired) + def test_binary_ring(self): + actual = ringtophat.binary_ring(1, 2) + desired = np.array([[False, False, True, False, False], + [False, True, True, True, False], + [ True, True, False, True, True], + [False, True, True, True, False], + [False, False, True, False, False]]) + assert_equal(actual, desired) + + if __name__ == '__main__': + unittest.main() + +
Add first tests. disk and ring masks for simple cases.
## Code Before: """Check ringtophat results against scipy.ndimage.convolve""" ## Instruction: Add first tests. disk and ring masks for simple cases. ## Code After: """Check ringtophat results against scipy.ndimage.convolve""" import unittest from numpy.testing import assert_equal, assert_almost_equal import numpy as np import ringtophat class TestKernels(unittest.TestCase): def test_binary_disk(self): actual = ringtophat.binary_disk(1) desired = np.array([[False, True, False], [ True, True, True], [False, True, False]]) assert_equal(actual, desired) def test_binary_ring(self): actual = ringtophat.binary_ring(1, 2) desired = np.array([[False, False, True, False, False], [False, True, True, True, False], [ True, True, False, True, True], [False, True, True, True, False], [False, False, True, False, False]]) assert_equal(actual, desired) if __name__ == '__main__': unittest.main()
"""Check ringtophat results against scipy.ndimage.convolve""" + import unittest + from numpy.testing import assert_equal, assert_almost_equal + import numpy as np + import ringtophat + + class TestKernels(unittest.TestCase): + def test_binary_disk(self): + actual = ringtophat.binary_disk(1) + desired = np.array([[False, True, False], + [ True, True, True], + [False, True, False]]) + assert_equal(actual, desired) + def test_binary_ring(self): + actual = ringtophat.binary_ring(1, 2) + desired = np.array([[False, False, True, False, False], + [False, True, True, True, False], + [ True, True, False, True, True], + [False, True, True, True, False], + [False, False, True, False, False]]) + assert_equal(actual, desired) + + if __name__ == '__main__': + unittest.main() +
3daa15b0ccb3fc4891daf55724cbeaa705f923e5
scripts/clio_daemon.py
scripts/clio_daemon.py
import logging import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app logger = logging.getLogger() if logger.handlers: [app.logger.addHandler(h) for h in logger.handlers] app.logger.setLevel(logger.level) eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main()
import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main()
Revert "output flask logging into simpledaemon's log file."
Revert "output flask logging into simpledaemon's log file." This is completely superfluous - logging does this already automatically. This reverts commit 18091efef351ecddb1d29ee7d01d0a7fb567a7b7.
Python
apache-2.0
geodelic/clio,geodelic/clio
- - import logging import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app - logger = logging.getLogger() - if logger.handlers: - [app.logger.addHandler(h) for h in logger.handlers] - app.logger.setLevel(logger.level) eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main()
Revert "output flask logging into simpledaemon's log file."
## Code Before: import logging import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app logger = logging.getLogger() if logger.handlers: [app.logger.addHandler(h) for h in logger.handlers] app.logger.setLevel(logger.level) eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main() ## Instruction: Revert "output flask logging into simpledaemon's log file." ## Code After: import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main()
- - import logging import simpledaemon class clio_daemon(simpledaemon.Daemon): default_conf = 'clio_daemon.conf' section = 'clio' def run(self): import eventlet from clio.store import app - logger = logging.getLogger() - if logger.handlers: - [app.logger.addHandler(h) for h in logger.handlers] - app.logger.setLevel(logger.level) eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app) if __name__ == '__main__': clio_daemon().main()
ea42e8c61bddf614a5fc444b53eb38dcdcff88af
HotCIDR/hotcidr/ports.py
HotCIDR/hotcidr/ports.py
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): assert(isinstance(fromport, int)) assert(isinstance(toport, int)) self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__
Check that input to port is an integer
Check that input to port is an integer
Python
apache-2.0
ViaSat/hotcidr
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): + assert(isinstance(fromport, int)) + assert(isinstance(toport, int)) self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__
Check that input to port is an integer
## Code Before: def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__ ## Instruction: Check that input to port is an integer ## Code After: def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): assert(isinstance(fromport, int)) assert(isinstance(toport, int)) self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__
def parse(s): try: return Port(int(s)) except ValueError: if s == "all": return Port(None) else: start, _, end = s.partition('-') try: return Port(int(start), int(end)) except ValueError: return None class Port(object): def __init__(self, fromport, toport=None): + assert(isinstance(fromport, int)) + assert(isinstance(toport, int)) self._fromport = fromport if toport: self._toport = toport else: self._toport = fromport @property def fromport(self): return self._fromport @property def toport(self): return self._toport @property def all(self): return self.fromport == None and self.toport == None def yaml_str(self): if self.all: return "all" elif self.fromport < self.toport: return "%d-%d" % (self.fromport, self.toport) else: return self.fromport def __hash__(self): return hash((self.fromport, self.toport)) def __eq__(self, other): return self.__dict__ == other.__dict__
e4193b7082cf3d891c993905443415a613630f8f
mailtemplates/model/sqla/models.py
mailtemplates/model/sqla/models.py
from sqlalchemy import ForeignKey, Column from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(Text(), nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(Text())
from sqlalchemy import ForeignKey, Column, UnicodeText from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(UnicodeText, nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(UnicodeText())
Change type from text to UnicodeText
Change type from text to UnicodeText
Python
mit
axant/tgapp-mailtemplates,axant/tgapp-mailtemplates
- from sqlalchemy import ForeignKey, Column + from sqlalchemy import ForeignKey, Column, UnicodeText from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) - usage = Column(Text(), nullable=False) + usage = Column(UnicodeText, nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) - body = Column(Text()) + body = Column(UnicodeText())
Change type from text to UnicodeText
## Code Before: from sqlalchemy import ForeignKey, Column from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(Text(), nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(Text()) ## Instruction: Change type from text to UnicodeText ## Code After: from sqlalchemy import ForeignKey, Column, UnicodeText from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) usage = Column(UnicodeText, nullable=False) class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) body = Column(UnicodeText())
- from sqlalchemy import ForeignKey, Column + from sqlalchemy import ForeignKey, Column, UnicodeText ? +++++++++++++ from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import Unicode, Integer from sqlalchemy.orm import backref, relation from tgext.pluggable import app_model, primary_key DeclarativeBase = declarative_base() class MailModel(DeclarativeBase): __tablename__ = 'mailtemplates_mail_models' _id = Column(Integer, autoincrement=True, primary_key=True) name = Column(Unicode(128), unique=True, nullable=False) - usage = Column(Text(), nullable=False) ? -- + usage = Column(UnicodeText, nullable=False) ? +++++++ class TemplateTranslation(DeclarativeBase): __tablename__ = 'mailtemplates_template_translations' _id = Column(Integer, autoincrement=True, primary_key=True) mail_model_id = Column(Integer, ForeignKey(primary_key(MailModel))) mail_model = relation(MailModel, backref=backref('template_translations')) language = Column(Unicode(128), nullable=False) subject = Column(Unicode(500)) - body = Column(Text()) + body = Column(UnicodeText()) ? +++++++
5fd04a337dd6fec1afc9bf53b437cce01e4fef9e
myDevices/os/threadpool.py
myDevices/os/threadpool.py
from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton import inspect executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): def Submit(something): future = executor.submit(something) def SubmitParam(*arg): executor.submit(*arg) def Shutdown(): executor.shutdown()
from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): """Singleton thread pool class""" @staticmethod def Submit(func): """Submit a function for the thread pool to run""" executor.submit(func) @staticmethod def Shutdown(): """Shutdown the thread pool""" executor.shutdown()
Clean up thread pool code.
Clean up thread pool code.
Python
mit
myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent
- from concurrent.futures import ThreadPoolExecutor + from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton - import inspect executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): - def Submit(something): - future = executor.submit(something) - def SubmitParam(*arg): - executor.submit(*arg) + """Singleton thread pool class""" + + @staticmethod + def Submit(func): + """Submit a function for the thread pool to run""" + executor.submit(func) + + @staticmethod - def Shutdown(): + def Shutdown(): + """Shutdown the thread pool""" - executor.shutdown() + executor.shutdown() +
Clean up thread pool code.
## Code Before: from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton import inspect executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): def Submit(something): future = executor.submit(something) def SubmitParam(*arg): executor.submit(*arg) def Shutdown(): executor.shutdown() ## Instruction: Clean up thread pool code. ## Code After: from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): """Singleton thread pool class""" @staticmethod def Submit(func): """Submit a function for the thread pool to run""" executor.submit(func) @staticmethod def Shutdown(): """Shutdown the thread pool""" executor.shutdown()
- from concurrent.futures import ThreadPoolExecutor ? - + from concurrent.futures import ThreadPoolExecutor from myDevices.utils.singleton import Singleton - import inspect executor = ThreadPoolExecutor(max_workers=4) class ThreadPool(Singleton): - def Submit(something): - future = executor.submit(something) - def SubmitParam(*arg): - executor.submit(*arg) + """Singleton thread pool class""" + + @staticmethod + def Submit(func): + """Submit a function for the thread pool to run""" + executor.submit(func) + + @staticmethod - def Shutdown(): ? ^ + def Shutdown(): ? ^^^^ + """Shutdown the thread pool""" - executor.shutdown() ? ^^ + executor.shutdown() ? ^^^^^^^^ +
ff4204659b158827070fbb4bdf9bfc1f263e8b33
fanstatic/registry.py
fanstatic/registry.py
import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): if libraries is None: return for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry
import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry
Remove some code that wasn't in use anymore.
Remove some code that wasn't in use anymore.
Python
bsd-3-clause
fanstatic/fanstatic,fanstatic/fanstatic
import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): - if libraries is None: - return for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry
Remove some code that wasn't in use anymore.
## Code Before: import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): if libraries is None: return for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry ## Instruction: Remove some code that wasn't in use anymore. ## Code After: import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry
import pkg_resources ENTRY_POINT = 'fanstatic.libraries' class LibraryRegistry(dict): """A dictionary-like registry of libraries. This is a dictionary that mains libraries. A value is a :py:class:`Library` instance, and a key is its library ``name``. Normally there is only a single global LibraryRegistry, obtained by calling ``get_library_registry()``. :param libraries: a sequence of libraries """ def __init__(self, libraries): - if libraries is None: - return for library in libraries: self[library.name] = library def add(self, library): """Add a Library instance to the registry. :param add: add a library to the registry. """ self[library.name] = library def get_libraries_from_entry_points(): libraries = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT): libraries.append(entry_point.load()) return libraries _library_registry = None def get_library_registry(): '''Get the global :py:class:`LibraryRegistry`. It gets filled with the libraries registered using the fanstatic entry point. You can also add libraries to it later. ''' global _library_registry if _library_registry is not None: return _library_registry _library_registry = LibraryRegistry(get_libraries_from_entry_points()) return _library_registry
e1e7189bbe859d6dfa6f883d2ff46ff1faed4842
scrape.py
scrape.py
import scholarly import requests _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' def search(query, start_year, end_year): """Search by scholar query and return a generator of Publication objects""" soup = scholarly._get_soup( _SEARCH.format(requests.utils.quote(query), str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", 2015, 2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
import scholarly import requests _EXACT_SEARCH = '/scholar?q="{}"' _START_YEAR = '&as_ylo={}' _END_YEAR = '&as_yhi={}' def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" url = _EXACT_SEARCH.format(requests.utils.quote(query)) if start_year: url += _START_YEAR.format(start_year) if end_year: url += _END_YEAR.format(end_year) soup = scholarly._get_soup(url) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
Make year range arguments optional in search
Make year range arguments optional in search
Python
mit
Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker
import scholarly import requests - _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' + _EXACT_SEARCH = '/scholar?q="{}"' + _START_YEAR = '&as_ylo={}' + _END_YEAR = '&as_yhi={}' - def search(query, start_year, end_year): + def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" + url = _EXACT_SEARCH.format(requests.utils.quote(query)) + if start_year: + url += _START_YEAR.format(start_year) + if end_year: + url += _END_YEAR.format(end_year) - soup = scholarly._get_soup( + soup = scholarly._get_soup(url) - _SEARCH.format(requests.utils.quote(query), - str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': - s = search("Cure Alzheimer's Fund", 2015, 2015) + s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
Make year range arguments optional in search
## Code Before: import scholarly import requests _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' def search(query, start_year, end_year): """Search by scholar query and return a generator of Publication objects""" soup = scholarly._get_soup( _SEARCH.format(requests.utils.quote(query), str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", 2015, 2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num) ## Instruction: Make year range arguments optional in search ## Code After: import scholarly import requests _EXACT_SEARCH = '/scholar?q="{}"' _START_YEAR = '&as_ylo={}' _END_YEAR = '&as_yhi={}' def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" url = _EXACT_SEARCH.format(requests.utils.quote(query)) if start_year: url += _START_YEAR.format(start_year) if end_year: url += _END_YEAR.format(end_year) soup = scholarly._get_soup(url) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
import scholarly import requests - _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' + _EXACT_SEARCH = '/scholar?q="{}"' + _START_YEAR = '&as_ylo={}' + _END_YEAR = '&as_yhi={}' - def search(query, start_year, end_year): + def search(query, exact=True, start_year=None, end_year=None): ? ++++++++++++ +++++ +++++ """Search by scholar query and return a generator of Publication objects""" + url = _EXACT_SEARCH.format(requests.utils.quote(query)) + if start_year: + url += _START_YEAR.format(start_year) + if end_year: + url += _END_YEAR.format(end_year) - soup = scholarly._get_soup( + soup = scholarly._get_soup(url) ? ++++ - _SEARCH.format(requests.utils.quote(query), - str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': - s = search("Cure Alzheimer's Fund", 2015, 2015) + s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) ? +++++++++++ +++++++++ num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
6705b4eb603f69681357a5f71f02e81705ea5e17
setup.py
setup.py
from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', requires=['bitstring'], install_requires=['bitstring'], long_description=long_description, data_files=[('', ['README.md'])] )
from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', requires=['bitstring', 'six'], install_requires=['bitstring', 'six'], long_description=long_description, data_files=[('', ['README.md'])] )
Add six as dependency to fix import issue
Add six as dependency to fix import issue
Python
mit
use-sparingly/pymp4parse
from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', - requires=['bitstring'], + requires=['bitstring', 'six'], - install_requires=['bitstring'], + install_requires=['bitstring', 'six'], long_description=long_description, data_files=[('', ['README.md'])] )
Add six as dependency to fix import issue
## Code Before: from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', requires=['bitstring'], install_requires=['bitstring'], long_description=long_description, data_files=[('', ['README.md'])] ) ## Instruction: Add six as dependency to fix import issue ## Code After: from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', requires=['bitstring', 'six'], install_requires=['bitstring', 'six'], long_description=long_description, data_files=[('', ['README.md'])] )
from distutils.core import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name='pymp4parse', version='0.3.0', packages=[''], url='https://github.com/use-sparingly/pymp4parse', license='The MIT License', author='Alastair Mccormack', author_email='alastair at alu.media', description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser', - requires=['bitstring'], + requires=['bitstring', 'six'], ? +++++++ - install_requires=['bitstring'], + install_requires=['bitstring', 'six'], ? +++++++ long_description=long_description, data_files=[('', ['README.md'])] )
301a70469dba6fdfe8d72d3d70fa75e4146756c6
integration-test/843-normalize-underscore.py
integration-test/843-normalize-underscore.py
assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 # verify that no aerialway subkind exists when its value is yes with features_in_tile_layer(16, 10910, 25120, 'roads') as features: for feature in features: props = feature['properties'] if props['id'] == 258132198: assert props['kind'] == 'aerialway' assert 'aerialway' not in props break else: assert 0, 'No feature with id 258132198 found'
assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 assert_has_feature( 16, 10910, 25120, 'roads', { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) })
Simplify test to check for no aerialway property
Simplify test to check for no aerialway property
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 + assert_has_feature( + 16, 10910, 25120, 'roads', + { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) }) - # verify that no aerialway subkind exists when its value is yes - with features_in_tile_layer(16, 10910, 25120, 'roads') as features: - for feature in features: - props = feature['properties'] - if props['id'] == 258132198: - assert props['kind'] == 'aerialway' - assert 'aerialway' not in props - break - else: - assert 0, 'No feature with id 258132198 found'
Simplify test to check for no aerialway property
## Code Before: assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 # verify that no aerialway subkind exists when its value is yes with features_in_tile_layer(16, 10910, 25120, 'roads') as features: for feature in features: props = feature['properties'] if props['id'] == 258132198: assert props['kind'] == 'aerialway' assert 'aerialway' not in props break else: assert 0, 'No feature with id 258132198 found' ## Instruction: Simplify test to check for no aerialway property ## Code After: assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 assert_has_feature( 16, 10910, 25120, 'roads', { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) })
assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialway': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'aerialway': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 + assert_has_feature( + 16, 10910, 25120, 'roads', + { 'id': 258132198, 'kind': 'aerialway', 'aerialway': type(None) }) - # verify that no aerialway subkind exists when its value is yes - with features_in_tile_layer(16, 10910, 25120, 'roads') as features: - for feature in features: - props = feature['properties'] - if props['id'] == 258132198: - assert props['kind'] == 'aerialway' - assert 'aerialway' not in props - break - else: - assert 0, 'No feature with id 258132198 found'
a36fe5002bbf5dfcf27a3251cfed85c341e2156d
cbcollections.py
cbcollections.py
class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: return self.default_factory()
class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: self[key] = self.default_factory() return self[key]
Save generated value for defaultdict
MB-6867: Save generated value for defaultdict Instead of just returning value, keep it in dict. Change-Id: I2a9862503b71f2234a4a450c48998b5f53a951bc Reviewed-on: http://review.couchbase.org/21602 Tested-by: Bin Cui <[email protected]> Reviewed-by: Pavel Paulau <[email protected]>
Python
apache-2.0
couchbase/couchbase-cli,couchbaselabs/couchbase-cli,membase/membase-cli,membase/membase-cli,couchbase/couchbase-cli,membase/membase-cli,couchbaselabs/couchbase-cli,couchbaselabs/couchbase-cli
class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: - return self.default_factory() + self[key] = self.default_factory() + return self[key]
Save generated value for defaultdict
## Code Before: class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: return self.default_factory() ## Instruction: Save generated value for defaultdict ## Code After: class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: self[key] = self.default_factory() return self[key]
class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is None: return super(defaultdict, self).__getitem__(key) else: try: return super(defaultdict, self).__getitem__(key) except KeyError: - return self.default_factory() ? ^ ^^^^ + self[key] = self.default_factory() ? ^ ^^^^^^^^^ + return self[key]
6dab43543e1b6a1e1e8119db9b38cc685dd81f82
ckanext/qa/controllers/base.py
ckanext/qa/controllers/base.py
from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): def __init__(self, *args, **kwargs): super(QAController, self).__init(*args, **kwargs)
from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): pass
Fix typo in constructor. Seems unnecessary anyway.
Fix typo in constructor. Seems unnecessary anyway.
Python
mit
ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa
from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): + pass - def __init__(self, *args, **kwargs): - super(QAController, self).__init(*args, **kwargs)
Fix typo in constructor. Seems unnecessary anyway.
## Code Before: from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): def __init__(self, *args, **kwargs): super(QAController, self).__init(*args, **kwargs) ## Instruction: Fix typo in constructor. Seems unnecessary anyway. ## Code After: from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): pass
from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): + pass - - def __init__(self, *args, **kwargs): - super(QAController, self).__init(*args, **kwargs)
fea76a8c9c03fef5c70e2fdd93d97cd3e096de7d
tests/test_mysql.py
tests/test_mysql.py
import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) # Service checks service_checks = self.check.get_service_checks() service_checks_count = len(service_checks) self.assertTrue(type(service_checks) == type([])) self.assertTrue(service_checks_count > 0) self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks) # Assert that all service checks have the proper tags: host and port self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks) self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
Add test for Mysql sc
Add test for Mysql sc
Python
bsd-3-clause
brettlangdon/dd-agent,truthbk/dd-agent,jraede/dd-agent,relateiq/dd-agent,cberry777/dd-agent,tebriel/dd-agent,urosgruber/dd-agent,jraede/dd-agent,ess/dd-agent,Shopify/dd-agent,joelvanvelden/dd-agent,jyogi/purvar-agent,eeroniemi/dd-agent,citrusleaf/dd-agent,indeedops/dd-agent,eeroniemi/dd-agent,Mashape/dd-agent,AniruddhaSAtre/dd-agent,c960657/dd-agent,lookout/dd-agent,pfmooney/dd-agent,truthbk/dd-agent,PagerDuty/dd-agent,c960657/dd-agent,jvassev/dd-agent,benmccann/dd-agent,pmav99/praktoras,relateiq/dd-agent,PagerDuty/dd-agent,gphat/dd-agent,citrusleaf/dd-agent,tebriel/dd-agent,AntoCard/powerdns-recursor_check,jvassev/dd-agent,darron/dd-agent,yuecong/dd-agent,yuecong/dd-agent,zendesk/dd-agent,mderomph-coolblue/dd-agent,benmccann/dd-agent,urosgruber/dd-agent,manolama/dd-agent,citrusleaf/dd-agent,cberry777/dd-agent,ess/dd-agent,cberry777/dd-agent,a20012251/dd-agent,tebriel/dd-agent,mderomph-coolblue/dd-agent,AntoCard/powerdns-recursor_check,jshum/dd-agent,JohnLZeller/dd-agent,AntoCard/powerdns-recursor_check,jshum/dd-agent,pfmooney/dd-agent,ess/dd-agent,PagerDuty/dd-agent,joelvanvelden/dd-agent,AntoCard/powerdns-recursor_check,packetloop/dd-agent,Shopify/dd-agent,pmav99/praktoras,PagerDuty/dd-agent,Shopify/dd-agent,takus/dd-agent,packetloop/dd-agent,relateiq/dd-agent,gphat/dd-agent,jraede/dd-agent,packetloop/dd-agent,gphat/dd-agent,yuecong/dd-agent,jamesandariese/dd-agent,guruxu/dd-agent,huhongbo/dd-agent,pmav99/praktoras,huhongbo/dd-agent,zendesk/dd-agent,brettlangdon/dd-agent,lookout/dd-agent,a20012251/dd-agent,Wattpad/dd-agent,urosgruber/dd-agent,indeedops/dd-agent,takus/dd-agent,GabrielNicolasAvellaneda/dd-agent,polynomial/dd-agent,AntoCard/powerdns-recursor_check,joelvanvelden/dd-agent,JohnLZeller/dd-agent,ess/dd-agent,mderomph-coolblue/dd-agent,Wattpad/dd-agent,yuecong/dd-agent,tebriel/dd-agent,Shopify/dd-agent,jraede/dd-agent,Mashape/dd-agent,oneandoneis2/dd-agent,eeroniemi/dd-agent,amalakar/dd-agent,benmccann/dd-agent,amalakar/dd-agent,takus/dd-agent,jshum/dd-agent,Wattpad/dd-agent,remh/dd-agent,GabrielNicolasAvellaneda/dd-agent,oneandoneis2/dd-agent,remh/dd-agent,indeedops/dd-agent,oneandoneis2/dd-agent,c960657/dd-agent,zendesk/dd-agent,amalakar/dd-agent,remh/dd-agent,truthbk/dd-agent,oneandoneis2/dd-agent,manolama/dd-agent,huhongbo/dd-agent,mderomph-coolblue/dd-agent,Mashape/dd-agent,Mashape/dd-agent,mderomph-coolblue/dd-agent,c960657/dd-agent,pfmooney/dd-agent,amalakar/dd-agent,indeedops/dd-agent,eeroniemi/dd-agent,guruxu/dd-agent,relateiq/dd-agent,JohnLZeller/dd-agent,polynomial/dd-agent,pfmooney/dd-agent,jamesandariese/dd-agent,manolama/dd-agent,truthbk/dd-agent,brettlangdon/dd-agent,jvassev/dd-agent,huhongbo/dd-agent,packetloop/dd-agent,AniruddhaSAtre/dd-agent,PagerDuty/dd-agent,urosgruber/dd-agent,lookout/dd-agent,pmav99/praktoras,jraede/dd-agent,jshum/dd-agent,Shopify/dd-agent,jvassev/dd-agent,polynomial/dd-agent,manolama/dd-agent,lookout/dd-agent,pfmooney/dd-agent,jyogi/purvar-agent,takus/dd-agent,huhongbo/dd-agent,GabrielNicolasAvellaneda/dd-agent,jamesandariese/dd-agent,guruxu/dd-agent,JohnLZeller/dd-agent,jamesandariese/dd-agent,cberry777/dd-agent,jyogi/purvar-agent,gphat/dd-agent,manolama/dd-agent,darron/dd-agent,AniruddhaSAtre/dd-agent,joelvanvelden/dd-agent,indeedops/dd-agent,Wattpad/dd-agent,a20012251/dd-agent,yuecong/dd-agent,amalakar/dd-agent,cberry777/dd-agent,lookout/dd-agent,citrusleaf/dd-agent,Mashape/dd-agent,GabrielNicolasAvellaneda/dd-agent,pmav99/praktoras,remh/dd-agent,brettlangdon/dd-agent,jamesandariese/dd-agent,tebriel/dd-agent,jshum/dd-agent,JohnLZeller/dd-agent,a20012251/dd-agent,benmccann/dd-agent,darron/dd-agent,urosgruber/dd-agent,guruxu/dd-agent,jyogi/purvar-agent,truthbk/dd-agent,joelvanvelden/dd-agent,Wattpad/dd-agent,AniruddhaSAtre/dd-agent,jyogi/purvar-agent,a20012251/dd-agent,eeroniemi/dd-agent,zendesk/dd-agent,guruxu/dd-agent,gphat/dd-agent,takus/dd-agent,packetloop/dd-agent,jvassev/dd-agent,darron/dd-agent,zendesk/dd-agent,GabrielNicolasAvellaneda/dd-agent,c960657/dd-agent,ess/dd-agent,relateiq/dd-agent,polynomial/dd-agent,darron/dd-agent,citrusleaf/dd-agent,benmccann/dd-agent,remh/dd-agent,AniruddhaSAtre/dd-agent,brettlangdon/dd-agent,oneandoneis2/dd-agent,polynomial/dd-agent
import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: - agentConfig = { + agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) + + # Service checks + service_checks = self.check.get_service_checks() + service_checks_count = len(service_checks) + self.assertTrue(type(service_checks) == type([])) + self.assertTrue(service_checks_count > 0) + self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks) + # Assert that all service checks have the proper tags: host and port + self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks) + self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks) + time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) - + + if __name__ == '__main__': unittest.main()
Add test for Mysql sc
## Code Before: import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main() ## Instruction: Add test for Mysql sc ## Code After: import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) # Service checks service_checks = self.check.get_service_checks() service_checks_count = len(service_checks) self.assertTrue(type(service_checks) == type([])) self.assertTrue(service_checks_count > 0) self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks) # Assert that all service checks have the proper tags: host and port self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks) self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks) time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) if __name__ == '__main__': unittest.main()
import unittest from tests.common import load_check import time class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest self.skip = False try: import pymysql except ImportError: self.skip = True def testChecks(self): if not self.skip: - agentConfig = { ? - + agentConfig = { 'version': '0.1', 'api_key': 'toto' } conf = {'init_config': {}, 'instances': [{ 'server': 'localhost', 'user': 'dog', 'pass': 'dog', 'options': {'replication': True}, }]} # Initialize the check from checks.d self.check = load_check('mysql', conf, agentConfig) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 8, metrics) + + # Service checks + service_checks = self.check.get_service_checks() + service_checks_count = len(service_checks) + self.assertTrue(type(service_checks) == type([])) + self.assertTrue(service_checks_count > 0) + self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks) + # Assert that all service checks have the proper tags: host and port + self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks) + self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks) + time.sleep(1) self.check.run() metrics = self.check.get_metrics() self.assertTrue(len(metrics) >= 16, metrics) - + + if __name__ == '__main__': unittest.main()
38775f06c2285f3d12b9f4a0bc70bded29dce274
hbmqtt/utils.py
hbmqtt/utils.py
def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False
def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False def format_client_message(session=None, address=None, port=None, id=None): if session: return "(client @=%s:%d id=%s)" % (session.remote_address, session.remote_port, session.client_id) else: return "(client @=%s:%d id=%s)" % (address, port, id)
Add method for formatting client info (address, port, id)
Add method for formatting client info (address, port, id)
Python
mit
beerfactory/hbmqtt
def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False + + + def format_client_message(session=None, address=None, port=None, id=None): + if session: + return "(client @=%s:%d id=%s)" % (session.remote_address, session.remote_port, session.client_id) + else: + return "(client @=%s:%d id=%s)" % (address, port, id) +
Add method for formatting client info (address, port, id)
## Code Before: def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False ## Instruction: Add method for formatting client info (address, port, id) ## Code After: def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False def format_client_message(session=None, address=None, port=None, id=None): if session: return "(client @=%s:%d id=%s)" % (session.remote_address, session.remote_port, session.client_id) else: return "(client @=%s:%d id=%s)" % (address, port, id)
def not_in_dict_or_none(dict, key): """ Check if a key exists in a map and if it's not None :param dict: map to look for key :param key: key to find :return: true if key is in dict and not None """ if key not in dict or dict[key] is None: return True else: return False + + + def format_client_message(session=None, address=None, port=None, id=None): + if session: + return "(client @=%s:%d id=%s)" % (session.remote_address, session.remote_port, session.client_id) + else: + return "(client @=%s:%d id=%s)" % (address, port, id)
e5db0a11634dc442f77f5550efd5cbf687ea6526
lionschool/core/admin.py
lionschool/core/admin.py
from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden for model in {Grade, Group, Pupil, Teacher, Warden}: admin.site.register(model)
from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden, Course for model in Grade, Group, Pupil, Teacher, Warden, Course: admin.site.register(model)
Add Course field to Admin
Add Course field to Admin Oops! forgot..
Python
bsd-3-clause
Leo2807/lioncore
from django.contrib import admin - from .models import Grade, Group, Pupil, Teacher, Warden + from .models import Grade, Group, Pupil, Teacher, Warden, Course - for model in {Grade, Group, Pupil, Teacher, Warden}: + for model in Grade, Group, Pupil, Teacher, Warden, Course: admin.site.register(model)
Add Course field to Admin
## Code Before: from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden for model in {Grade, Group, Pupil, Teacher, Warden}: admin.site.register(model) ## Instruction: Add Course field to Admin ## Code After: from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden, Course for model in Grade, Group, Pupil, Teacher, Warden, Course: admin.site.register(model)
from django.contrib import admin - from .models import Grade, Group, Pupil, Teacher, Warden + from .models import Grade, Group, Pupil, Teacher, Warden, Course ? ++++++++ - for model in {Grade, Group, Pupil, Teacher, Warden}: ? - - ^ + for model in Grade, Group, Pupil, Teacher, Warden, Course: ? ^^^^^^^^ admin.site.register(model)
5ca96beb26dd2ab5285a57f5cade6f01160df368
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence and Warshall's algorithm. Pseudocode and Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:28 AM" # related=[("Some article", "its/url")]
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")]
Update description and timestamp for dynamic programming part 1
Update description and timestamp for dynamic programming part 1
Python
mit
joequery/joequery.me,joequery/joequery.me,joequery/joequery.me,joequery/joequery.me
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. - Examples in these notes include the Fibonacci sequence and Warshall's + Examples in these notes include the Fibonacci sequence, the Binomial Formula, - algorithm. Pseudocode and Python implementations of the algorithms are + and Warshall's algorithm. Python implementations of the algorithms are provided. """ - time="2012-12-10 Mon 02:28 AM" + time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")]
Update description and timestamp for dynamic programming part 1
## Code Before: title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence and Warshall's algorithm. Pseudocode and Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:28 AM" # related=[("Some article", "its/url")] ## Instruction: Update description and timestamp for dynamic programming part 1 ## Code After: title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")]
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. - Examples in these notes include the Fibonacci sequence and Warshall's ? ^ ^^^^^^^ ^^ + Examples in these notes include the Fibonacci sequence, the Binomial Formula, ? + ^^^^^^ ^^^ ++++++ ^^ - algorithm. Pseudocode and Python implementations of the algorithms are ? --------------- + and Warshall's algorithm. Python implementations of the algorithms are ? +++++++++++++++ provided. """ - time="2012-12-10 Mon 02:28 AM" ? ^ + time="2012-12-10 Mon 02:48 AM" ? ^ # related=[("Some article", "its/url")]
fece0019a54534b56960a30785bb70edb5d205bf
example_base/forms.py
example_base/forms.py
from base.form_utils import RequiredFieldForm from .models import Document from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()}
from django import forms from base.form_utils import RequiredFieldForm, FileDropInput from .models import Document class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) # Not required RequiredFieldForm uses FileDropInput for FileField # widgets = {'file': FileDropInput()} # this is an example of how to use in a basic ModelForm class BasicDocumentModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()} # this is an example of how to use in a basic Form class NonModelForm(forms.Form): file = forms.FileField(widget=FileDropInput) description = forms.CharField(max_length=200) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} )
Add examples of ways to use FileDropInput
Add examples of ways to use FileDropInput
Python
apache-2.0
pkimber/base,pkimber/base,pkimber/base,pkimber/base
+ from django import forms - from base.form_utils import RequiredFieldForm + from base.form_utils import RequiredFieldForm, FileDropInput - from .models import Document - from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) + + # Not required RequiredFieldForm uses FileDropInput for FileField + # widgets = {'file': FileDropInput()} + + + # this is an example of how to use in a basic ModelForm + class BasicDocumentModelForm(forms.ModelForm): + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for name in ('file', 'description'): + self.fields[name].widget.attrs.update( + {'class': 'pure-input-2-3'} + ) + + class Meta: + model = Document + fields = ( + 'file', + 'description', + ) widgets = {'file': FileDropInput()} + + # this is an example of how to use in a basic Form + class NonModelForm(forms.Form): + + file = forms.FileField(widget=FileDropInput) + description = forms.CharField(max_length=200) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for name in ('file', 'description'): + self.fields[name].widget.attrs.update( + {'class': 'pure-input-2-3'} + ) +
Add examples of ways to use FileDropInput
## Code Before: from base.form_utils import RequiredFieldForm from .models import Document from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()} ## Instruction: Add examples of ways to use FileDropInput ## Code After: from django import forms from base.form_utils import RequiredFieldForm, FileDropInput from .models import Document class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) # Not required RequiredFieldForm uses FileDropInput for FileField # widgets = {'file': FileDropInput()} # this is an example of how to use in a basic ModelForm class BasicDocumentModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()} # this is an example of how to use in a basic Form class NonModelForm(forms.Form): file = forms.FileField(widget=FileDropInput) description = forms.CharField(max_length=200) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} )
+ from django import forms - from base.form_utils import RequiredFieldForm + from base.form_utils import RequiredFieldForm, FileDropInput ? +++++++++++++++ - from .models import Document - from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) + + # Not required RequiredFieldForm uses FileDropInput for FileField + # widgets = {'file': FileDropInput()} + + + # this is an example of how to use in a basic ModelForm + class BasicDocumentModelForm(forms.ModelForm): + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for name in ('file', 'description'): + self.fields[name].widget.attrs.update( + {'class': 'pure-input-2-3'} + ) + + class Meta: + model = Document + fields = ( + 'file', + 'description', + ) widgets = {'file': FileDropInput()} + + + # this is an example of how to use in a basic Form + class NonModelForm(forms.Form): + + file = forms.FileField(widget=FileDropInput) + description = forms.CharField(max_length=200) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for name in ('file', 'description'): + self.fields[name].widget.attrs.update( + {'class': 'pure-input-2-3'} + )
2b07fdcefdc915e69580016d9c0a08ab8e478ce7
chatterbot/adapters/logic/closest_match.py
chatterbot/adapters/logic/closest_match.py
from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement ''' closest_match, confidence = process.extractOne( input_statement.text, text_of_all_statements ) ''' # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
Remove commented out method call.
Remove commented out method call.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,Gustavo6046/ChatterBot,vkosuri/ChatterBot,gunthercox/ChatterBot,Reinaesaya/OUIRL-ChatBot,davizucon/ChatterBot
from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement - ''' - closest_match, confidence = process.extractOne( - input_statement.text, - text_of_all_statements - ) - ''' - # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
Remove commented out method call.
## Code Before: from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement ''' closest_match, confidence = process.extractOne( input_statement.text, text_of_all_statements ) ''' # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match ## Instruction: Remove commented out method call. ## Code After: from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
from .base_match import BaseMatchAdapter from fuzzywuzzy import fuzz class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text, statement.text) if ratio > confidence: confidence = ratio closest_match = statement - ''' - closest_match, confidence = process.extractOne( - input_statement.text, - text_of_all_statements - ) - ''' - # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
07b6f05d913337619205d6fd82b472e112e2a2c7
src/demo.py
src/demo.py
"""Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) if __name__ == "__main__": main(sys.argv)
"""Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) hard_puzzle = NonogramPuzzle( # https://commons.wikimedia.org/wiki/File:Paint_by_numbers_Animation.gif [[3], [5], [3,1], [2,1], [3,3,4], [2,2,7], [6,1,1], [4,2,2], [1,1], [3,1], [6], [2,7], [6,3,1], [1,2,2,1,1], [4,1,1,3], [4,2,2], [3,3,1], [3,3], [3], [2,1]], [[2], [1,2], [2,3], [2,3], [3,1,1], [2,1,1], [1,1,1,2,2], [1,1,3,1,3], [2,6,4], [3,3,9,1], [5,3,2], [3,1,2,2], [2,1,7], [3,3,2], [2,4], [2,1,2], [2,2,1], [2,2], [1], [1]]) def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) test_solver(BackwardChainSolver, hard_puzzle) if __name__ == "__main__": main(sys.argv)
Add a hard puzzle not yet correctly solved
Add a hard puzzle not yet correctly solved
Python
apache-2.0
ggould256/nonogram
"""Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) + hard_puzzle = NonogramPuzzle( + # https://commons.wikimedia.org/wiki/File:Paint_by_numbers_Animation.gif + [[3], [5], [3,1], [2,1], [3,3,4], [2,2,7], [6,1,1], [4,2,2], [1,1], [3,1], + [6], [2,7], [6,3,1], [1,2,2,1,1], [4,1,1,3], [4,2,2], [3,3,1], [3,3], + [3], [2,1]], + [[2], [1,2], [2,3], [2,3], [3,1,1], [2,1,1], [1,1,1,2,2], [1,1,3,1,3], + [2,6,4], [3,3,9,1], [5,3,2], [3,1,2,2], [2,1,7], [3,3,2], [2,4], [2,1,2], + [2,2,1], [2,2], [1], [1]]) + def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) + test_solver(BackwardChainSolver, hard_puzzle) if __name__ == "__main__": main(sys.argv)
Add a hard puzzle not yet correctly solved
## Code Before: """Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) if __name__ == "__main__": main(sys.argv) ## Instruction: Add a hard puzzle not yet correctly solved ## Code After: """Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) hard_puzzle = NonogramPuzzle( # https://commons.wikimedia.org/wiki/File:Paint_by_numbers_Animation.gif [[3], [5], [3,1], [2,1], [3,3,4], [2,2,7], [6,1,1], [4,2,2], [1,1], [3,1], [6], [2,7], [6,3,1], [1,2,2,1,1], [4,1,1,3], [4,2,2], [3,3,1], [3,3], [3], [2,1]], [[2], [1,2], [2,3], [2,3], [3,1,1], [2,1,1], [1,1,1,2,2], [1,1,3,1,3], [2,6,4], [3,3,9,1], [5,3,2], [3,1,2,2], [2,1,7], [3,3,2], [2,4], [2,1,2], [2,2,1], [2,2], [1], [1]]) def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) test_solver(BackwardChainSolver, hard_puzzle) if __name__ == "__main__": main(sys.argv)
"""Brief demo of nonogram solving.""" import sys from rules.nonogram import NonogramPuzzle easy_puzzle = NonogramPuzzle([[1], [1, 1]], [[1], [1], [1]]) ambiguous_puzzle = NonogramPuzzle([[1], [1]], [[1], [1]]) + hard_puzzle = NonogramPuzzle( + # https://commons.wikimedia.org/wiki/File:Paint_by_numbers_Animation.gif + [[3], [5], [3,1], [2,1], [3,3,4], [2,2,7], [6,1,1], [4,2,2], [1,1], [3,1], + [6], [2,7], [6,3,1], [1,2,2,1,1], [4,1,1,3], [4,2,2], [3,3,1], [3,3], + [3], [2,1]], + [[2], [1,2], [2,3], [2,3], [3,1,1], [2,1,1], [1,1,1,2,2], [1,1,3,1,3], + [2,6,4], [3,3,9,1], [5,3,2], [3,1,2,2], [2,1,7], [3,3,2], [2,4], [2,1,2], + [2,2,1], [2,2], [1], [1]]) + def main(args): from solver.solver_coroutine import test_solver from solver.brute_force import BruteForceNonogramSolver test_solver(BruteForceNonogramSolver, easy_puzzle) test_solver(BruteForceNonogramSolver, ambiguous_puzzle) from solver.backward_chain_solver import BackwardChainSolver test_solver(BackwardChainSolver, easy_puzzle) test_solver(BackwardChainSolver, ambiguous_puzzle) + test_solver(BackwardChainSolver, hard_puzzle) if __name__ == "__main__": main(sys.argv)
52bca1129cfe21669b5f7faf2e99e148a559bd32
src/utils/build_dependencies.py
src/utils/build_dependencies.py
import glob dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') d = set() for line in open(src, 'r'): words = line.split() if words and words[0].lower() == 'use': name = words[1].strip(',') if name in ['mpi','hdf5','h5lt']: continue if name.startswith('xml_data_'): name = name.replace('xml_data_', 'templates/') d.add(name) if d: d = list(d) d.sort() dependencies[module] = d keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('')
import glob import re dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') deps = set() d = re.findall(r'\n\s*use\s+(\w+)', open(src,'r').read()) for name in d: if name in ['mpi','hdf5','h5lt']: continue if name.startswith('xml_data_'): name = name.replace('xml_data_', 'templates/') deps.add(name) if deps: dependencies[module] = sorted(list(deps)) keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('')
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
Python
mit
mjlong/openmc,wbinventor/openmc,kellyrowland/openmc,lilulu/openmc,liangjg/openmc,mit-crpg/openmc,johnnyliu27/openmc,smharper/openmc,keadyk/openmc_mg_prepush,smharper/openmc,paulromano/openmc,johnnyliu27/openmc,smharper/openmc,liangjg/openmc,mit-crpg/openmc,smharper/openmc,walshjon/openmc,lilulu/openmc,sxds/opemmc,paulromano/openmc,mjlong/openmc,amandalund/openmc,wbinventor/openmc,bhermanmit/openmc,samuelshaner/openmc,johnnyliu27/openmc,johnnyliu27/openmc,shenqicang/openmc,shikhar413/openmc,walshjon/openmc,bhermanmit/cdash,walshjon/openmc,samuelshaner/openmc,lilulu/openmc,shikhar413/openmc,samuelshaner/openmc,amandalund/openmc,amandalund/openmc,wbinventor/openmc,shenqicang/openmc,amandalund/openmc,shikhar413/openmc,shikhar413/openmc,keadyk/openmc_mg_prepush,paulromano/openmc,kellyrowland/openmc,samuelshaner/openmc,liangjg/openmc,mit-crpg/openmc,nhorelik/openmc,walshjon/openmc,mit-crpg/openmc,sxds/opemmc,keadyk/openmc_mg_prepush,nhorelik/openmc,liangjg/openmc,bhermanmit/openmc,paulromano/openmc,wbinventor/openmc
import glob + import re dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') - d = set() + deps = set() + d = re.findall(r'\n\s*use\s+(\w+)', + open(src,'r').read()) + for name in d: - for line in open(src, 'r'): - words = line.split() - if words and words[0].lower() == 'use': - name = words[1].strip(',') - if name in ['mpi','hdf5','h5lt']: + if name in ['mpi','hdf5','h5lt']: - continue + continue - if name.startswith('xml_data_'): + if name.startswith('xml_data_'): - name = name.replace('xml_data_', 'templates/') + name = name.replace('xml_data_', 'templates/') - d.add(name) + deps.add(name) - if d: + if deps: - d = list(d) - d.sort() - dependencies[module] = d + dependencies[module] = sorted(list(deps)) keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('')
Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
## Code Before: import glob dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') d = set() for line in open(src, 'r'): words = line.split() if words and words[0].lower() == 'use': name = words[1].strip(',') if name in ['mpi','hdf5','h5lt']: continue if name.startswith('xml_data_'): name = name.replace('xml_data_', 'templates/') d.add(name) if d: d = list(d) d.sort() dependencies[module] = d keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('') ## Instruction: Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work. ## Code After: import glob import re dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') deps = set() d = re.findall(r'\n\s*use\s+(\w+)', open(src,'r').read()) for name in d: if name in ['mpi','hdf5','h5lt']: continue if name.startswith('xml_data_'): name = name.replace('xml_data_', 'templates/') deps.add(name) if deps: dependencies[module] = sorted(list(deps)) keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('')
import glob + import re dependencies = {} for src in glob.iglob('*.F90'): module = src.strip('.F90') - d = set() + deps = set() ? +++ + d = re.findall(r'\n\s*use\s+(\w+)', + open(src,'r').read()) + for name in d: - for line in open(src, 'r'): - words = line.split() - if words and words[0].lower() == 'use': - name = words[1].strip(',') - if name in ['mpi','hdf5','h5lt']: ? ---- + if name in ['mpi','hdf5','h5lt']: - continue ? ---- + continue - if name.startswith('xml_data_'): ? ---- + if name.startswith('xml_data_'): - name = name.replace('xml_data_', 'templates/') ? ---- + name = name.replace('xml_data_', 'templates/') - d.add(name) ? ---- + deps.add(name) ? +++ - if d: + if deps: ? +++ - d = list(d) - d.sort() - dependencies[module] = d + dependencies[module] = sorted(list(deps)) ? +++++ ++++++++++++ keys = dependencies.keys() keys.sort() for module in keys: for dep in dependencies[module]: print("{0}.o: {1}.o".format(module, dep)) print('')
569c056e016131ec4325185ee9fe814018d5e1fe
server/bands/__init__.py
server/bands/__init__.py
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: del session['bandId'] return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
Fix problem on no-longer existing bands that are still as logged in session available
Fix problem on no-longer existing bands that are still as logged in session available
Python
apache-2.0
dennisausbremen/tunefish,dennisausbremen/tunefish,dennisausbremen/tunefish
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: + del session['bandId'] return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
Fix problem on no-longer existing bands that are still as logged in session available
## Code Before: from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400 ## Instruction: Fix problem on no-longer existing bands that are still as logged in session available ## Code After: from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: del session['bandId'] return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
from flask import session, redirect, url_for, g, jsonify, Response from flask.views import MethodView from server.models import Band class RestrictedBandPage(MethodView): def dispatch_request(self, *args, **kwargs): if not 'bandId' in session: return redirect(url_for('bands.session.index')) else: self.band = Band.query.get(session['bandId']) if not self.band: + del session['bandId'] return redirect(url_for('bands.session.index')) else: g.band = self.band return super(RestrictedBandPage, self).dispatch_request(*args, **kwargs) class AjaxException(Exception): errors = [] def __init__(self, *args): super(Exception, self).__init__() self.errors = args AJAX_SUCCESS = Response(200) class AjaxForm(MethodView): def post(self): if self.form.validate_on_submit(): try: result = self.on_submit() if type(result) is Response: return result else: return jsonify(result) except AjaxException as e: errors = self.form.errors if len(e.errors) > 0: errors['general'] = e.errors return jsonify(errors=errors), 400 else: return jsonify(errors=self.form.errors), 400
0f1a3d06b316590c029e4e6c0e474f716e047033
pokebattle/game_entrypoint.py
pokebattle/game_entrypoint.py
from nameko.web.handlers import http from pokebattle.scores import ScoreService class GameService(object): score_service = RpcProxy('score_service') @http('POST', '/signup') def signup(self): pass @http('POST', '/login') def login(self): pass @http('POST', '/battle') def new_game(self): pass @http('GET', '/leaderboard') def leaderboard(self): pass @http('GET', '/user/<int:id>') def user(self): pass @http('GET', '/user/<int:id>/pokemons') def user_pokemons(self): pass
import json from nameko.web.handlers import http from nameko.rpc import RpcProxy from pokebattle.scores import ScoreService class GameService(object): name = 'game_service' score_rpc = RpcProxy('score_service') @http('POST', '/signup') def signup(self, request): pass @http('POST', '/login') def login(self, request): pass @http('POST', '/battle') def new_game(self, request): pass @http('GET', '/leaderboard') def leaderboard(self, request): return json.dumps(self.score_rpc.leaderboard()) @http('GET', '/user/<int:id>') def user(self, request): pass @http('GET', '/user/<int:id>/pokemons') def user_pokemons(self, request): pass
Add leaderbord rpc call and add request arg to all methods
Add leaderbord rpc call and add request arg to all methods
Python
mit
skooda/poke-battle,radekj/poke-battle
+ import json + from nameko.web.handlers import http + from nameko.rpc import RpcProxy from pokebattle.scores import ScoreService class GameService(object): - + name = 'game_service' - score_service = RpcProxy('score_service') + score_rpc = RpcProxy('score_service') @http('POST', '/signup') - def signup(self): + def signup(self, request): pass @http('POST', '/login') - def login(self): + def login(self, request): pass @http('POST', '/battle') - def new_game(self): + def new_game(self, request): pass @http('GET', '/leaderboard') - def leaderboard(self): + def leaderboard(self, request): - pass + return json.dumps(self.score_rpc.leaderboard()) @http('GET', '/user/<int:id>') - def user(self): + def user(self, request): pass @http('GET', '/user/<int:id>/pokemons') - def user_pokemons(self): + def user_pokemons(self, request): pass
Add leaderbord rpc call and add request arg to all methods
## Code Before: from nameko.web.handlers import http from pokebattle.scores import ScoreService class GameService(object): score_service = RpcProxy('score_service') @http('POST', '/signup') def signup(self): pass @http('POST', '/login') def login(self): pass @http('POST', '/battle') def new_game(self): pass @http('GET', '/leaderboard') def leaderboard(self): pass @http('GET', '/user/<int:id>') def user(self): pass @http('GET', '/user/<int:id>/pokemons') def user_pokemons(self): pass ## Instruction: Add leaderbord rpc call and add request arg to all methods ## Code After: import json from nameko.web.handlers import http from nameko.rpc import RpcProxy from pokebattle.scores import ScoreService class GameService(object): name = 'game_service' score_rpc = RpcProxy('score_service') @http('POST', '/signup') def signup(self, request): pass @http('POST', '/login') def login(self, request): pass @http('POST', '/battle') def new_game(self, request): pass @http('GET', '/leaderboard') def leaderboard(self, request): return json.dumps(self.score_rpc.leaderboard()) @http('GET', '/user/<int:id>') def user(self, request): pass @http('GET', '/user/<int:id>/pokemons') def user_pokemons(self, request): pass
+ import json + from nameko.web.handlers import http + from nameko.rpc import RpcProxy from pokebattle.scores import ScoreService class GameService(object): - + name = 'game_service' - score_service = RpcProxy('score_service') ? -- ^^ - + score_rpc = RpcProxy('score_service') ? ^ @http('POST', '/signup') - def signup(self): + def signup(self, request): ? +++++++++ pass @http('POST', '/login') - def login(self): + def login(self, request): ? +++++++++ pass @http('POST', '/battle') - def new_game(self): + def new_game(self, request): ? +++++++++ pass @http('GET', '/leaderboard') - def leaderboard(self): + def leaderboard(self, request): ? +++++++++ - pass + return json.dumps(self.score_rpc.leaderboard()) @http('GET', '/user/<int:id>') - def user(self): + def user(self, request): ? +++++++++ pass @http('GET', '/user/<int:id>/pokemons') - def user_pokemons(self): + def user_pokemons(self, request): ? +++++++++ pass
05240d24f6184b015422e2e1996fb90d7f6d7654
twstock/cli/best_four_point.py
twstock/cli/best_four_point.py
import twstock def main(argv): print('四大買賣點判斷 Best Four Point') print('------------------------------') if len(argv) > 1: sids = argv[1:] for sid in sids: bfp = twstock.BestFourPoint(twstock.Stock(sid)) bfp = bfp.best_four_point() print('%s: ' % (sid), end='') if bfp: if bfp[0]: print('Buy ', bfp[1]) else: print('Sell ', bfp[1]) else: print("Don't touch")
import twstock def run(argv): print('四大買賣點判斷 Best Four Point') print('------------------------------') for sid in argv: bfp = twstock.BestFourPoint(twstock.Stock(sid)) bfp = bfp.best_four_point() print('%s: ' % (sid), end='') if bfp: if bfp[0]: print('Buy ', bfp[1]) else: print('Sell ', bfp[1]) else: print("Don't touch")
Fix best four point cli
Fix best four point cli
Python
mit
mlouielu/twstock,TCCinTaiwan/twstock
import twstock - def main(argv): + def run(argv): print('四大買賣點判斷 Best Four Point') print('------------------------------') + for sid in argv: - if len(argv) > 1: - sids = argv[1:] - for sid in sids: - bfp = twstock.BestFourPoint(twstock.Stock(sid)) + bfp = twstock.BestFourPoint(twstock.Stock(sid)) - bfp = bfp.best_four_point() + bfp = bfp.best_four_point() - print('%s: ' % (sid), end='') + print('%s: ' % (sid), end='') + if bfp: - if bfp: + if bfp[0]: - if bfp[0]: - print('Buy ', bfp[1]) + print('Buy ', bfp[1]) - else: - print('Sell ', bfp[1]) else: + print('Sell ', bfp[1]) + else: - print("Don't touch") + print("Don't touch")
Fix best four point cli
## Code Before: import twstock def main(argv): print('四大買賣點判斷 Best Four Point') print('------------------------------') if len(argv) > 1: sids = argv[1:] for sid in sids: bfp = twstock.BestFourPoint(twstock.Stock(sid)) bfp = bfp.best_four_point() print('%s: ' % (sid), end='') if bfp: if bfp[0]: print('Buy ', bfp[1]) else: print('Sell ', bfp[1]) else: print("Don't touch") ## Instruction: Fix best four point cli ## Code After: import twstock def run(argv): print('四大買賣點判斷 Best Four Point') print('------------------------------') for sid in argv: bfp = twstock.BestFourPoint(twstock.Stock(sid)) bfp = bfp.best_four_point() print('%s: ' % (sid), end='') if bfp: if bfp[0]: print('Buy ', bfp[1]) else: print('Sell ', bfp[1]) else: print("Don't touch")
import twstock - def main(argv): ? ^^^ + def run(argv): ? ^^ print('四大買賣點判斷 Best Four Point') print('------------------------------') + for sid in argv: - if len(argv) > 1: - sids = argv[1:] - for sid in sids: - bfp = twstock.BestFourPoint(twstock.Stock(sid)) ? ---- + bfp = twstock.BestFourPoint(twstock.Stock(sid)) - bfp = bfp.best_four_point() ? ---- + bfp = bfp.best_four_point() - print('%s: ' % (sid), end='') ? ---- + print('%s: ' % (sid), end='') + if bfp: - if bfp: + if bfp[0]: ? +++ - if bfp[0]: - print('Buy ', bfp[1]) ? ---- + print('Buy ', bfp[1]) - else: - print('Sell ', bfp[1]) else: + print('Sell ', bfp[1]) + else: - print("Don't touch") ? ---- + print("Don't touch")
e4452ff7e8c27e2e8315c2edb8627a2e92ca86e3
panoptes_cli/scripts/panoptes.py
panoptes_cli/scripts/panoptes.py
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
Use os.path.expanduser to find config directory
Use os.path.expanduser to find config directory Works on Windows and Unix.
Python
apache-2.0
zooniverse/panoptes-cli
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): - ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') + ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
Use os.path.expanduser to find config directory
## Code Before: import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import * ## Instruction: Use os.path.expanduser to find config directory ## Code After: import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): - ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') + ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
ee00138478726ffb60b0a9d3541bb010b95903d8
cea/interfaces/dashboard/api/__init__.py
cea/interfaces/dashboard/api/__init__.py
from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary')
from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary') @api.errorhandler def default_error_handler(error): """Default error handler""" import traceback trace = traceback.format_exc() return {'message': error.message, 'trace': trace}, 500
Add general error handler for unhandled exceptions in api
Add general error handler for unhandled exceptions in api
Python
mit
architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst
from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary') + + @api.errorhandler + def default_error_handler(error): + """Default error handler""" + import traceback + trace = traceback.format_exc() + return {'message': error.message, 'trace': trace}, 500 +
Add general error handler for unhandled exceptions in api
## Code Before: from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary') ## Instruction: Add general error handler for unhandled exceptions in api ## Code After: from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary') @api.errorhandler def default_error_handler(error): """Default error handler""" import traceback trace = traceback.format_exc() return {'message': error.message, 'trace': trace}, 500
from flask import Blueprint from flask_restplus import Api from .tools import api as tools from .project import api as project from .inputs import api as inputs from .dashboard import api as dashboard from .glossary import api as glossary blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint) api.add_namespace(tools, path='/tools') api.add_namespace(project, path='/project') api.add_namespace(inputs, path='/inputs') api.add_namespace(dashboard, path='/dashboards') api.add_namespace(glossary, path='/glossary') + + + @api.errorhandler + def default_error_handler(error): + """Default error handler""" + import traceback + trace = traceback.format_exc() + return {'message': error.message, 'trace': trace}, 500
ab72360da83e3b8d95030394f35a442943f53233
domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py
domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py
from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped from control import lqr import numpy as np class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) A = np.array([[0., 1, 0], [0,0,1], [0,0,0]]) B = np.array([[0.],[0],[1]]) Q = np.diag([1.,1,1]) R = np.diag([1.]) K, S, E = lqr(A,B,Q,R) self.K = K def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin()
from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin()
Remove some unused code that unnecessarily introduced depends
Remove some unused code that unnecessarily introduced depends This should be regarded as an update to 9aa5b02e12a2287642a285541c43790a10d6444f that removes unnecessary dependencies for the lqr.py example. In the example provided by 9aa5b02e12a2287642a285541c43790a10d6444f Python code was introduced that led to dependencies on NumPy and the Python Control System Library (control), yet the state-feedback gains were hard-coded. We will re-introduce these dependencies in the next changeset, but having this checkpoint without them seems useful.
Python
bsd-3-clause
fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark
from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped - from control import lqr - import numpy as np - class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) - A = np.array([[0., 1, 0], [0,0,1], [0,0,0]]) - B = np.array([[0.],[0],[1]]) - Q = np.diag([1.,1,1]) - R = np.diag([1.]) - K, S, E = lqr(A,B,Q,R) - self.K = K def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin()
Remove some unused code that unnecessarily introduced depends
## Code Before: from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped from control import lqr import numpy as np class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) A = np.array([[0., 1, 0], [0,0,1], [0,0,0]]) B = np.array([[0.],[0],[1]]) Q = np.diag([1.,1,1]) R = np.diag([1.]) K, S, E = lqr(A,B,Q,R) self.K = K def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin() ## Instruction: Remove some unused code that unnecessarily introduced depends ## Code After: from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin()
from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped - from control import lqr - import numpy as np - class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state) self.intopic = rospy.Publisher(intopic, VectorStamped, queue_size=1) - A = np.array([[0., 1, 0], [0,0,1], [0,0,0]]) - B = np.array([[0.],[0],[1]]) - Q = np.diag([1.,1,1]) - R = np.diag([1.]) - K, S, E = lqr(A,B,Q,R) - self.K = K def read_state(self, vs): self.intopic.publish(VectorStamped(point=[-(vs.point[0] + 2.4142*vs.point[1] + 2.4142*vs.point[2])])) if __name__ == "__main__": rospy.init_node("lqr", anonymous=True) lqrc = LQRController("input", "output") rospy.spin()
22a0968d92ef81e021aeae5ab4fd724cc64a3f8c
saleor/site/utils.py
saleor/site/utils.py
from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id)
from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id) def get_setting_value(request, key): site_settings = get_site_settings(request) return getattr(site_settings, key, None)
Define function for getting setting value by key
Define function for getting setting value by key
Python
bsd-3-clause
KenMutemi/saleor,maferelo/saleor,mociepka/saleor,HyperManTT/ECommerceSaleor,maferelo/saleor,jreigel/saleor,KenMutemi/saleor,itbabu/saleor,UITools/saleor,maferelo/saleor,itbabu/saleor,tfroehlich82/saleor,UITools/saleor,jreigel/saleor,car3oon/saleor,tfroehlich82/saleor,tfroehlich82/saleor,jreigel/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,KenMutemi/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,car3oon/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,UITools/saleor
from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id) + + def get_setting_value(request, key): + site_settings = get_site_settings(request) + return getattr(site_settings, key, None) +
Define function for getting setting value by key
## Code Before: from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id) ## Instruction: Define function for getting setting value by key ## Code After: from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id) def get_setting_value(request, key): site_settings = get_site_settings(request) return getattr(site_settings, key, None)
from django.conf import settings from .models import SiteSetting def get_site_settings(request): if not hasattr(request, 'site_settings'): site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None) request.site_settings = get_site_settings_uncached(site_settings_id) return request.site_settings def get_site_settings_uncached(site_id=None): return SiteSetting.objects.get(pk=site_id) + + + def get_setting_value(request, key): + site_settings = get_site_settings(request) + return getattr(site_settings, key, None)
f40fca40d5e09d7ae64acab1258f58cea6810662
setup.py
setup.py
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, version='0.8', author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
Add a version number for scattering.
Add a version number for scattering.
Python
bsd-2-clause
dopplershift/Scattering
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, + version='0.8', author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
Add a version number for scattering.
## Code Before: from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict()) ## Instruction: Add a version number for scattering. ## Code After: from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, version='0.8', author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info from os.path import join flags = ['-W', '-Wall', '-march=opteron', '-O3'] def configuration(parent_package='', top_path=None): config = Configuration('scattering', parent_package, top_path, + version='0.8', author = 'Ryan May', author_email = '[email protected]', platforms = ['Linux'], description = 'Software for simulating weather radar data.', url = 'http://weather.ou.edu/~rmay/research.html') lapack = get_info('lapack_opt') sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f'] config.add_extension('_tmatrix', [join('src', f) for f in sources], extra_compile_args=flags, **lapack) return config setup(**configuration(top_path='').todict())
17266889388c6ae45ac5235a8e22900bf169eba3
typhon/__init__.py
typhon/__init__.py
from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots from . import spareice from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
Revert "Import spareice per default."
Revert "Import spareice per default." This reverts commit d54042d41b981b3479adb140f2534f76c967fa1c.
Python
mit
atmtools/typhon,atmtools/typhon
from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots - from . import spareice from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
Revert "Import spareice per default."
## Code Before: from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots from . import spareice from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) ## Instruction: Revert "Import spareice per default." ## Code After: from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import atmosphere from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import oem from . import physics from . import plots - from . import spareice from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
5657fb5cb8d5abbc8f6ab8cf59208a97e8104f34
utils/graph.py
utils/graph.py
from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: if output == 'stdout': plt.savefig(sys.stdout, format='png') else: plt.savefig(output) else: plt.show()
from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: plt.savefig(output) else: plt.show()
Remove unused `--output stdout` option
Remove unused `--output stdout` option
Python
mit
wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation
from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: - if output == 'stdout': - plt.savefig(sys.stdout, format='png') - else: - plt.savefig(output) + plt.savefig(output) else: plt.show()
Remove unused `--output stdout` option
## Code Before: from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: if output == 'stdout': plt.savefig(sys.stdout, format='png') else: plt.savefig(output) else: plt.show() ## Instruction: Remove unused `--output stdout` option ## Code After: from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: plt.savefig(output) else: plt.show()
from utils import config OFFSET = 2 # offset = max_x/stepsize * OFFSET def init(output): import matplotlib config.mpl(matplotlib, bool(output)) from matplotlib import pyplot globals()['plt'] = pyplot def line_plot(xs, ys, color='red'): plt.plot( xs, ys, color=color, linewidth=2.0 ) def legend(*args): plt.legend(args, loc='best') def scatter_plot(x, y, color='blue'): plt.scatter(x, y, color=color) def scale_x_plot(max_x, stepsize): offset = max_x/stepsize * OFFSET plt.axis(xmin=-offset, xmax=max_x+offset) def scale_y_plot(max_y, stepsize): offset = max_y/stepsize * OFFSET plt.axis(ymin=-offset, ymax=max_y+offset) def prepare_plot(xlabel, ylabel, title): plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid(True) def display_plot(output): if output: - if output == 'stdout': - plt.savefig(sys.stdout, format='png') - else: - plt.savefig(output) ? ---- + plt.savefig(output) else: plt.show()
458fd49fdf73f5cc338c58b1e741fde42f2f7251
exampleapp/models.py
exampleapp/models.py
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors.resize import Fit class Photo(ImageModel): thumbnail = ImageSpec([Fit(50, 50)]) full = ImageSpec([Fit(400, 200)]) caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): thumbnail = ImageSpec([Fit(70, 40)]) class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10)
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors import ResizeToFit class Photo(ImageModel): thumbnail = ImageSpec([ResizeToFit(50, 50)]) full = ImageSpec([ResizeToFit(400, 200)]) caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): thumbnail = ImageSpec([ResizeToFit(70, 40)]) class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10)
Use (not so) new processor class names
Use (not so) new processor class names
Python
mit
hzdg/django-galleries,hzdg/django-galleries,hzdg/django-galleries
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec - from imagekit.processors.resize import Fit + from imagekit.processors import ResizeToFit class Photo(ImageModel): - thumbnail = ImageSpec([Fit(50, 50)]) + thumbnail = ImageSpec([ResizeToFit(50, 50)]) - full = ImageSpec([Fit(400, 200)]) + full = ImageSpec([ResizeToFit(400, 200)]) caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): - thumbnail = ImageSpec([Fit(70, 40)]) + thumbnail = ImageSpec([ResizeToFit(70, 40)]) class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10)
Use (not so) new processor class names
## Code Before: from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors.resize import Fit class Photo(ImageModel): thumbnail = ImageSpec([Fit(50, 50)]) full = ImageSpec([Fit(400, 200)]) caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): thumbnail = ImageSpec([Fit(70, 40)]) class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10) ## Instruction: Use (not so) new processor class names ## Code After: from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors import ResizeToFit class Photo(ImageModel): thumbnail = ImageSpec([ResizeToFit(50, 50)]) full = ImageSpec([ResizeToFit(400, 200)]) caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): thumbnail = ImageSpec([ResizeToFit(70, 40)]) class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10)
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec - from imagekit.processors.resize import Fit ? ------- + from imagekit.processors import ResizeToFit ? ++++++++ class Photo(ImageModel): - thumbnail = ImageSpec([Fit(50, 50)]) + thumbnail = ImageSpec([ResizeToFit(50, 50)]) ? ++++++++ - full = ImageSpec([Fit(400, 200)]) + full = ImageSpec([ResizeToFit(400, 200)]) ? ++++++++ caption = models.CharField(max_length=100) class PortfolioImage(ImageModel): - thumbnail = ImageSpec([Fit(70, 40)]) + thumbnail = ImageSpec([ResizeToFit(70, 40)]) ? ++++++++ class Video(models.Model): title = models.CharField(max_length=50) video = models.FileField(upload_to='galleries/video/video') thumbnail = models.ImageField(upload_to='galleries/video/thumbnail', blank=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] class PhotoAlbum(Gallery): class GalleryMeta: member_models = [Photo] class Meta: verbose_name = 'Photo Album' class Portfolio(Gallery): class GalleryMeta: member_models = [Video] membership_class = 'PortfolioMembership' class PortfolioMembership(Portfolio.BaseMembership): extra_field = models.CharField(max_length=10)