commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
40c6a07808be26de0534a5b6f47ef28f591a500c
bump again
radiosilence/django-suave,radiosilence/django-suave
setup.py
setup.py
from setuptools import setup, find_packages requires = [] dep_links = [] for dep in open('requirements.txt').read().split("\n"): if dep.startswith('git+'): dep_links.append(dep) else: requires.append(dep) setup( name='django-suave', version="0.5.7", description='Rather nice pages.', long_description=open('README.rst').read(), url='https://github.com/radiosilence/django-suave', author='James Cleveland', author_email='[email protected]', packages=find_packages(), include_package_data=True, license="LICENSE.txt", install_requires=requires, dependency_links=dep_links, )
from setuptools import setup, find_packages requires = [] dep_links = [] for dep in open('requirements.txt').read().split("\n"): if dep.startswith('git+'): dep_links.append(dep) else: requires.append(dep) setup( name='django-suave', version="0.5.6", description='Rather nice pages.', long_description=open('README.rst').read(), url='https://github.com/radiosilence/django-suave', author='James Cleveland', author_email='[email protected]', packages=find_packages(), include_package_data=True, license="LICENSE.txt", install_requires=requires, dependency_links=dep_links, )
mit
Python
71fb2fc819c82e2db4075c6e5e32b2addc99c63a
Add platforms and classifiers
CygnusNetworks/python-gsmsapi
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name='gsmsapi', version='0.10', description='SMS API for (german) SMS providers', author='Torge Szczepanek', author_email='[email protected]', maintainer='Torge Szczepanek', maintainer_email='[email protected]', license='MIT', packages=['gsmsapi'], url = 'https://github.com/CygnusNetworks/python-gsmsapi', download_url = 'https://github.com/CygnusNetworks/python-gsmsapi/tarball/v0.10', keywords = ["sms", "german", "sipgate", "smstrade", "api"], platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules'] # see: https://pypi.python.org/pypi?%3Aaction=list_classifiers )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name='gsmsapi', version='0.10', description='SMS API for (german) SMS providers', author='Torge Szczepanek', author_email='[email protected]', maintainer='Torge Szczepanek', maintainer_email='[email protected]', license='MIT', packages=['gsmsapi'], url = 'https://github.com/CygnusNetworks/python-gsmsapi', download_url = 'https://github.com/CygnusNetworks/python-gsmsapi/tarball/v0.10', keywords = ["sms", "german", "sipgate", "smstrade", "api"], )
mit
Python
8b8383680e73496a73a3a520c3ebc85e2e01ce01
fix version in setup.py
SquirrelMajik/flask_rest4
setup.py
setup.py
#!/usr/bin/env python """ Flask-REST4 ------------- Elegant RESTful API for your Flask apps. """ from setuptools import setup setup( name='flask_rest4', version='0.1.3', url='https://github.com/squirrelmajik/flask_rest4', license='See License', author='majik', author_email='[email protected]', description='Elegant RESTful API for your Flask apps.', long_description=__doc__, py_modules=['flask_rest4'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
#!/usr/bin/env python """ Flask-REST4 ------------- Elegant RESTful API for your Flask apps. """ from setuptools import setup setup( name='flask_rest4', version='0.1.0', url='https://github.com/squirrelmajik/flask_rest4', license='See License', author='majik', author_email='[email protected]', description='Elegant RESTful API for your Flask apps.', long_description=__doc__, py_modules=['flask_rest4'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
mit
Python
656d24c38c69891d8731ccf32852b66e32120eb7
Bump dependency
globality-corp/microcosm-pubsub,globality-corp/microcosm-pubsub
setup.py
setup.py
#!/usr/bin/env python from setuptools import find_packages, setup project = "microcosm_pubsub" version = "0.26.1" setup( name=project, version=version, description="PubSub with SNS/SQS", author="Globality Engineering", author_email="[email protected]", url="https://github.com/globality-corp/microcosm-pubsub", packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), include_package_data=True, zip_safe=False, install_requires=[ "boto3>=1.3.0", "marshmallow>=2.12.1", "microcosm>=0.17.2", "microcosm-daemon>=0.10.0", "microcosm-logging>=0.12.0", ], setup_requires=[ "nose>=1.3.6", ], dependency_links=[ ], entry_points={ "microcosm.factories": [ "sqs_message_context = microcosm_pubsub.context:configure_sqs_message_context", "pubsub_message_schema_registry = microcosm_pubsub.registry:configure_schema_registry", "sqs_consumer = microcosm_pubsub.consumer:configure_sqs_consumer", "sqs_envelope = microcosm_pubsub.envelope:configure_sqs_envelope", "sqs_message_dispatcher = microcosm_pubsub.dispatcher:configure", "sqs_message_handler_registry = microcosm_pubsub.registry:configure_handler_registry", "sns_producer = microcosm_pubsub.producer:configure_sns_producer", "sns_topic_arns = microcosm_pubsub.producer:configure_sns_topic_arns", ] }, tests_require=[ "coverage>=3.7.1", "mock>=1.0.1", "PyHamcrest>=1.8.5", ], )
#!/usr/bin/env python from setuptools import find_packages, setup project = "microcosm_pubsub" version = "0.26.1" setup( name=project, version=version, description="PubSub with SNS/SQS", author="Globality Engineering", author_email="[email protected]", url="https://github.com/globality-corp/microcosm-pubsub", packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), include_package_data=True, zip_safe=False, install_requires=[ "boto3>=1.3.0", "marshmallow>=2.12.1", "microcosm>=0.17.1", "microcosm-daemon>=0.10.0", "microcosm-logging>=0.12.0", ], setup_requires=[ "nose>=1.3.6", ], dependency_links=[ ], entry_points={ "microcosm.factories": [ "sqs_message_context = microcosm_pubsub.context:configure_sqs_message_context", "pubsub_message_schema_registry = microcosm_pubsub.registry:configure_schema_registry", "sqs_consumer = microcosm_pubsub.consumer:configure_sqs_consumer", "sqs_envelope = microcosm_pubsub.envelope:configure_sqs_envelope", "sqs_message_dispatcher = microcosm_pubsub.dispatcher:configure", "sqs_message_handler_registry = microcosm_pubsub.registry:configure_handler_registry", "sns_producer = microcosm_pubsub.producer:configure_sns_producer", "sns_topic_arns = microcosm_pubsub.producer:configure_sns_topic_arns", ] }, tests_require=[ "coverage>=3.7.1", "mock>=1.0.1", "PyHamcrest>=1.8.5", ], )
apache-2.0
Python
5e9fa7a1bb8601fb5629d7e7e92a894ab335ccf1
update readme extension
OHSUCompBio/labkey_multisite_query_tool,ohsu-computational-biology/labkey_multisite_query_tool
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.md') as readme_file: readme = readme_file.read() requirements = [ "wheel>=0.23.0", "requests>=2.7.0", "pandas>=0.16.2", "docopt>=0.6.2" ] test_requirements = [ # TODO: put package test requirements here ] setup( name='labkey_multisite_query_tool', version='0.1.0', description="Commandline tool for querying across mutltiple LabKey instances.", long_description=readme, author="Stefan Novak", author_email='[email protected]', url='https://github.com/OHSUCompBio/labkey_multisite_query_tool', packages=[ 'labkey_multisite_query_tool', ], package_dir={'labkey_multisite_query_tool': 'labkey_multisite_query_tool'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='labkey_multisite_query_tool', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], scripts=['bin/labkey'], test_suite='tests', tests_require=test_requirements )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', '') requirements = [ "wheel>=0.23.0", "requests>=2.7.0", "pandas>=0.16.2", "docopt>=0.6.2" ] test_requirements = [ # TODO: put package test requirements here ] setup( name='labkey_multisite_query_tool', version='0.1.0', description="Commandline tool for querying across mutltiple LabKey instances.", long_description=readme + '\n\n' + history, author="Stefan Novak", author_email='[email protected]', url='https://github.com/OHSUCompBio/labkey_multisite_query_tool', packages=[ 'labkey_multisite_query_tool', ], package_dir={'labkey_multisite_query_tool': 'labkey_multisite_query_tool'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='labkey_multisite_query_tool', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], scripts=['bin/labkey'], test_suite='tests', tests_require=test_requirements )
bsd-3-clause
Python
c95234c130435ddd116784ad1829f7bdaa9182c5
ADD 138 solutions with A195615(OEIS)
byung-u/ProjectEuler
100_to_199/euler_138.py
100_to_199/euler_138.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Problem 138 Consider the isosceles triangle with base length, b = 16, and legs, L = 17. By using the Pythagorean theorem it can be seen that the height of the triangle, h = √(172 − 82) = 15, which is one less than the base length. With b = 272 and L = 305, we get h = 273, which is one more than the base length, and this is the second smallest isosceles triangle with the property that h = b ± 1. Find ∑ L for the twelve smallest isosceles triangles for which h = b ± 1 and b, L are positive integers. ''' from decimal import Decimal from math import modf # Pythagorean approximations # http://oeis.org/A195615 (FORMULA) def a(n): if n == 0: return 15 if n == 1: return 273 if n == 2: return 4895 return 17 * a(n - 1) + 17 * a(n - 2) - a(n - 3) def p138(): highs = [a(i) for i in range(0, 12)] result = [] for h in highs: hd = h ** 2 bd = ((h - 1) // 2) ** 2 ret = Decimal(hd + bd).sqrt() ret_float, ret_int = modf(ret) if ret_float == 0.0: # print('[-]', [h], ret, ret_float, ret_int) result.append(int(ret_int)) continue bd = ((h + 1) // 2) ** 2 ret = Decimal(hd + bd).sqrt() ret_float, ret_int = modf(ret) if ret_float == 0.0: # print('[+]', [h], ret, ret_float, ret_int) result.append(int(ret_int)) print(sum(result)) p138()
mit
Python
e7b54968a67bda76546deff546baa49f836cfbaa
Add train_fcn32s
wkentaro/fcn
examples/voc/train_fcn32s.py
examples/voc/train_fcn32s.py
#!/usr/bin/env python import chainer from chainer.training import extensions import fcn def main(): gpu = 0 resume = None # filename # 1. dataset dataset_train = fcn.datasets.PascalVOC2012SegmentationDataset('train') dataset_val = fcn.datasets.PascalVOC2012SegmentationDataset('val') iter_train = chainer.iterators.SerialIterator(dataset_train, batch_size=1) iter_val = chainer.iterators.SerialIterator(dataset_val, batch_size=1) # 2. model vgg_path = fcn.data.download_vgg16_chainermodel vgg = fcn.models.VGG16() chainer.serializers.load_hdf5(vgg_path, vgg) model = fcn.models.FCN32s() fcn.util.copy_chainermodel(vgg, model) if gpu >= 0: chainer.cuda.get_device(gpu).use() model.to_gpu() # 3. optimizer optimizer = chainer.optimizers.MomentumSGD(lr=1e-10, momentum=0.99) optimizer.set(model) # 4. trainer max_epoch = 10000 updater = chainer.training.StandardUpdater( iter_train, optimizer, device=gpu) trainer = chainer.training.Trainer( updater, (max_epoch, 'epoch'), out='result') trainer.extend(extensions.Evaluator(iter_val, model, device=gpu)) trainer.extend(extensions.snapshot(), trigger=(max_epoch, 'epoch')) trainer.extend(extensions.LogReport()) trainer.extend(extensions.PrintReport( ['epoch', 'main/loss', 'validation/main/loss', 'main/accuracy', 'validation/main/accuracy', 'elapsed_time'])) trainer.extend(extensions.ProgressBar()) if resume: chainer.serializers.load_hdf5(resume, trainer) trainer.run() if __name__ == '__main__': main()
mit
Python
b01bd1b21f1b12c9120845ec8a85355b038d6b20
Add a basic Storage engine to talk to the DB
codeforsanjose/inventory-control,worldcomputerxchange/inventory-control
inventory_control/storage.py
inventory_control/storage.py
""" This is the Storage engine. It's how everything should talk to the database layer that sits on the inside of the inventory-control system. """ import MySQLdb class StorageEngine(object): """ Instantiate a DB access object, create all the necessary hooks and then the accessors to a SQL database. """ def __init__(self, config): self.config = config self.db = MySQLdb.connect(host=self.config['host'], user=self.config['user'], passwd=self.config['password'], db=self.config['db']) self.cursor = self.db.cursor()
mit
Python
5397bbe4a87dba82dc9fa57abf09a4346aa63f46
Add 168 python solution (#38)
qiyuangong/leetcode,qiyuangong/leetcode,qiyuangong/leetcode
python/168_Excel_Sheet_Column_Title.py
python/168_Excel_Sheet_Column_Title.py
class Solution: def convertToTitle(self, n: int) -> str: res = "" while n > 0: n -= 1 res = chr(65 + n % 26) + res n //= 26 return res
mit
Python
399daa8ebec14bc4d7ee6c08135e525190e1eb6f
Add short Python script that prints as many dummy divs as needed.
scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback
collections/show-test/print-divs.py
collections/show-test/print-divs.py
# print-divs.py def printDivs(num): for i in range(num): print('<div class="item">Item ' + str(i+1) + '</div>') printDivs(20)
apache-2.0
Python
97883fa22dd8b1207cd533b4dd9e438c83a32a90
Update version.
suriya/mixer,mattcaldwell/mixer,mechaxl/mixer
mixer/__init__.py
mixer/__init__.py
""" Description. """ # Module information # ================== __version__ = '0.2.0' __project__ = 'mixer' __author__ = "horneds <[email protected]>" __license__ = "BSD"
""" Description. """ # Module information # ================== __version__ = '0.1.0' __project__ = 'mixer' __author__ = "horneds <[email protected]>" __license__ = "BSD"
bsd-3-clause
Python
2b80b358edd5bcf914d0c709369dbbcfd748772b
Add in a test for the marketing_link function in mitxmako
polimediaupv/edx-platform,praveen-pal/edx-platform,pdehaye/theming-edx-platform,raccoongang/edx-platform,defance/edx-platform,atsolakid/edx-platform,Softmotions/edx-platform,IONISx/edx-platform,ampax/edx-platform,LICEF/edx-platform,IndonesiaX/edx-platform,abdoosh00/edraak,chudaol/edx-platform,morpheby/levelup-by,raccoongang/edx-platform,eduNEXT/edunext-platform,dkarakats/edx-platform,peterm-itr/edx-platform,Edraak/circleci-edx-platform,caesar2164/edx-platform,Semi-global/edx-platform,cpennington/edx-platform,waheedahmed/edx-platform,xuxiao19910803/edx-platform,pabloborrego93/edx-platform,EduPepperPDTesting/pepper2013-testing,SravanthiSinha/edx-platform,solashirai/edx-platform,rhndg/openedx,DefyVentures/edx-platform,cognitiveclass/edx-platform,pepeportela/edx-platform,cecep-edu/edx-platform,inares/edx-platform,J861449197/edx-platform,ampax/edx-platform-backup,eemirtekin/edx-platform,arifsetiawan/edx-platform,msegado/edx-platform,peterm-itr/edx-platform,antoviaque/edx-platform,mushtaqak/edx-platform,franosincic/edx-platform,PepperPD/edx-pepper-platform,hamzehd/edx-platform,kmoocdev/edx-platform,OmarIthawi/edx-platform,beacloudgenius/edx-platform,deepsrijit1105/edx-platform,itsjeyd/edx-platform,JCBarahona/edX,chauhanhardik/populo,bigdatauniversity/edx-platform,DNFcode/edx-platform,edry/edx-platform,rationalAgent/edx-platform-custom,iivic/BoiseStateX,atsolakid/edx-platform,cselis86/edx-platform,ahmadiga/min_edx,kursitet/edx-platform,SivilTaram/edx-platform,wwj718/ANALYSE,jbassen/edx-platform,jelugbo/tundex,devs1991/test_edx_docmode,yokose-ks/edx-platform,jelugbo/tundex,pelikanchik/edx-platform,cecep-edu/edx-platform,ahmadiga/min_edx,prarthitm/edxplatform,edry/edx-platform,vismartltd/edx-platform,doganov/edx-platform,devs1991/test_edx_docmode,miptliot/edx-platform,EDUlib/edx-platform,shashank971/edx-platform,atsolakid/edx-platform,angelapper/edx-platform,rue89-tech/edx-platform,mjg2203/edx-platform-seas,appliedx/edx-platform,jazztpt/edx-platform,chrisndodge/edx-platform,zadgroup/edx-platform,EduPepperPDTesting/pepper2013-testing,ovnicraft/edx-platform,stvstnfrd/edx-platform,devs1991/test_edx_docmode,etzhou/edx-platform,vasyarv/edx-platform,doganov/edx-platform,mushtaqak/edx-platform,pepeportela/edx-platform,pku9104038/edx-platform,alexthered/kienhoc-platform,ESOedX/edx-platform,kamalx/edx-platform,nttks/jenkins-test,Ayub-Khan/edx-platform,PepperPD/edx-pepper-platform,lduarte1991/edx-platform,cselis86/edx-platform,Edraak/circleci-edx-platform,zubair-arbi/edx-platform,cecep-edu/edx-platform,xinjiguaike/edx-platform,eestay/edx-platform,procangroup/edx-platform,ahmadiga/min_edx,morenopc/edx-platform,SivilTaram/edx-platform,proversity-org/edx-platform,dsajkl/123,jolyonb/edx-platform,hkawasaki/kawasaki-aio8-2,Shrhawk/edx-platform,analyseuc3m/ANALYSE-v1,tiagochiavericosta/edx-platform,dsajkl/123,nikolas/edx-platform,Ayub-Khan/edx-platform,WatanabeYasumasa/edx-platform,adoosii/edx-platform,TeachAtTUM/edx-platform,jbzdak/edx-platform,simbs/edx-platform,vikas1885/test1,dkarakats/edx-platform,inares/edx-platform,cyanna/edx-platform,jazztpt/edx-platform,cpennington/edx-platform,utecuy/edx-platform,amir-qayyum-khan/edx-platform,edx-solutions/edx-platform,zofuthan/edx-platform,nanolearning/edx-platform,edry/edx-platform,stvstnfrd/edx-platform,zubair-arbi/edx-platform,EduPepperPD/pepper2013,louyihua/edx-platform,syjeon/new_edx,AkA84/edx-platform,olexiim/edx-platform,eduNEXT/edunext-platform,openfun/edx-platform,andyzsf/edx,synergeticsedx/deployment-wipro,doismellburning/edx-platform,LICEF/edx-platform,carsongee/edx-platform,dsajkl/reqiop,CourseTalk/edx-platform,fly19890211/edx-platform,UXE/local-edx,xingyepei/edx-platform,cecep-edu/edx-platform,martynovp/edx-platform,CourseTalk/edx-platform,fintech-circle/edx-platform,Edraak/circleci-edx-platform,stvstnfrd/edx-platform,morenopc/edx-platform,shubhdev/edxOnBaadal,chand3040/cloud_that,10clouds/edx-platform,zerobatu/edx-platform,bigdatauniversity/edx-platform,tanmaykm/edx-platform,cognitiveclass/edx-platform,franosincic/edx-platform,jolyonb/edx-platform,ferabra/edx-platform,martynovp/edx-platform,morenopc/edx-platform,LearnEra/LearnEraPlaftform,vikas1885/test1,nanolearning/edx-platform,Lektorium-LLC/edx-platform,cyanna/edx-platform,olexiim/edx-platform,zofuthan/edx-platform,torchingloom/edx-platform,benpatterson/edx-platform,vasyarv/edx-platform,kxliugang/edx-platform,openfun/edx-platform,abdoosh00/edx-rtl-final,arbrandes/edx-platform,TsinghuaX/edx-platform,vismartltd/edx-platform,nttks/jenkins-test,ampax/edx-platform,Lektorium-LLC/edx-platform,proversity-org/edx-platform,olexiim/edx-platform,shubhdev/edx-platform,deepsrijit1105/edx-platform,playm2mboy/edx-platform,jazkarta/edx-platform,jamiefolsom/edx-platform,kmoocdev/edx-platform,shubhdev/edx-platform,alu042/edx-platform,mitocw/edx-platform,sudheerchintala/LearnEraPlatForm,hkawasaki/kawasaki-aio8-1,adoosii/edx-platform,Unow/edx-platform,Ayub-Khan/edx-platform,WatanabeYasumasa/edx-platform,jonathan-beard/edx-platform,dsajkl/reqiop,mjirayu/sit_academy,cognitiveclass/edx-platform,antoviaque/edx-platform,jbassen/edx-platform,fly19890211/edx-platform,beacloudgenius/edx-platform,ahmadio/edx-platform,tiagochiavericosta/edx-platform,alu042/edx-platform,doismellburning/edx-platform,jzoldak/edx-platform,leansoft/edx-platform,ESOedX/edx-platform,zhenzhai/edx-platform,PepperPD/edx-pepper-platform,etzhou/edx-platform,jbzdak/edx-platform,JioEducation/edx-platform,ZLLab-Mooc/edx-platform,OmarIthawi/edx-platform,gsehub/edx-platform,xuxiao19910803/edx,eestay/edx-platform,zerobatu/edx-platform,etzhou/edx-platform,praveen-pal/edx-platform,ampax/edx-platform-backup,bitifirefly/edx-platform,ampax/edx-platform-backup,auferack08/edx-platform,bitifirefly/edx-platform,jswope00/griffinx,shurihell/testasia,dsajkl/123,shubhdev/openedx,jazkarta/edx-platform,Endika/edx-platform,TsinghuaX/edx-platform,chauhanhardik/populo,rismalrv/edx-platform,RPI-OPENEDX/edx-platform,nanolearningllc/edx-platform-cypress-2,nttks/edx-platform,xingyepei/edx-platform,xingyepei/edx-platform,TeachAtTUM/edx-platform,hastexo/edx-platform,itsjeyd/edx-platform,martynovp/edx-platform,kmoocdev2/edx-platform,10clouds/edx-platform,longmen21/edx-platform,antonve/s4-project-mooc,zerobatu/edx-platform,UXE/local-edx,morpheby/levelup-by,xinjiguaike/edx-platform,angelapper/edx-platform,vasyarv/edx-platform,IndonesiaX/edx-platform,MSOpenTech/edx-platform,Kalyzee/edx-platform,xuxiao19910803/edx-platform,edry/edx-platform,chudaol/edx-platform,shashank971/edx-platform,dcosentino/edx-platform,EduPepperPD/pepper2013,rationalAgent/edx-platform-custom,kxliugang/edx-platform,peterm-itr/edx-platform,CourseTalk/edx-platform,xuxiao19910803/edx,jamiefolsom/edx-platform,chauhanhardik/populo,don-github/edx-platform,abdoosh00/edraak,inares/edx-platform,halvertoluke/edx-platform,zadgroup/edx-platform,eemirtekin/edx-platform,dsajkl/reqiop,xuxiao19910803/edx,xingyepei/edx-platform,marcore/edx-platform,mahendra-r/edx-platform,rue89-tech/edx-platform,AkA84/edx-platform,jzoldak/edx-platform,shubhdev/edxOnBaadal,4eek/edx-platform,antonve/s4-project-mooc,Livit/Livit.Learn.EdX,motion2015/edx-platform,polimediaupv/edx-platform,ZLLab-Mooc/edx-platform,torchingloom/edx-platform,hkawasaki/kawasaki-aio8-0,ovnicraft/edx-platform,kalebhartje/schoolboost,shubhdev/openedx,SivilTaram/edx-platform,JioEducation/edx-platform,yokose-ks/edx-platform,simbs/edx-platform,Endika/edx-platform,hkawasaki/kawasaki-aio8-0,carsongee/edx-platform,gymnasium/edx-platform,waheedahmed/edx-platform,Livit/Livit.Learn.EdX,xinjiguaike/edx-platform,Stanford-Online/edx-platform,Softmotions/edx-platform,miptliot/edx-platform,tanmaykm/edx-platform,rhndg/openedx,playm2mboy/edx-platform,CredoReference/edx-platform,longmen21/edx-platform,Stanford-Online/edx-platform,alexthered/kienhoc-platform,eemirtekin/edx-platform,OmarIthawi/edx-platform,EDUlib/edx-platform,dsajkl/123,prarthitm/edxplatform,IITBinterns13/edx-platform-dev,kalebhartje/schoolboost,y12uc231/edx-platform,kalebhartje/schoolboost,AkA84/edx-platform,jamiefolsom/edx-platform,JCBarahona/edX,leansoft/edx-platform,zubair-arbi/edx-platform,B-MOOC/edx-platform,yokose-ks/edx-platform,ZLLab-Mooc/edx-platform,zadgroup/edx-platform,dsajkl/123,jjmiranda/edx-platform,cyanna/edx-platform,arifsetiawan/edx-platform,mitocw/edx-platform,wwj718/ANALYSE,MakeHer/edx-platform,stvstnfrd/edx-platform,nagyistoce/edx-platform,rue89-tech/edx-platform,B-MOOC/edx-platform,Softmotions/edx-platform,TeachAtTUM/edx-platform,jswope00/griffinx,AkA84/edx-platform,mjg2203/edx-platform-seas,morpheby/levelup-by,pomegranited/edx-platform,MakeHer/edx-platform,unicri/edx-platform,4eek/edx-platform,motion2015/edx-platform,don-github/edx-platform,CredoReference/edx-platform,iivic/BoiseStateX,ferabra/edx-platform,Stanford-Online/edx-platform,halvertoluke/edx-platform,procangroup/edx-platform,shurihell/testasia,SravanthiSinha/edx-platform,syjeon/new_edx,dkarakats/edx-platform,cecep-edu/edx-platform,polimediaupv/edx-platform,RPI-OPENEDX/edx-platform,hastexo/edx-platform,appliedx/edx-platform,rhndg/openedx,JCBarahona/edX,fly19890211/edx-platform,Endika/edx-platform,motion2015/edx-platform,apigee/edx-platform,hmcmooc/muddx-platform,kmoocdev/edx-platform,amir-qayyum-khan/edx-platform,SravanthiSinha/edx-platform,TsinghuaX/edx-platform,torchingloom/edx-platform,IITBinterns13/edx-platform-dev,eemirtekin/edx-platform,Edraak/edx-platform,nanolearningllc/edx-platform-cypress,UOMx/edx-platform,doismellburning/edx-platform,mahendra-r/edx-platform,BehavioralInsightsTeam/edx-platform,DNFcode/edx-platform,halvertoluke/edx-platform,valtech-mooc/edx-platform,jbzdak/edx-platform,nttks/jenkins-test,jruiperezv/ANALYSE,EduPepperPDTesting/pepper2013-testing,praveen-pal/edx-platform,ferabra/edx-platform,sameetb-cuelogic/edx-platform-test,IONISx/edx-platform,MSOpenTech/edx-platform,pomegranited/edx-platform,philanthropy-u/edx-platform,procangroup/edx-platform,longmen21/edx-platform,beni55/edx-platform,UOMx/edx-platform,kamalx/edx-platform,Shrhawk/edx-platform,pdehaye/theming-edx-platform,bdero/edx-platform,caesar2164/edx-platform,shashank971/edx-platform,devs1991/test_edx_docmode,pelikanchik/edx-platform,hamzehd/edx-platform,AkA84/edx-platform,jruiperezv/ANALYSE,msegado/edx-platform,nttks/jenkins-test,andyzsf/edx,cognitiveclass/edx-platform,appliedx/edx-platform,IONISx/edx-platform,Ayub-Khan/edx-platform,edx/edx-platform,Kalyzee/edx-platform,Shrhawk/edx-platform,EduPepperPDTesting/pepper2013-testing,devs1991/test_edx_docmode,simbs/edx-platform,philanthropy-u/edx-platform,morenopc/edx-platform,ak2703/edx-platform,jazkarta/edx-platform-for-isc,jruiperezv/ANALYSE,JCBarahona/edX,knehez/edx-platform,simbs/edx-platform,atsolakid/edx-platform,philanthropy-u/edx-platform,openfun/edx-platform,don-github/edx-platform,sameetb-cuelogic/edx-platform-test,mcgachey/edx-platform,don-github/edx-platform,jbzdak/edx-platform,kxliugang/edx-platform,pomegranited/edx-platform,dcosentino/edx-platform,nanolearning/edx-platform,kursitet/edx-platform,DNFcode/edx-platform,shubhdev/edxOnBaadal,louyihua/edx-platform,zofuthan/edx-platform,ubc/edx-platform,tiagochiavericosta/edx-platform,Unow/edx-platform,marcore/edx-platform,devs1991/test_edx_docmode,SivilTaram/edx-platform,inares/edx-platform,mjirayu/sit_academy,JioEducation/edx-platform,vismartltd/edx-platform,jamiefolsom/edx-platform,PepperPD/edx-pepper-platform,caesar2164/edx-platform,10clouds/edx-platform,edry/edx-platform,ferabra/edx-platform,syjeon/new_edx,pabloborrego93/edx-platform,knehez/edx-platform,edx-solutions/edx-platform,CredoReference/edx-platform,chrisndodge/edx-platform,4eek/edx-platform,fintech-circle/edx-platform,hkawasaki/kawasaki-aio8-1,vikas1885/test1,y12uc231/edx-platform,ubc/edx-platform,olexiim/edx-platform,a-parhom/edx-platform,hkawasaki/kawasaki-aio8-2,raccoongang/edx-platform,ahmadio/edx-platform,solashirai/edx-platform,mjg2203/edx-platform-seas,wwj718/edx-platform,mjirayu/sit_academy,andyzsf/edx,motion2015/a3,pepeportela/edx-platform,Kalyzee/edx-platform,shabab12/edx-platform,analyseuc3m/ANALYSE-v1,vasyarv/edx-platform,kalebhartje/schoolboost,alexthered/kienhoc-platform,hkawasaki/kawasaki-aio8-1,auferack08/edx-platform,motion2015/edx-platform,chauhanhardik/populo_2,antoviaque/edx-platform,BehavioralInsightsTeam/edx-platform,BehavioralInsightsTeam/edx-platform,wwj718/edx-platform,shubhdev/openedx,kalebhartje/schoolboost,nikolas/edx-platform,bigdatauniversity/edx-platform,Edraak/circleci-edx-platform,pomegranited/edx-platform,y12uc231/edx-platform,abdoosh00/edx-rtl-final,xingyepei/edx-platform,wwj718/ANALYSE,chauhanhardik/populo_2,miptliot/edx-platform,cpennington/edx-platform,mahendra-r/edx-platform,valtech-mooc/edx-platform,ESOedX/edx-platform,shabab12/edx-platform,LearnEra/LearnEraPlaftform,kursitet/edx-platform,fintech-circle/edx-platform,dkarakats/edx-platform,mitocw/edx-platform,hkawasaki/kawasaki-aio8-2,jjmiranda/edx-platform,alu042/edx-platform,arifsetiawan/edx-platform,playm2mboy/edx-platform,dcosentino/edx-platform,mtlchun/edx,knehez/edx-platform,appsembler/edx-platform,LICEF/edx-platform,Unow/edx-platform,ahmedaljazzar/edx-platform,romain-li/edx-platform,mahendra-r/edx-platform,DefyVentures/edx-platform,RPI-OPENEDX/edx-platform,ovnicraft/edx-platform,nikolas/edx-platform,halvertoluke/edx-platform,eemirtekin/edx-platform,ahmedaljazzar/edx-platform,mcgachey/edx-platform,hkawasaki/kawasaki-aio8-2,benpatterson/edx-platform,olexiim/edx-platform,wwj718/edx-platform,jamesblunt/edx-platform,jzoldak/edx-platform,edx-solutions/edx-platform,apigee/edx-platform,dkarakats/edx-platform,jelugbo/tundex,J861449197/edx-platform,appsembler/edx-platform,adoosii/edx-platform,jswope00/griffinx,pelikanchik/edx-platform,msegado/edx-platform,eestay/edx-platform,apigee/edx-platform,Edraak/edx-platform,proversity-org/edx-platform,nanolearningllc/edx-platform-cypress-2,a-parhom/edx-platform,shubhdev/edxOnBaadal,J861449197/edx-platform,solashirai/edx-platform,Ayub-Khan/edx-platform,Edraak/edx-platform,auferack08/edx-platform,lduarte1991/edx-platform,cselis86/edx-platform,antonve/s4-project-mooc,MakeHer/edx-platform,SivilTaram/edx-platform,Livit/Livit.Learn.EdX,naresh21/synergetics-edx-platform,pepeportela/edx-platform,naresh21/synergetics-edx-platform,nttks/jenkins-test,doismellburning/edx-platform,tanmaykm/edx-platform,openfun/edx-platform,EduPepperPD/pepper2013,jswope00/griffinx,jjmiranda/edx-platform,dcosentino/edx-platform,arifsetiawan/edx-platform,rhndg/openedx,nanolearningllc/edx-platform-cypress,ubc/edx-platform,hamzehd/edx-platform,ahmedaljazzar/edx-platform,wwj718/ANALYSE,kamalx/edx-platform,ubc/edx-platform,Shrhawk/edx-platform,benpatterson/edx-platform,playm2mboy/edx-platform,bigdatauniversity/edx-platform,teltek/edx-platform,ovnicraft/edx-platform,auferack08/edx-platform,gsehub/edx-platform,iivic/BoiseStateX,pdehaye/theming-edx-platform,MSOpenTech/edx-platform,jamiefolsom/edx-platform,mtlchun/edx,IONISx/edx-platform,kmoocdev/edx-platform,xuxiao19910803/edx,vasyarv/edx-platform,shubhdev/edxOnBaadal,eduNEXT/edx-platform,cselis86/edx-platform,utecuy/edx-platform,shurihell/testasia,marcore/edx-platform,chauhanhardik/populo_2,a-parhom/edx-platform,ahmedaljazzar/edx-platform,nanolearning/edx-platform,jolyonb/edx-platform,y12uc231/edx-platform,sudheerchintala/LearnEraPlatForm,edx-solutions/edx-platform,jazztpt/edx-platform,louyihua/edx-platform,EduPepperPDTesting/pepper2013-testing,bitifirefly/edx-platform,franosincic/edx-platform,valtech-mooc/edx-platform,hamzehd/edx-platform,eduNEXT/edx-platform,jazkarta/edx-platform,B-MOOC/edx-platform,IONISx/edx-platform,mjirayu/sit_academy,alexthered/kienhoc-platform,antonve/s4-project-mooc,Shrhawk/edx-platform,ESOedX/edx-platform,xuxiao19910803/edx-platform,romain-li/edx-platform,appsembler/edx-platform,msegado/edx-platform,apigee/edx-platform,romain-li/edx-platform,halvertoluke/edx-platform,xuxiao19910803/edx-platform,PepperPD/edx-pepper-platform,jonathan-beard/edx-platform,zadgroup/edx-platform,MSOpenTech/edx-platform,analyseuc3m/ANALYSE-v1,nagyistoce/edx-platform,Unow/edx-platform,nikolas/edx-platform,Edraak/circleci-edx-platform,Semi-global/edx-platform,synergeticsedx/deployment-wipro,iivic/BoiseStateX,chauhanhardik/populo_2,J861449197/edx-platform,romain-li/edx-platform,UOMx/edx-platform,cyanna/edx-platform,Endika/edx-platform,shurihell/testasia,Lektorium-LLC/edx-platform,EduPepperPD/pepper2013,teltek/edx-platform,4eek/edx-platform,polimediaupv/edx-platform,mtlchun/edx,EduPepperPD/pepper2013,chauhanhardik/populo,beni55/edx-platform,itsjeyd/edx-platform,gymnasium/edx-platform,appliedx/edx-platform,abdoosh00/edx-rtl-final,mitocw/edx-platform,hkawasaki/kawasaki-aio8-0,cpennington/edx-platform,sudheerchintala/LearnEraPlatForm,unicri/edx-platform,chand3040/cloud_that,nanolearningllc/edx-platform-cypress,arbrandes/edx-platform,mcgachey/edx-platform,dsajkl/reqiop,defance/edx-platform,amir-qayyum-khan/edx-platform,waheedahmed/edx-platform,jonathan-beard/edx-platform,gymnasium/edx-platform,vikas1885/test1,rismalrv/edx-platform,zerobatu/edx-platform,gsehub/edx-platform,praveen-pal/edx-platform,ak2703/edx-platform,rue89-tech/edx-platform,Edraak/edx-platform,xuxiao19910803/edx-platform,nagyistoce/edx-platform,jamesblunt/edx-platform,adoosii/edx-platform,angelapper/edx-platform,OmarIthawi/edx-platform,RPI-OPENEDX/edx-platform,chauhanhardik/populo,jswope00/GAI,longmen21/edx-platform,jolyonb/edx-platform,bigdatauniversity/edx-platform,simbs/edx-platform,xuxiao19910803/edx,alu042/edx-platform,arbrandes/edx-platform,SravanthiSinha/edx-platform,chudaol/edx-platform,dcosentino/edx-platform,Edraak/edraak-platform,bitifirefly/edx-platform,rhndg/openedx,antoviaque/edx-platform,doismellburning/edx-platform,Semi-global/edx-platform,don-github/edx-platform,jruiperezv/ANALYSE,sameetb-cuelogic/edx-platform-test,nanolearningllc/edx-platform-cypress-2,appsembler/edx-platform,jazztpt/edx-platform,proversity-org/edx-platform,beni55/edx-platform,inares/edx-platform,beni55/edx-platform,hastexo/edx-platform,Semi-global/edx-platform,DefyVentures/edx-platform,wwj718/edx-platform,ubc/edx-platform,rationalAgent/edx-platform-custom,BehavioralInsightsTeam/edx-platform,abdoosh00/edraak,jbassen/edx-platform,zofuthan/edx-platform,etzhou/edx-platform,yokose-ks/edx-platform,TsinghuaX/edx-platform,jonathan-beard/edx-platform,beacloudgenius/edx-platform,unicri/edx-platform,solashirai/edx-platform,zhenzhai/edx-platform,WatanabeYasumasa/edx-platform,doganov/edx-platform,nikolas/edx-platform,IndonesiaX/edx-platform,TeachAtTUM/edx-platform,nanolearningllc/edx-platform-cypress,jazkarta/edx-platform,Softmotions/edx-platform,ak2703/edx-platform,eestay/edx-platform,mahendra-r/edx-platform,alexthered/kienhoc-platform,longmen21/edx-platform,jonathan-beard/edx-platform,vikas1885/test1,mushtaqak/edx-platform,J861449197/edx-platform,defance/edx-platform,benpatterson/edx-platform,DNFcode/edx-platform,hmcmooc/muddx-platform,fly19890211/edx-platform,cselis86/edx-platform,eduNEXT/edunext-platform,nttks/edx-platform,raccoongang/edx-platform,itsjeyd/edx-platform,jswope00/GAI,jelugbo/tundex,hastexo/edx-platform,jamesblunt/edx-platform,yokose-ks/edx-platform,a-parhom/edx-platform,louyihua/edx-platform,MakeHer/edx-platform,sameetb-cuelogic/edx-platform-test,franosincic/edx-platform,abdoosh00/edraak,edx/edx-platform,mtlchun/edx,LICEF/edx-platform,kursitet/edx-platform,analyseuc3m/ANALYSE-v1,utecuy/edx-platform,4eek/edx-platform,knehez/edx-platform,mjg2203/edx-platform-seas,edx/edx-platform,mjirayu/sit_academy,cognitiveclass/edx-platform,deepsrijit1105/edx-platform,shubhdev/openedx,martynovp/edx-platform,jbassen/edx-platform,kmoocdev2/edx-platform,beacloudgenius/edx-platform,motion2015/a3,devs1991/test_edx_docmode,doganov/edx-platform,tiagochiavericosta/edx-platform,hmcmooc/muddx-platform,polimediaupv/edx-platform,zhenzhai/edx-platform,fintech-circle/edx-platform,WatanabeYasumasa/edx-platform,vismartltd/edx-platform,jazkarta/edx-platform-for-isc,Softmotions/edx-platform,shabab12/edx-platform,zerobatu/edx-platform,mbareta/edx-platform-ft,morpheby/levelup-by,eduNEXT/edx-platform,tiagochiavericosta/edx-platform,zubair-arbi/edx-platform,unicri/edx-platform,mtlchun/edx,eestay/edx-platform,rismalrv/edx-platform,mushtaqak/edx-platform,jruiperezv/ANALYSE,valtech-mooc/edx-platform,iivic/BoiseStateX,pku9104038/edx-platform,playm2mboy/edx-platform,mbareta/edx-platform-ft,adoosii/edx-platform,nagyistoce/edx-platform,kmoocdev2/edx-platform,shubhdev/edx-platform,hkawasaki/kawasaki-aio8-1,LearnEra/LearnEraPlaftform,amir-qayyum-khan/edx-platform,chrisndodge/edx-platform,knehez/edx-platform,y12uc231/edx-platform,defance/edx-platform,pabloborrego93/edx-platform,waheedahmed/edx-platform,chudaol/edx-platform,ahmadio/edx-platform,DNFcode/edx-platform,ovnicraft/edx-platform,ampax/edx-platform,DefyVentures/edx-platform,nanolearningllc/edx-platform-cypress-2,jjmiranda/edx-platform,Kalyzee/edx-platform,EDUlib/edx-platform,atsolakid/edx-platform,msegado/edx-platform,shubhdev/edx-platform,nttks/edx-platform,Edraak/edraak-platform,doganov/edx-platform,shashank971/edx-platform,tanmaykm/edx-platform,kursitet/edx-platform,motion2015/a3,naresh21/synergetics-edx-platform,jazkarta/edx-platform-for-isc,CourseTalk/edx-platform,ampax/edx-platform-backup,ak2703/edx-platform,eduNEXT/edx-platform,pku9104038/edx-platform,synergeticsedx/deployment-wipro,mbareta/edx-platform-ft,kmoocdev/edx-platform,beni55/edx-platform,shubhdev/edx-platform,pdehaye/theming-edx-platform,zubair-arbi/edx-platform,kxliugang/edx-platform,prarthitm/edxplatform,prarthitm/edxplatform,chauhanhardik/populo_2,mushtaqak/edx-platform,ak2703/edx-platform,shurihell/testasia,gsehub/edx-platform,zofuthan/edx-platform,Livit/Livit.Learn.EdX,rue89-tech/edx-platform,IndonesiaX/edx-platform,martynovp/edx-platform,nttks/edx-platform,vismartltd/edx-platform,ahmadiga/min_edx,Semi-global/edx-platform,waheedahmed/edx-platform,teltek/edx-platform,B-MOOC/edx-platform,shubhdev/openedx,pelikanchik/edx-platform,shashank971/edx-platform,pomegranited/edx-platform,pabloborrego93/edx-platform,abdoosh00/edx-rtl-final,synergeticsedx/deployment-wipro,valtech-mooc/edx-platform,romain-li/edx-platform,jazztpt/edx-platform,carsongee/edx-platform,EduPepperPDTesting/pepper2013-testing,gymnasium/edx-platform,xinjiguaike/edx-platform,JCBarahona/edX,mcgachey/edx-platform,devs1991/test_edx_docmode,CredoReference/edx-platform,chand3040/cloud_that,marcore/edx-platform,leansoft/edx-platform,ferabra/edx-platform,Edraak/edx-platform,kmoocdev2/edx-platform,torchingloom/edx-platform,ahmadiga/min_edx,kxliugang/edx-platform,UXE/local-edx,motion2015/a3,chrisndodge/edx-platform,MakeHer/edx-platform,chudaol/edx-platform,ahmadio/edx-platform,leansoft/edx-platform,jamesblunt/edx-platform,arbrandes/edx-platform,sudheerchintala/LearnEraPlatForm,jazkarta/edx-platform,openfun/edx-platform,solashirai/edx-platform,IITBinterns13/edx-platform-dev,ZLLab-Mooc/edx-platform,bdero/edx-platform,jbzdak/edx-platform,bitifirefly/edx-platform,RPI-OPENEDX/edx-platform,rationalAgent/edx-platform-custom,Edraak/edraak-platform,jzoldak/edx-platform,deepsrijit1105/edx-platform,philanthropy-u/edx-platform,bdero/edx-platform,unicri/edx-platform,10clouds/edx-platform,Edraak/edraak-platform,syjeon/new_edx,shabab12/edx-platform,mcgachey/edx-platform,ahmadio/edx-platform,bdero/edx-platform,jbassen/edx-platform,nanolearningllc/edx-platform-cypress-2,leansoft/edx-platform,B-MOOC/edx-platform,andyzsf/edx,eduNEXT/edunext-platform,hmcmooc/muddx-platform,LICEF/edx-platform,kamalx/edx-platform,EDUlib/edx-platform,chand3040/cloud_that,zhenzhai/edx-platform,procangroup/edx-platform,utecuy/edx-platform,lduarte1991/edx-platform,DefyVentures/edx-platform,jelugbo/tundex,chand3040/cloud_that,ampax/edx-platform,benpatterson/edx-platform,pku9104038/edx-platform,morenopc/edx-platform,kmoocdev2/edx-platform,edx/edx-platform,JioEducation/edx-platform,wwj718/ANALYSE,naresh21/synergetics-edx-platform,jswope00/GAI,utecuy/edx-platform,mbareta/edx-platform-ft,cyanna/edx-platform,rismalrv/edx-platform,franosincic/edx-platform,zhenzhai/edx-platform,jamesblunt/edx-platform,nanolearning/edx-platform,xinjiguaike/edx-platform,jazkarta/edx-platform-for-isc,appliedx/edx-platform,rismalrv/edx-platform,UXE/local-edx,hkawasaki/kawasaki-aio8-0,antonve/s4-project-mooc,Kalyzee/edx-platform,carsongee/edx-platform,jswope00/GAI,rationalAgent/edx-platform-custom,motion2015/a3,etzhou/edx-platform,hamzehd/edx-platform,IndonesiaX/edx-platform,beacloudgenius/edx-platform,SravanthiSinha/edx-platform,peterm-itr/edx-platform,motion2015/edx-platform,lduarte1991/edx-platform,jazkarta/edx-platform-for-isc,miptliot/edx-platform,caesar2164/edx-platform,jswope00/griffinx,nanolearningllc/edx-platform-cypress,Lektorium-LLC/edx-platform,ampax/edx-platform-backup,UOMx/edx-platform,arifsetiawan/edx-platform,sameetb-cuelogic/edx-platform-test,Stanford-Online/edx-platform,nagyistoce/edx-platform,zadgroup/edx-platform,MSOpenTech/edx-platform,nttks/edx-platform,torchingloom/edx-platform,LearnEra/LearnEraPlaftform,ZLLab-Mooc/edx-platform,IITBinterns13/edx-platform-dev,wwj718/edx-platform,teltek/edx-platform,angelapper/edx-platform,kamalx/edx-platform,fly19890211/edx-platform
common/djangoapps/mitxmako/tests.py
common/djangoapps/mitxmako/tests.py
from django.test import TestCase from django.test.utils import override_settings from django.core.urlresolvers import reverse from django.conf import settings from mitxmako.shortcuts import marketing_link from mock import patch class ShortcutsTests(TestCase): """ Test the mitxmako shortcuts file """ @override_settings(MKTG_URLS={'ROOT': 'dummy-root', 'ABOUT': '/about-us'}) @override_settings(MKTG_URL_LINK_MAP={'ABOUT': 'about_edx'}) def test_marketing_link(self): # test marketing site on with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': True}): expected_link = 'dummy-root/about-us' link = marketing_link('ABOUT') self.assertEquals(link, expected_link) # test marketing site off with patch.dict('django.conf.settings.MITX_FEATURES', {'ENABLE_MKTG_SITE': False}): expected_link = reverse('about_edx') link = marketing_link('ABOUT') self.assertEquals(link, expected_link)
agpl-3.0
Python
7236d0358064968b9cbb0ab7f4ee9876dea02aaa
add python common functions
DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public
python/tcp_port_scan/tcp_port_scan.py
python/tcp_port_scan/tcp_port_scan.py
# -*- coding: utf-8 -*- #!/usr/bin/python ##------------------------------------------------------------------- ## @copyright 2015 DennyZhang.com ## File : tcp_port_scan.py ## Author : DennyZhang.com <[email protected]> ## Description : ## -- ## Created : <2016-01-15> ## Updated: Time-stamp: <2016-08-11 23:14:08> ##------------------------------------------------------------------- import argparse import subprocess import os, sys ################################################################################ # TODO: move to common library def strip_comments(string): # remove empty lines and comments (# ...) from string l = [] for line in string.split("\n"): line = line.strip() if line.startswith("#") or line == "": continue l.append(line) return "\n".join(l) def string_remove(string, opt_list): l = [] # remove entries from string for line in string.split("\n"): should_remove = False for item in opt_list: if item in line: should_remove = True if should_remove is False: l.append(line) return "\n".join(l) # TODO: common logging ################################################################################ nmap_command = "sudo nmap -sS -PN %s" # ("-p T:XXX,XXX 192.168.0.16") result_dict = {} def nmap_check(server_ip, ports): if ports == "": nmap_opts = server_ip else: nmap_opts = "-p %s %s" % (ports, server_ip) command = nmap_command % (nmap_opts) print "Run: %s" % (command) nmap_output = subprocess.check_output(command, shell=True) return cleanup_nmap_output(nmap_outputoutput, server_ip) def cleanup_nmap_output(nmap_output, server_ip): return nmap_output def audit_open_ports(port_list, whitelist): return ################################################################################ if __name__=='__main__': # Sample: # python ./tcp_port_scan.py --server_list_file XXX --port_list_file XXXX --white_list_file XXX parser = argparse.ArgumentParser() parser.add_argument('--server_list_file', required=True, help="ip list to scan", type=str) parser.add_argument('--port_list_file', required=True, help="customized tcp ports to scan", type=str) parser.add_argument('--white_list_file', required=True, help="safe ports to allow open", type=str) args = parser.parse_args() server_list_file = args.server_list_file port_list_file = args.port_list_file white_list_file = args.white_list_file print nmap_check("104.131.129.100", "") ## File : tcp_port_scan.py ends
mit
Python
a119c9f53babd87f5e5adc1886256c59a21c19a5
Move content_type formatting support to a different module
yasoob/hug,MuhammadAlkarouri/hug,timothycrosley/hug,timothycrosley/hug,MuhammadAlkarouri/hug,timothycrosley/hug,alisaifee/hug,origingod/hug,jean/hug,alisaifee/hug,philiptzou/hug,jean/hug,giserh/hug,janusnic/hug,janusnic/hug,MuhammadAlkarouri/hug,gbn972/hug,STANAPO/hug,yasoob/hug,shaunstanislaus/hug,giserh/hug,gbn972/hug,shaunstanislaus/hug,origingod/hug,STANAPO/hug,philiptzou/hug
hug/format.py
hug/format.py
def content_type(content_type): '''Attaches an explicit HTML content type to a Hug formatting function''' def decorator(method): method.content_type = content_type return method return decorator
mit
Python
ef803b8ac95bb2440d1d312584376149573ac798
Create bbgdailyhistory.py
tagomatech/ETL
BBG/bbgdailyhistory.py
BBG/bbgdailyhistory.py
# *- bbgdailyhistory.py -* import os import numpy as np import pandas as pd import blpapi class BBGDailyHistory: ''' Parameters ---------- sec : str Ticker fields : str or list Field of list of fields ('PX_HIGH', 'PX_LOW', etc...) start : str Start date end : stf End date ''' def __init__(self, sec, fields, start=None, end=None): #self.rqst = rqst self.sec = sec self.fields = fields self.start = start self.end = end def get_data(self) -> pd.DataFrame: ''' Returns ------- data : pd.DataFrame() The historical data queried returned in a dataFrame presented as long format ''' # Session management sess = blpapi.Session() sess.start() # Define data type sess.openService('//blp/refdata') service = sess.getService('//blp/refdata') # Create request request = service.createRequest('HistoricalDataRequest') # Optional request setters request.set('startDate', self.start) request.set('endDate', self.end) request.getElement('securities').appendValue(self.sec) # Data holders date_acc =[] ticker_acc = [] field_acc = [] value_acc = [] # Loop over fields for fie in self.fields: request.getElement('fields').appendValue(fie) sess.sendRequest(request) endReached = False while endReached == False: event = sess.nextEvent(500) if event.eventType() == blpapi.Event.RESPONSE or event.eventType() == blpapi.Event.PARTIAL_RESPONSE: for msg in event: fieldData = msg.getElement('securityData').getElement('fieldData') for data in fieldData.values(): for fld in self.fields: date_acc.append(data.getElement('date').getValue()) field_acc.append(fld) value_acc.append(data.getElement(fld).getValue()) ticker_acc.append(self.sec) if event.eventType() == blpapi.Event.RESPONSE: endReached = True sess.stop() data = pd.DataFrame({'timestamp' : date_acc, 'ticker' : ticker_acc, 'field' : fie, 'value' : value_acc}) return data if __name__ == "__main__": # Use example of BBGHistory #from bbgdatapuller import BBGHistory # Expect folder issue security = 'SIMA SW Equity' #'SIMA SW Equity' fields = ['PX_OPEN', 'PX_HIGH', 'PX_LOW', 'PX_LAST'] start = '20200105' end = '20200109' d = BBGDailyHistory(sec=security, fields=fields, start=start, end=end).get_data() print(d.head())
mit
Python
353868bc281ade826b48d2c5a79ad14986c0d35c
Create lowercaseLists.py
ReginaExMachina/royaltea-word-app,ReginaExMachina/royaltea-word-app
Bits/lowercaseLists.py
Bits/lowercaseLists.py
#!/usr/bin/env python docs = ["The Corporation", "Valentino: The Last Emperor", "Kings of Patsry"] movies = ["The Talented Mr. Ripley", "The Network", "Silence of the Lambs", "Wall Street", "Marie Antoinette", "My Mana Godfrey", "Rope", "Sleuth"] films = [[docs], [movies]] movies[5] = "My Man Godfrey" docs[-1] = "Kings of Pastry" y = [x.lower() for x in ["A","B","C"]] print(y) newFilmsList = [x.lower() for x in docs] + [x.lower() for x in movies] print(newFilmsList)
mit
Python
9afd1a8d3584e45d32858c3b8fa44efd0f1a09f1
add unit test for ofproto automatic detection
haniehrajabi/ryu,alyosha1879/ryu,gopchandani/ryu,haniehrajabi/ryu,Zouyiran/ryu,elahejalalpour/ELRyu,takahashiminoru/ryu,ttsubo/ryu,pichuang/ryu,lsqtongxin/ryu,zangree/ryu,jalilm/ryu,zangree/ryu,evanscottgray/ryu,habibiefaried/ryu,citrix-openstack-build/ryu,yamt/ryu,gopchandani/ryu,shinpeimuraoka/ryu,habibiefaried/ryu,sivaramakrishnansr/ryu,torufuru/OFPatchPanel,umkcdcrg01/ryu_openflow,haniehrajabi/ryu,elahejalalpour/ELRyu,ynkjm/ryu,Tejas-Subramanya/RYU_MEC,openvapour/ryu,samrussell/ryu,gareging/SDN_Framework,osrg/ryu,muzixing/ryu,fujita/ryu,unifycore/ryu,hisaharu/ryu,o3project/ryu-oe,hisaharu/ryu,evanscottgray/ryu,fujita/ryu,John-Lin/ryu,lzppp/mylearning,torufuru/oolhackathon,habibiefaried/ryu,zangree/ryu,Tesi-Luca-Davide/ryu,StephenKing/ryu,mikhaelharswanto/ryu,OpenState-SDN/ryu,jkoelker/ryu,openvapour/ryu,OpenState-SDN/ryu,alanquillin/ryu,elahejalalpour/ELRyu,TakeshiTseng/ryu,ntts-clo/mld-ryu,zangree/ryu,darjus-amzn/ryu,osrg/ryu,Zouyiran/ryu,Tejas-Subramanya/RYU_MEC,ttsubo/ryu,ynkjm/ryu,ysywh/ryu,Zouyiran/ryu,Tesi-Luca-Davide/ryu,iwaseyusuke/ryu,fkakuma/ryu,alanquillin/ryu,alyosha1879/ryu,habibiefaried/ryu,yamt/ryu,fkakuma/ryu,alanquillin/ryu,takahashiminoru/ryu,Tesi-Luca-Davide/ryu,John-Lin/ryu,Tejas-Subramanya/RYU_MEC,StephenKing/ryu,yamada-h/ryu,o3project/ryu-oe,shinpeimuraoka/ryu,TakeshiTseng/ryu,umkcdcrg01/ryu_openflow,ysywh/ryu,yamada-h/ryu,muzixing/ryu,castroflavio/ryu,ttsubo/ryu,ttsubo/ryu,zyq001/ryu,openvapour/ryu,pichuang/ryu,ysywh/ryu,darjus-amzn/ryu,jkoelker/ryu,ttsubo/ryu,gareging/SDN_Framework,pichuang/ryu,castroflavio/ryu,shinpeimuraoka/ryu,zyq001/ryu,gareging/SDN_Framework,OpenState-SDN/ryu,pichuang/ryu,torufuru/oolhackathon,iwaseyusuke/ryu,diogommartins/ryu,jazzmes/ryu,castroflavio/ryu,torufuru/OFPatchPanel,lagopus/ryu-lagopus-ext,unifycore/ryu,gopchandani/ryu,zyq001/ryu,yamt/ryu,jazzmes/ryu,diogommartins/ryu,muzixing/ryu,iwaseyusuke/ryu,sivaramakrishnansr/ryu,StephenKing/ryu,osrg/ryu,fkakuma/ryu,muzixing/ryu,samrussell/ryu,OpenState-SDN/ryu,alanquillin/ryu,gopchandani/ryu,iwaseyusuke/ryu,takahashiminoru/ryu,lagopus/ryu-lagopus-ext,lsqtongxin/ryu,elahejalalpour/ELRyu,shinpeimuraoka/ryu,haniehrajabi/ryu,John-Lin/ryu,jalilm/ryu,ynkjm/ryu,Tesi-Luca-Davide/ryu,takahashiminoru/ryu,muzixing/ryu,openvapour/ryu,hisaharu/ryu,Zouyiran/ryu,fkakuma/ryu,yamt/ryu,osrg/ryu,fujita/ryu,haniehrajabi/ryu,osrg/ryu,mikhaelharswanto/ryu,lsqtongxin/ryu,elahejalalpour/ELRyu,jalilm/ryu,alanquillin/ryu,sivaramakrishnansr/ryu,fujita/ryu,sivaramakrishnansr/ryu,John-Lin/ryu,citrix-openstack/build-ryu,Tejas-Subramanya/RYU_MEC,citrix-openstack-build/ryu,jkoelker/ryu,Tejas-Subramanya/RYU_MEC,alyosha1879/ryu,lsqtongxin/ryu,lagopus/ryu-lagopus-ext,yamt/ryu,torufuru/oolhackathon,hisaharu/ryu,StephenKing/summerschool-2015-ryu,StephenKing/summerschool-2015-ryu,alyosha1879/ryu,fkakuma/ryu,sivaramakrishnansr/ryu,ysywh/ryu,diogommartins/ryu,lsqtongxin/ryu,lzppp/mylearning,ntts-clo/mld-ryu,StephenKing/summerschool-2015-ryu,StephenKing/ryu,TakeshiTseng/ryu,OpenState-SDN/ryu,umkcdcrg01/ryu_openflow,hisaharu/ryu,darjus-amzn/ryu,John-Lin/ryu,pichuang/ryu,gopchandani/ryu,gareging/SDN_Framework,darjus-amzn/ryu,jazzmes/ryu,lzppp/mylearning,ntts-clo/ryu,ysywh/ryu,zangree/ryu,Zouyiran/ryu,iwaseyusuke/ryu,ynkjm/ryu,gareging/SDN_Framework,StephenKing/summerschool-2015-ryu,StephenKing/ryu,zyq001/ryu,openvapour/ryu,jalilm/ryu,umkcdcrg01/ryu_openflow,diogommartins/ryu,habibiefaried/ryu,StephenKing/summerschool-2015-ryu,umkcdcrg01/ryu_openflow,citrix-openstack/build-ryu,diogommartins/ryu,Tesi-Luca-Davide/ryu,ynkjm/ryu,lagopus/ryu-lagopus-ext,TakeshiTseng/ryu,darjus-amzn/ryu,jalilm/ryu,takahashiminoru/ryu,evanscottgray/ryu,zyq001/ryu,lzppp/mylearning,lagopus/ryu-lagopus-ext,shinpeimuraoka/ryu,ntts-clo/ryu,fujita/ryu,lzppp/mylearning,TakeshiTseng/ryu
ryu/tests/unit/ofproto/test_ofproto.py
ryu/tests/unit/ofproto/test_ofproto.py
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # vim: tabstop=4 shiftwidth=4 softtabstop=4 import unittest import logging from nose.tools import eq_ LOG = logging.getLogger('test_ofproto') class TestOfprotCommon(unittest.TestCase): """ Test case for ofproto """ def test_ofp_event(self): import ryu.ofproto reload(ryu.ofproto) import ryu.controller.ofp_event reload(ryu.controller.ofp_event) def test_ofproto(self): # When new version of OFP support is added, # this test must be updated. import ryu.ofproto reload(ryu.ofproto) ofp_modules = ryu.ofproto.get_ofp_modules() import ryu.ofproto.ofproto_v1_0 import ryu.ofproto.ofproto_v1_2 import ryu.ofproto.ofproto_v1_3 eq_(set(ofp_modules.keys()), set([ryu.ofproto.ofproto_v1_0.OFP_VERSION, ryu.ofproto.ofproto_v1_2.OFP_VERSION, ryu.ofproto.ofproto_v1_3.OFP_VERSION, ])) consts_mods = set([ofp_mod[0] for ofp_mod in ofp_modules.values()]) eq_(consts_mods, set([ryu.ofproto.ofproto_v1_0, ryu.ofproto.ofproto_v1_2, ryu.ofproto.ofproto_v1_3, ])) parser_mods = set([ofp_mod[1] for ofp_mod in ofp_modules.values()]) import ryu.ofproto.ofproto_v1_0_parser import ryu.ofproto.ofproto_v1_2_parser import ryu.ofproto.ofproto_v1_3_parser eq_(parser_mods, set([ryu.ofproto.ofproto_v1_0_parser, ryu.ofproto.ofproto_v1_2_parser, ryu.ofproto.ofproto_v1_3_parser, ]))
apache-2.0
Python
657591afce265521078a7cb2f84347c2319b6b33
Add tests to help with autograding
jhamrick/original-nbgrader,jhamrick/original-nbgrader
nbgrader/tests.py
nbgrader/tests.py
import nose.tools import numpy as np def assert_unequal(a, b, msg=""): if a == b: raise AssertionError(msg) def assert_same_shape(a, b): a_ = np.array(a, copy=False) b_ = np.array(b, copy=False) assert a_.shape == b_.shape, "{} != {}".format(a_.shape, b_.shape) def assert_allclose(a, b): assert np.allclose(a, b), "{} != {}".format(a, b) assert_equal = nose.tools.eq_ assert_raises = nose.tools.assert_raises
mit
Python
5e7746d054f7762d93e1f70296fa3b43f882553c
Add synthtool scripts (#3765)
googleapis/google-cloud-java,googleapis/google-cloud-java,googleapis/google-cloud-java
java-bigquerydatatransfer/google-cloud-bigquerydatatransfer/synth.py
java-bigquerydatatransfer/google-cloud-bigquerydatatransfer/synth.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script is used to synthesize generated parts of this library.""" import synthtool as s import synthtool.gcp as gcp gapic = gcp.GAPICGenerator() common_templates = gcp.CommonTemplates() library = gapic.java_library( service='bigquerydatatransfer', version='v1', config_path='/google/cloud/bigquery/datatransfer/artman_bigquerydatatransfer.yaml', artman_output_name='google-cloud-bigquerydatatransfer-v1') s.copy(library / 'gapic-google-cloud-bigquerydatatransfer-v1/src', 'src') s.copy(library / 'grpc-google-cloud-bigquerydatatransfer-v1/src', '../../google-api-grpc/grpc-google-cloud-bigquerydatatransfer-v1/src') s.copy(library / 'proto-google-cloud-bigquerydatatransfer-v1/src', '../../google-api-grpc/proto-google-cloud-bigquerydatatransfer-v1/src')
apache-2.0
Python
c13ec330194612832dfb0953d3e561a0ac151d69
add irrigation baseline file gen scripts
akrherz/dep,akrherz/dep,akrherz/dep,akrherz/dep,akrherz/dep
scripts/RT/create_irrigation_files.py
scripts/RT/create_irrigation_files.py
"""Create the generalized irrigation files, for now. https://www.ars.usda.gov/ARSUserFiles/50201000/WEPP/usersum.pdf page 60 """ from datetime import date LASTYEAR = date.today().year def main(): """Create files.""" for ofecnt in range(1, 7): # Do we have more than 6 OFEs? fn = f"/i/0/irrigation/ofe{ofecnt}.txt" with open(fn, "w", encoding="utf-8") as fh: fh.write("95.7\n") # datver fh.write(f"{ofecnt} 2 1\n") # furrow depletion fh.write("0.013 0.025\n") # mindepth maxdepth for year in range(2007, LASTYEAR + 1): for ofe in range(1, ofecnt): fh.write( f"{ofe} 0.176E-05 1.3 0.5 1.0 175 {year} 185 {year}\n" ) if __name__ == "__main__": main()
mit
Python
dfdbadbd83d41ccf71be74c7add6e04513a752d2
Add Custom Field Change Report script
closeio/closeio-api-scripts
scripts/custom_field_change_report.py
scripts/custom_field_change_report.py
import sys import argparse from closeio_api import Client as CloseIO_API, APIError import csv reload(sys) sys.setdefaultencoding('utf-8') parser = argparse.ArgumentParser(description='Export a list of custom field changes for a specific custom field') parser.add_argument('--api-key', '-k', required=True, help='API Key') parser.add_argument('--start-date', '-s', help='The start of the date range you want to export call data for in yyyy-mm-dd format.') parser.add_argument('--end-date', '-e', help='The end of the date range you want to export call data for in yyyy-mm-dd format.') parser.add_argument('--custom-field', '-f', required=True, help='The lcf id of the custom field you\'re searching for') parser.add_argument('--lead-id', '-l', help='Use this field if you want to narrow your search to a specific lead_id') parser.add_argument('--user-id', '-u', help='Use this field if you want to narrow your search to changes done by a specific user') args = parser.parse_args() api = CloseIO_API(args.api_key) org_id = api.get('api_key/' + args.api_key)['organization_id'] org = api.get('organization/' + org_id, params={ '_fields': 'id,name,memberships,inactive_memberships,lead_custom_fields'}) org_name = org['name'].replace('/', "") org_memberships = org['memberships'] + org['inactive_memberships'] try: custom_field_name = [i for i in org['lead_custom_fields'] if i['id'] == args.custom_field][0]['name'] except IndexError as e: print "ERROR: Could not find custom field %s in %s" % (args.custom_field, org_name) sys.exit() users = {} for member in org_memberships: users[member['user_id']] = member['user_full_name'] params = { 'object_type': 'lead', 'action': 'updated' } events = [] custom_lcf = "custom." + str(args.custom_field) if args.start_date: params['date_updated__gte'] = args.start_date if args.end_date: params['date_updated__lte'] = args.end_date if args.lead_id: params['lead_id'] = args.lead_id if args.user_id: params['user_id'] = args.user_id has_more = True cursor = '' count = 0 while has_more: params['_cursor'] = cursor try: resp = api.get('event', params=params) for event in resp['data']: if custom_lcf in event['changed_fields'] and event.get('previous_data') and event.get('data'): events.append({ 'Date': event['date_created'], 'Lead ID': event['lead_id'], 'Lead Name': event['data']['display_name'], 'User that Made the Change': event['user_id'], 'Old Value': event['previous_data'].get(custom_lcf), 'New Value': event['data'].get(custom_lcf) }) cursor = resp['cursor_next'] count += len(resp['data']) print "Analyzed Events: %s" % count has_more = bool(resp['cursor_next']) except APIError as e: pass print "Total %s Change Events Found: %s" % (custom_field_name, len(events)) f = open('%s %s Custom Field Changes.csv' % (org_name, custom_field_name), 'wt') try: ordered_keys = ['Date', 'Lead ID', 'Lead Name', 'User that Made the Change', 'Old Value', 'New Value'] writer = csv.DictWriter(f, ordered_keys) writer.writeheader() writer.writerows(events) finally: f.close()
mit
Python
1b9aa5ccd500e17aa32c315e212068c8be96216c
Add profiler, now not import. thanks @tweekmoster!
zchee/deoplete-go,zchee/deoplete-go
rplugin/python3/deoplete/sources/deoplete_go/profiler.py
rplugin/python3/deoplete/sources/deoplete_go/profiler.py
import functools import queue try: import statistics stdev = statistics.stdev mean = statistics.mean except ImportError: stdev = None def mean(l): return sum(l) / len(l) try: import time clock = time.perf_counter except Exception: import timeit clock = timeit.default_timer class tfloat(float): color = 39 def __str__(self): n = self * 1000 return '\x1b[%dm%f\x1b[mms' % (self.color, n) def profile(func): name = func.__name__ samples = queue.deque(maxlen=5) @functools.wraps(func) def wrapper(self, *args, **kwargs): if not self.debug_enabled: return func(self, *args, **kwargs) start = clock() ret = func(self, *args, **kwargs) n = tfloat(clock() - start) if len(samples) < 2: m = 0 d = 0 n.color = 36 else: m = mean(samples) if stdev: d = tfloat(stdev(samples)) else: d = 0 if n <= m + d: n.color = 32 elif n > m + d * 2: n.color = 31 else: n.color = 33 samples.append(n) self.info('\x1b[34m%s\x1b[m t = %s, \u00b5 = %s, \u03c3 = %s)', name, n, m, d) return ret return wrapper
mit
Python
6df31f3b1049071bf5112521de8876d94e8a959a
Add support for the TinyOS 2.x serial forwarder protocol
samboiki/smap-data,samboiki/smap-data,samboiki/smap-data,samboiki/smap-data,samboiki/smap-data
python/smap/iface/tinyos.py
python/smap/iface/tinyos.py
""" Copyright (c) 2013 Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ """ Provide twisted support for TinyOS serial forwarders. You should subclass TOSSerialClient and implement packetReceived. You can then connect it to a transport, for instance a serial port, using: from twisted.internet.serialport import SerialPort SerialPort(KetiMoteReceiver(self), port, reactor, baudrate=baud) Based on Razvan Musaloiu-E.'s tos.py @author Stephen Dawson-Haggerty <[email protected]> """ from twisted.internet import reactor, protocol class TOSSerialClient(protocol.Protocol): HDLC_FLAG_BYTE = 0x7e HDLC_CTLESC_BYTE = 0x7d def __init__(self): self.packet = [] def dataReceived(self, data): self._pump(data) def _pump(self, data): # Developer notes: # # Packet data read from Serial is in this format: # [HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE] # # [Escaped data] is encoded so that [HDLC_FLAG_BYTE] byte # values cannot occur within it. When [Escaped data] has been # unescaped, the last 2 bytes are a 16-bit CRC of the earlier # part of the packet (excluding the initial HDLC_FLAG_BYTE # byte) # # It's also possible that the serial device was half-way # through transmitting a packet when this function was called # (app was just started). So we also neeed to handle this case: # # [Incomplete escaped data][HDLC_FLAG_BYTE][HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE] # # In this case we skip over the first (incomplete) packet. # # Read bytes until we get to a HDLC_FLAG_BYTE value # (either the end of a packet, or the start of a new one) for d in data: if ord(d) == self.HDLC_FLAG_BYTE: self._deliver() else: self.packet.append(ord(d)) def _deliver(self): # Decode the packet, and check CRC: packet = self._unescape(self.packet) self.packet = [] crc = self._crc16(0, packet[:-2]) packet_crc = self._decode(packet[-2:]) if crc != packet_crc: print "Warning: wrong CRC! %x != %x %s" % \ (crc, packet_crc, ["%2x" % i for i in packet]) if len(packet): self.packetReceived(''.join(map(chr, packet[:-2]))) def _unescape(self, packet): r = [] esc = False for b in packet: if esc: r.append(b ^ 0x20) esc = False elif b == self.HDLC_CTLESC_BYTE: esc = True else: r.append(b) return r def _decode(self, v): r = long(0) for i in v[::-1]: r = (r << 8) + i return r def _crc16(self, base_crc, frame_data): crc = base_crc for b in frame_data: crc = crc ^ (b << 8) for i in range(0, 8): if crc & 0x8000 == 0x8000: crc = (crc << 1) ^ 0x1021 else: crc = crc << 1 crc = crc & 0xffff return crc
bsd-2-clause
Python
e9f2e966361d8a23c83fbbbb4a4b3d4046203a16
Test script for the heart container
cerr/CERR,cerr/CERR,cerr/CERR,aditiiyer/CERR,aditiiyer/CERR,aditiiyer/CERR,aditiiyer/CERR,cerr/CERR,cerr/CERR,cerr/CERR,aditiiyer/CERR,cerr/CERR,aditiiyer/CERR,cerr/CERR,aditiiyer/CERR,cerr/CERR,aditiiyer/CERR
CERR_core/Contouring/models/heart/test/test.py
CERR_core/Contouring/models/heart/test/test.py
#Test script for heart container testing if all the imports are successful import sys import os import numpy as np import h5py import fnmatch from modeling.sync_batchnorm.replicate import patch_replication_callback from modeling.deeplab import * from torchvision.utils import make_grid from dataloaders.utils import decode_seg_map_sequence from skimage.transform import resize from dataloaders import custom_transforms as tr from PIL import Image from torchvision import transforms input_size = 512 def main(argv): print("All imports done. Test Successful") if __name__ == "__main__": main(sys.argv)
lgpl-2.1
Python
b223c8be2bcb11d529a07997c05a9c5ab2b183b2
Add basic tests for run length encoding printable
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
csunplugged/tests/resources/generators/test_run_length_encoding.py
csunplugged/tests/resources/generators/test_run_length_encoding.py
from unittest import mock from django.http import QueryDict from django.test import tag from resources.generators.RunLengthEncodingResourceGenerator import RunLengthEncodingResourceGenerator from tests.resources.generators.utils import BaseGeneratorTest @tag("resource") class RunLengthEncodingResourceGeneratorTest(BaseGeneratorTest): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.language = "en" def test_worksheet_version_values(self): query = QueryDict("worksheet_type=student-basic&paper_size=a4") generator = RunLengthEncodingResourceGenerator(query) self.run_parameter_smoke_tests(generator, "worksheet_type") def test_subtitle_student_basic_a4(self): query = QueryDict("worksheet_type=student-basic&paper_size=a4") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Kid Fax - a4" ) def test_subtitle_student_basic_letter(self): query = QueryDict("worksheet_type=student-basic&paper_size=letter") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Kid Fax - letter" ) def test_subtitle_student_create_a4(self): query = QueryDict("worksheet_type=student-create&paper_size=a4") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Create your own - a4" ) def test_subtitle_student_create_letter(self): query = QueryDict("worksheet_type=student-create&paper_size=letter") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Create your own - letter" ) def test_subtitle_student_create_colour_a4(self): query = QueryDict("worksheet_type=student-create-colour&paper_size=a4") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Create your own in colour - a4" ) def test_subtitle_student_create_colour_letter(self): query = QueryDict("worksheet_type=student-create-colour&paper_size=letter") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Student Worksheet - Create your own in colour - letter" ) def test_subtitle_student_teacher_a4(self): query = QueryDict("worksheet_type=teacher&paper_size=a4") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Teacher Worksheet - a4" ) def test_subtitle_student_teacher_letter(self): query = QueryDict("worksheet_type=teacher&paper_size=letter") generator = RunLengthEncodingResourceGenerator(query) self.assertEqual( generator.subtitle, "Teacher Worksheet - letter" )
mit
Python
24c3166906c8431523c641721e635fdc28fd91ce
add server that tests if a cookie was set
thiagoss/adaptive-test-server
cookiescheck-test-server.py
cookiescheck-test-server.py
import sys from flask import Flask, request, send_from_directory, make_response, abort app = Flask(__name__) filepath = None mainpath = None @app.route('/<path:path>') def get(path): ret = make_response(send_from_directory(filepath, path)) if path == mainpath: ret.set_cookie('auth', '1') elif request.cookies.get('auth') == '1': pass else: abort(403) return ret if __name__ == "__main__": if len(sys.argv) != 3: print "Usage: %s <dir-to-serve> <main-file>" sys.exit(1) print sys.argv filepath = sys.argv[1] mainpath = sys.argv[2] app.run(host='0.0.0.0')
lgpl-2.1
Python
c011154135a73db2c5bba247fc33f94032553f2e
Correct package files
savex/spectra
janitor/__init__.py
janitor/__init__.py
import utils utils = utils logger, logger_api = utils.logger.setup_loggers( "janitor" )
apache-2.0
Python
1c692359231f97c3b398861fef9d5c695e8ff5f8
Add config file module using Property List backed files.
kdart/pycopia,kdart/pycopia,kdart/pycopia,kdart/pycopia,kdart/pycopia
core/pycopia/plistconfig.py
core/pycopia/plistconfig.py
#!/usr/bin/python2 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # # Copyright (C) 2010 Keith Dart <[email protected]> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. """ Config object backed by a property list file. A property list file is an XML format text file using Apple's Property List DTD (PropertyList-1.0.dtd). """ from __future__ import absolute_import from __future__ import print_function #from __future__ import unicode_literals from __future__ import division import os import re import plistlib class AutoAttrDict(dict): """A dictionary with attribute-style access and automatic container node creation. """ def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) def __getstate__(self): return self.__dict__.items() def __setstate__(self, items): for key, val in items: self.__dict__[key] = val def __repr__(self): return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self)) def __setitem__(self, key, value): return super(AutoAttrDict, self).__setitem__(key, value) def __getitem__(self, name): try: return super(AutoAttrDict, self).__getitem__(name) except KeyError: d = AutoAttrDict() super(AutoAttrDict, self).__setitem__(name, d) return d def __delitem__(self, name): return super(AutoAttrDict, self).__delitem__(name) __getattr__ = __getitem__ __setattr__ = __setitem__ def copy(self): return AutoAttrDict(self) # perform shell-like variable expansion def expand(self, value): if '$' not in value: return value i = 0 while 1: mo = _var_re.search(value, i) if not mo: return value i, j = mo.span(0) oname = vname = mo.group(1) if vname.startswith('{') and vname.endswith('}'): vname = vname[1:-1] tail = value[j:] value = value[:i] + str(self.get(vname, "$"+oname)) i = len(value) value += tail def tofile(self, path_or_file): write_config(self, path_or_file) _var_re = re.compile(r'\$([a-zA-Z0-9_\?]+|\{[^}]*\})') def read_config_from_string(pstr): d = plistlib.readPlistFromString(pstr) return _convert_dict(d) def read_config(path_or_file): """Read a property list config file.""" d = plistlib.readPlist(path_or_file) return _convert_dict(d) def _convert_dict(d): for key, value in d.iteritems(): if isinstance(value, dict): d[key] = _convert_dict(value) return AutoAttrDict(d) def write_config_to_string(conf): return plistlib.writePlistToString(conf) def write_config(conf, path_or_file): """Write a property list config file.""" plistlib.writePlist(conf, path_or_file) def get_config(filename=None, init=None): """Get an existing or new plist config object. Optionally initialize from another dictionary. """ if init is not None: return _convert_dict(init) if filename is None: return AutoAttrDict() if os.path.exists(filename): return read_config(filename) else: d = AutoAttrDict() write_config(d, filename) return d if __name__ == "__main__": cf = get_config() cf.parts.program.flags.flagname = 2 cf.parts.program.path = "$BASE/program" cf.parts.BASE = "bin" assert cf.parts.program.flags.flagname == 2 assert cf.parts.program.path == "$BASE/program" assert cf.parts.expand(cf.parts.program.path) == "bin/program" cf.tofile("/tmp/testplist.plist") del cf cf = read_config("/tmp/testplist.plist") assert cf.parts.program.flags.flagname == 2 assert cf.parts.program.path == "$BASE/program" assert cf.parts.expand(cf.parts.program.path) == "bin/program" cf.parts.program.flags.flagname = 3 assert cf.parts.program.flags.flagname == 3 cf.tofile("/tmp/testplist.plist") del cf cf = read_config("/tmp/testplist.plist") assert cf.parts.program.flags.flagname == 3
apache-2.0
Python
b6aedc1589c754bb867381e309aba5ae19f7bb1a
Create GDAL_SaveRaster.py
leandromet/Geoprocessamento---Geoprocessing,leandromet/Geoprocessamento---Geoprocessing,leandromet/Geoprocessamento---Geoprocessing,leandromet/Geoprocessamento---Geoprocessing,leandromet/Geoprocessamento---Geoprocessing
GDAL_SaveRaster.py
GDAL_SaveRaster.py
from osgeo import gdal def save_raster ( output_name, raster_data, dataset, driver="GTiff" ): """ A function to save a 1-band raster using GDAL to the file indicated by ``output_name``. It requires a GDAL-accesible dataset to collect the projection and geotransform. """ # Open the reference dataset g_input = gdal.Open ( dataset ) # Get the Geotransform vector geo_transform = g_input.GetGeoTransform () x_size = g_input.RasterXSize # Raster xsize y_size = g_input.RasterYSize # Raster ysize srs = g_input.GetProjectionRef () # Projection # Need a driver object. By default, we use GeoTIFF if driver == "GTiff": driver = gdal.GetDriverByName ( driver ) dataset_out = driver.Create ( output_name, x_size, y_size, 1, \ gdal.GDT_Float32, ['TFW=YES', \ 'COMPRESS=LZW', 'TILED=YES'] ) else: driver = gdal.GetDriverByName ( driver ) dataset_out = driver.Create ( output_name, x_size, y_size, 1, \ gdal.GDT_Float32 ) dataset_out.SetGeoTransform ( geo_transform ) dataset_out.SetProjection ( srs ) dataset_out.GetRasterBand ( 1 ).WriteArray ( \ raster_data.astype(np.float32) ) dataset_out.GetRasterBand ( 1 ).SetNoDataValue ( float(-999) ) dataset_out = None
mit
Python
cf066fd373f0d12a43bad24db9e645e257617306
add consts
nakagami/pydrda
drda/consts.py
drda/consts.py
############################################################################## # The MIT License (MIT) # # Copyright (c) 2016 Hajime Nakagami # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ############################################################################## DRDA_TYPE_INTEGER = 0x02 DRDA_TYPE_NINTEGER = 0x03 DRDA_TYPE_SMALL = 0x04 DRDA_TYPE_NSMALL = 0x05 DRDA_TYPE_1BYTE_INT = 0x06 DRDA_TYPE_N1BYTE_INT = 0x07 DRDA_TYPE_FLOAT16 = 0x08 DRDA_TYPE_NFLOAT16 = 0x09 DRDA_TYPE_FLOAT8 = 0x0A DRDA_TYPE_NFLOAT8 = 0x0B DRDA_TYPE_FLOAT4 = 0x0C DRDA_TYPE_NFLOAT4 = 0x0D DRDA_TYPE_DECIMAL = 0x0E DRDA_TYPE_NDECIMAL = 0x0F DRDA_TYPE_ZDECIMAL = 0x10 DRDA_TYPE_NZDECIMAL = 0x11 DRDA_TYPE_NUMERIC_CHAR = 0x12 DRDA_TYPE_NNUMERIC_CHAR = 0x13 DRDA_TYPE_RSET_LOC = 0x14 DRDA_TYPE_NRSET_LOC = 0x15 DRDA_TYPE_INTEGER8 = 0x16 DRDA_TYPE_NINTEGER8 = 0x17 DRDA_TYPE_LOBLOC = 0x18 DRDA_TYPE_NLOBLOC = 0x19 DRDA_TYPE_CLOBLOC = 0x1A DRDA_TYPE_NCLOBLOC = 0x1B DRDA_TYPE_DBCSCLOBLOC = 0x1C DRDA_TYPE_NDBCSCLOBLOC = 0x1D DRDA_TYPE_ROWID = 0x1E DRDA_TYPE_NROWID = 0x1F DRDA_TYPE_DATE = 0x20 DRDA_TYPE_NDATE = 0x21 DRDA_TYPE_TIME = 0x22 DRDA_TYPE_NTIME = 0x23 DRDA_TYPE_TIMESTAMP = 0x24 DRDA_TYPE_NTIMESTAMP = 0x25 DRDA_TYPE_FIXBYTE = 0x26 DRDA_TYPE_NFIXBYTE = 0x27 DRDA_TYPE_VARBYTE = 0x28 DRDA_TYPE_NVARBYTE = 0x29 DRDA_TYPE_LONGVARBYTE = 0x2A DRDA_TYPE_NLONGVARBYTE = 0x2B DRDA_TYPE_NTERMBYTE = 0x2C DRDA_TYPE_NNTERMBYTE = 0x2D DRDA_TYPE_CSTR = 0x2E DRDA_TYPE_NCSTR = 0x2F DRDA_TYPE_CHAR = 0x30 DRDA_TYPE_NCHAR = 0x31 DRDA_TYPE_VARCHAR = 0x32 DRDA_TYPE_NVARCHAR = 0x33 DRDA_TYPE_LONG = 0x34 DRDA_TYPE_NLONG = 0x35 DRDA_TYPE_GRAPHIC = 0x36 DRDA_TYPE_NGRAPHIC = 0x37 DRDA_TYPE_VARGRAPH = 0x38 DRDA_TYPE_NVARGRAPH = 0x39 DRDA_TYPE_LONGRAPH = 0x3A DRDA_TYPE_NLONGRAPH = 0x3B DRDA_TYPE_MIX = 0x3C DRDA_TYPE_NMIX = 0x3D DRDA_TYPE_VARMIX = 0x3E DRDA_TYPE_NVARMIX = 0x3F DRDA_TYPE_LONGMIX = 0x40 DRDA_TYPE_NLONGMIX = 0x41 DRDA_TYPE_CSTRMIX = 0x42 DRDA_TYPE_NCSTRMIX = 0x43 DRDA_TYPE_PSCLBYTE = 0x44 DRDA_TYPE_NPSCLBYTE = 0x45 DRDA_TYPE_LSTR = 0x46 DRDA_TYPE_NLSTR = 0x47 DRDA_TYPE_LSTRMIX = 0x48 DRDA_TYPE_NLSTRMIX = 0x49 DRDA_TYPE_SDATALINK = 0x4C DRDA_TYPE_NSDATALINK = 0x4D DRDA_TYPE_MDATALINK = 0x4E DRDA_TYPE_NMDATALINK = 0x4F
mit
Python
542731f7fb3f5d09c4de4340f7ce18b7cbf41172
Create Client.py
Elviond/A4TL
Client.py
Client.py
from Networking import Client client = Client() client.connect('10.42.42.25', 12345).send({'Ordre':'Timelapse', 'Action':["/home/pi/photo3", 24, 30, 0.25, False]}) reponse = client.recv() client.close()
mit
Python
745adf9898e6dc80d37f1a0c3c4361acf76f2feb
Create main.py
ch4rliem4rbles/slack-five
main.py
main.py
import webapp2 import logging import json import utils import re import advanced class show_search_results(utils.BaseHandler): def post(self): #get info about slack post token = self.request.get('token') channel = self.request.get('channel') text = self.request.get('text') user = self.request.get('user_name') user_id = self.request.get('user_id') #verify that the call to app is being made by an authorized slack slash command if token == 'your_token': #extract the search term from the command and build the resulting search link query_name = re.match("[^\s]+", text) if query_name is not None: query_name = image_name.group(0) query_link = "<https://google.com/q?={}".format(query_name) self.response.out.write("".format(query_link)) #call the Slack incoming webhook url = "your_incoming_webhooks_url" payload = json.dumps( {"channel":channel, "username":"Highfive", "text":"".format(query_link)}) result = urlfetch.fetch(url=url, method=urlfetch.POST, payload=payload) app = webapp2.WSGIApplication([ ('/slack-five', query_link, debug=True)])
mit
Python
42753fc71b6a7cbe8697ba0eb053fdbc39c852a1
add test_eval
Akagi201/learning-python,Akagi201/learning-python,Akagi201/learning-python,Akagi201/learning-python,Akagi201/learning-python
misc/test_eval.py
misc/test_eval.py
# eval def main(): dictString = "{'Define1':[[63.3,0.00,0.5,0.3,0.0],[269.3,0.034,1.0,1.0,0.5]," \ "[332.2,0.933,0.2,0.99920654296875,1],[935.0,0.990,0.2,0.1,1.0]]," \ "'Define2':[[63.3,0.00,0.5,0.2,1.0],[269.3,0.034,1.0,0.3,0.5]," \ "[332.2,0.933,0.2, 0.4,0.6],[935.0,0.990,1.0, 0.5,0.0]],}" dict = eval(dictString) print("keys: ", dict.keys()) print("Define1 value ", dict['Define1']) # execfile execfile("test_list.py") if __name__ == '__main__': main()
mit
Python
293f0dde7f329399648317b8d67322604f2e9292
Add window_title_async.py module
tobes/py3status,valdur55/py3status,ultrabug/py3status,hburg1234/py3status,Shir0kamii/py3status,tobes/py3status,alexoneill/py3status,guiniol/py3status,Andrwe/py3status,docwalter/py3status,ultrabug/py3status,valdur55/py3status,ultrabug/py3status,guiniol/py3status,valdur55/py3status,Spirotot/py3status,Andrwe/py3status,vvoland/py3status
py3status/modules/window_title_async.py
py3status/modules/window_title_async.py
""" Display the current window title with async update. Uses asynchronous update via i3 IPC events. Provides instant title update only when it required. Configuration parameters: - format : format of the title, default: "{title}". - empty_title : string that will be shown instead of the title when the title is hidden, default: 500 spaces. - always_show : do not hide the title when it can be already visible (e.g. in tabbed layout), default: False. Requires: - i3ipc (https://github.com/acrisci/i3ipc-python) @author Anon1234 https://github.com/Anon1234 @license BSD """ from threading import Thread import i3ipc class Py3status: format = "{title}" empty_title = " " * 500 always_show = False def __init__(self): self.title = self.empty_title # we are listening to i3 events in a separate thread t = Thread(target=self._loop) t.daemon = True t.start() def _loop(self): def get_title(conn): tree = conn.get_tree() w = tree.find_focused() p = w.parent # dont show window title when the window already has means # to display it if not self.always_show and (w.border == "normal" or (p.layout in ("stacked", "tabbed") and len(p.nodes) > 1)): return self.empty_title else: return w.name def update_title(conn, e): # catch only focused window title updates title_changed = hasattr(e, "container") and e.container.focused # check if we need to update title due to changes # in the workspace layout layout_changed = (hasattr(e, "binding") and ( e.binding.command.startswith("layout") or e.binding.command.startswith("border"))) if title_changed or layout_changed: self.title = get_title(conn) or self.empty_title def clear_title(*args): self.title = self.empty_title conn = i3ipc.Connection() self.title = get_title(conn) # set title on startup # The order of following callbacks is important! # clears the title on empty ws conn.on('workspace::focus', clear_title) # clears the title when the last window on ws was closed conn.on("window::close", clear_title) # listens for events which can trigger the title update conn.on("window::title", update_title) conn.on("window::focus", update_title) conn.on("binding", update_title) conn.main() # run the event loop def window_title(self, i3s_output_list, i3s_config): resp = { 'cached_until': 0, # update ASAP 'full_text': self.format.format(title=self.title), } for option in ('min_width', 'align', 'separator'): try: resp[option] = getattr(self, option) except AttributeError: continue return resp if __name__ == "__main__": """ Test this module by calling it directly. """ from time import sleep x = Py3status() while True: print(x.window_title([], {})) sleep(1)
bsd-3-clause
Python
a9da84352d6ff8b26a8e25ac9d15d5737c84225f
Add problem 12
dimkarakostas/matasano-cryptochallenges
problem_12.py
problem_12.py
from crypto_library import ecb_aes from problem_11 import distinguish_encryption_mode from string import printable ''' from crypto_library import BLOCKSIZE import random ENCRYPTION_KEY = ''.join(random.choice(printable) for _ in range(BLOCKSIZE)) ''' def new_encryption_oracle(adversary_input): ENCRYPTION_KEY = ',y!3<CWn@1?wwF]\x0b' unknown_input = 'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK' return ecb_aes(adversary_input+unknown_input, ENCRYPTION_KEY) def find_blocksize(): adversary_input = '' previous_length = len(new_encryption_oracle(adversary_input)) found_block_change = False while True: adversary_input += '0' current_length = len(new_encryption_oracle(adversary_input)) if current_length > previous_length: if found_block_change: return current_length - previous_length found_block_change = True previous_length = current_length def find_unknown_text_length(blocksize): adversary_input = '' previous_length = len(new_encryption_oracle(adversary_input)) while True: adversary_input += '0' current_length = len(new_encryption_oracle(adversary_input)) if current_length > previous_length: return current_length - len(adversary_input) - blocksize def find_single_ecb_character(blocksize, decrypted, unknown_text_length): input_padding = '0'*(blocksize*(unknown_text_length/blocksize + 1) - len(decrypted) - 1) test_padding = input_padding + decrypted block_position = len(test_padding)/blocksize for test_char in printable: test_character = test_padding + test_char test_character_ciphertext = new_encryption_oracle(test_character) test_blocks = [test_character_ciphertext[i*blocksize:(i+1)*blocksize] for i in range(len(test_character_ciphertext)/blocksize)] ciphertext = new_encryption_oracle(input_padding) cipher_blocks = [ciphertext[i*blocksize:(i+1)*blocksize] for i in range(len(ciphertext)/blocksize)] if test_blocks[block_position] == cipher_blocks[block_position]: return test_char if __name__ == '__main__': blocksize = find_blocksize() unknown_text_length = find_unknown_text_length(blocksize) chosen_input = '0'*(3*blocksize) detection_ciphertext = new_encryption_oracle(chosen_input) encryption_mode = distinguish_encryption_mode(detection_ciphertext) if encryption_mode == 'ecb': decrypted = '' while len(decrypted) < unknown_text_length: decrypted += find_single_ecb_character(blocksize, decrypted, unknown_text_length) print decrypted.decode('base64')
mit
Python
0ecc153d3946258f7daddd48bfc2870cb497b5db
Add IPlugSession interface
usingnamespace/pyramid_pluggable_session,sontek/pyramid_pluggable_session
pyramid_pluggable_session/interfaces.py
pyramid_pluggable_session/interfaces.py
from zope.interface import Interface class IPlugSession(Interface): """ In interface that describes a pluggable session """ def loads(session, request): """ This function given a ``session`` and ``request`` should using the ``session_id`` attribute of the ``session`` This function should return either the opaque session information or None. """ def dumps(session, request, session_data): """ This function given a ``session`` and ``request`` should using the ``_session_id`` attribute of the ``session`` write the session information, with the ``session_id`` being used as a unique identifier, any previously stored session data should overwritten. ``session_data`` is an opaque object, it's contents are a serialised version of the session data. """
isc
Python
a0d8eff20cfd8b60be005e31692af74837ca16f5
test math.ceil() function
xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples,xmementoit/practiseSamples
pythonPractiseSamples/mathExcercises.py
pythonPractiseSamples/mathExcercises.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Damian Ziobro <[email protected]> import unittest import math class TestMathMethods(unittest.TestCase): def setUp(self): self.number = 3.5 def test_ceil(self): self.assertEqual(math.ceil(self.number), 4); if __name__ == "__main__": print ("running unittests for math") unittest.main();
apache-2.0
Python
44130357b98001790547d53b7e1080e79842a058
add group recorded
peruana80/python_training
test_add_group.py
test_add_group.py
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.common.action_chains import ActionChains import time, unittest def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False class test_add_group(unittest.TestCase): def setUp(self): self.wd = WebDriver() self.wd.implicitly_wait(60) def test_test_add_group(self): success = True wd = self.wd wd.get("http://localhost/addressbook/group.php") wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys("admin") wd.find_element_by_id("LoginForm").click() wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys("secret") wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click() wd.find_element_by_name("new").click() wd.find_element_by_name("group_name").click() wd.find_element_by_name("group_name").clear() wd.find_element_by_name("group_name").send_keys("new") wd.find_element_by_name("group_header").click() wd.find_element_by_name("group_header").clear() wd.find_element_by_name("group_header").send_keys("new") wd.find_element_by_name("group_footer").click() wd.find_element_by_name("group_footer").clear() wd.find_element_by_name("group_footer").send_keys("new") wd.find_element_by_name("submit").click() wd.find_element_by_link_text("group page").click() wd.find_element_by_link_text("Logout").click() self.assertTrue(success) def tearDown(self): self.wd.quit() if __name__ == '__main__': unittest.main()
apache-2.0
Python
4569c22d2d0245641e0c2696f798f273405c6bee
Test recorded and exported to the project
spcartman/python_qa
test_add_group.py
test_add_group.py
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.common.action_chains import ActionChains import time, unittest def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False class test_add_group(unittest.TestCase): def setUp(self): self.wd = WebDriver() self.wd.implicitly_wait(60) def test_test_add_group(self): success = True wd = self.wd wd.get("http://localhost/addressbook/") wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys("admin") wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys("secret") wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click() wd.find_element_by_link_text("groups").click() wd.find_element_by_name("new").click() wd.find_element_by_name("group_name").click() wd.find_element_by_name("group_name").clear() wd.find_element_by_name("group_name").send_keys("group_002") wd.find_element_by_name("group_header").click() wd.find_element_by_name("group_header").clear() wd.find_element_by_name("group_header").send_keys("another_header") wd.find_element_by_name("group_footer").click() wd.find_element_by_name("group_footer").clear() wd.find_element_by_name("group_footer").send_keys("another_footer") wd.find_element_by_name("submit").click() wd.find_element_by_link_text("group page").click() wd.find_element_by_link_text("Logout").click() self.assertTrue(success) def tearDown(self): self.wd.quit() if __name__ == '__main__': unittest.main()
mit
Python
1ce8285228c29370ad4230f7968abdd7436ff250
update nth stair
bkpathak/Programs-Collections,bkpathak/HackerRank-Problems,bkpathak/HackerRank-Problems,bkpathak/Programs-Collections
IK/DP/nth_stair.py
IK/DP/nth_stair.py
# http://www.geeksforgeeks.org/count-ways-reach-nth-stair/ # This problem is simpl extension of Fibonacci Number # Case 1 when person can take 1 or 2 steps def fibonacci_number(n): if n <= 1: return n return fibonacci_number(n-1) + fibonacci_number(n-2) def count_ways(s): # ways(1) = fib(2) = 1 # ways(2) = fib(3) = 2 # ways(3) = fib(4) = 3 return fibonacci_number(s+1) # generalized version # if person can take m steps (1,2,3.....m-1,m) def count_ways_util(n,m): if n <= 1: return n res = 0 i = 1 while i <= m and i <= n: res += count_ways_util(n-i,m) i += 1 return res def count_ways_generalize(s,m): return count_ways_util(s+1,m) if __name__ == "__main__": print("Number of ways: ",count_ways_generalize(4,2))
mit
Python
d5a42bd23e7227e041aa3d748765b056e3294a0d
Create infogan.py
kozistr/Awesome-GANs
InfoGAN/infogan.py
InfoGAN/infogan.py
# initial python file
mit
Python
af5c39347863f2804bb1e36cb0bf6f1a049530c2
add 15-26
MagicForest/Python
src/training/Core2/Chapter15RegularExpressions/exercise15_26.py
src/training/Core2/Chapter15RegularExpressions/exercise15_26.py
import re def replace_email(a_string, new_email): return re.sub('\w+@\w+\.\w+', new_email, a_string) if __name__ == '__main__': assert '[email protected] xx [email protected] b' == replace_email('[email protected] xx [email protected] b', '[email protected]') assert 'abb' == replace_email('abb', '[email protected]') print 'all passed.'
apache-2.0
Python
f730a8cfd6700eeedf1cbcc5df8b3b97f918f0fa
Add filterset for tag page, refs #450
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
grouprise/features/tags/filters.py
grouprise/features/tags/filters.py
from django.forms.widgets import CheckboxInput from django_filters import BooleanFilter from django_filters.widgets import BooleanWidget from grouprise.features.associations.filters import ContentFilterSet class TagContentFilterSet(ContentFilterSet): tagged_only = BooleanFilter( label='nur verschlagwortete Beiträge', widget=CheckboxInput, method='filter_tagged_only') def __init__(self, *args, tag=None, **kwargs): self.tag = tag super().__init__(*args, **kwargs) def filter_tagged_only(self, queryset, name, value): if value: queryset = queryset.filter(content__taggeds__tag=self.tag) return queryset
agpl-3.0
Python
42c7db3f9422d38b0d7273ad8f95db8183b69a9c
Add a python version of the lineset_test ... it demonstrates how one has to run eve from python.
sawenzel/root,nilqed/root,lgiommi/root,Duraznos/root,veprbl/root,gganis/root,evgeny-boger/root,Y--/root,mhuwiler/rootauto,beniz/root,olifre/root,Duraznos/root,Y--/root,omazapa/root,gbitzes/root,CristinaCristescu/root,arch1tect0r/root,Duraznos/root,davidlt/root,root-mirror/root,esakellari/root,cxx-hep/root-cern,karies/root,beniz/root,gbitzes/root,perovic/root,simonpf/root,georgtroska/root,dfunke/root,davidlt/root,beniz/root,agarciamontoro/root,karies/root,davidlt/root,veprbl/root,root-mirror/root,zzxuanyuan/root,davidlt/root,root-mirror/root,bbockelm/root,pspe/root,krafczyk/root,root-mirror/root,krafczyk/root,esakellari/my_root_for_test,davidlt/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,mattkretz/root,evgeny-boger/root,agarciamontoro/root,olifre/root,zzxuanyuan/root,BerserkerTroll/root,lgiommi/root,lgiommi/root,bbockelm/root,kirbyherm/root-r-tools,esakellari/root,sirinath/root,agarciamontoro/root,esakellari/root,mkret2/root,nilqed/root,karies/root,omazapa/root-old,zzxuanyuan/root-compressor-dummy,dfunke/root,buuck/root,Duraznos/root,Duraznos/root,ffurano/root5,0x0all/ROOT,sirinath/root,perovic/root,esakellari/my_root_for_test,karies/root,kirbyherm/root-r-tools,smarinac/root,krafczyk/root,esakellari/root,arch1tect0r/root,zzxuanyuan/root,simonpf/root,perovic/root,satyarth934/root,sbinet/cxx-root,strykejern/TTreeReader,esakellari/my_root_for_test,sawenzel/root,dfunke/root,satyarth934/root,jrtomps/root,evgeny-boger/root,satyarth934/root,davidlt/root,BerserkerTroll/root,abhinavmoudgil95/root,omazapa/root-old,sbinet/cxx-root,nilqed/root,BerserkerTroll/root,root-mirror/root,Y--/root,beniz/root,Dr15Jones/root,abhinavmoudgil95/root,Y--/root,sawenzel/root,thomaskeck/root,cxx-hep/root-cern,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,pspe/root,arch1tect0r/root,gbitzes/root,0x0all/ROOT,tc3t/qoot,davidlt/root,olifre/root,gganis/root,tc3t/qoot,nilqed/root,buuck/root,BerserkerTroll/root,mhuwiler/rootauto,olifre/root,bbockelm/root,cxx-hep/root-cern,mhuwiler/rootauto,mattkretz/root,esakellari/my_root_for_test,Y--/root,jrtomps/root,georgtroska/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,gganis/root,esakellari/my_root_for_test,cxx-hep/root-cern,mattkretz/root,CristinaCristescu/root,arch1tect0r/root,root-mirror/root,thomaskeck/root,mattkretz/root,georgtroska/root,veprbl/root,smarinac/root,omazapa/root,omazapa/root-old,BerserkerTroll/root,olifre/root,cxx-hep/root-cern,sirinath/root,satyarth934/root,zzxuanyuan/root,vukasinmilosevic/root,Y--/root,omazapa/root,esakellari/my_root_for_test,gbitzes/root,perovic/root,BerserkerTroll/root,bbockelm/root,buuck/root,smarinac/root,vukasinmilosevic/root,kirbyherm/root-r-tools,zzxuanyuan/root-compressor-dummy,Y--/root,mkret2/root,vukasinmilosevic/root,veprbl/root,satyarth934/root,bbockelm/root,jrtomps/root,krafczyk/root,mkret2/root,smarinac/root,tc3t/qoot,sbinet/cxx-root,gbitzes/root,0x0all/ROOT,strykejern/TTreeReader,vukasinmilosevic/root,nilqed/root,ffurano/root5,tc3t/qoot,arch1tect0r/root,mhuwiler/rootauto,CristinaCristescu/root,sirinath/root,mhuwiler/rootauto,omazapa/root-old,sirinath/root,strykejern/TTreeReader,nilqed/root,simonpf/root,evgeny-boger/root,thomaskeck/root,sawenzel/root,esakellari/my_root_for_test,sawenzel/root,alexschlueter/cern-root,Duraznos/root,CristinaCristescu/root,lgiommi/root,satyarth934/root,satyarth934/root,mhuwiler/rootauto,simonpf/root,abhinavmoudgil95/root,lgiommi/root,pspe/root,karies/root,ffurano/root5,vukasinmilosevic/root,olifre/root,Dr15Jones/root,sawenzel/root,zzxuanyuan/root,alexschlueter/cern-root,alexschlueter/cern-root,omazapa/root,smarinac/root,ffurano/root5,beniz/root,beniz/root,krafczyk/root,root-mirror/root,mkret2/root,abhinavmoudgil95/root,kirbyherm/root-r-tools,pspe/root,perovic/root,beniz/root,beniz/root,abhinavmoudgil95/root,thomaskeck/root,mattkretz/root,esakellari/root,georgtroska/root,gbitzes/root,Y--/root,agarciamontoro/root,smarinac/root,gbitzes/root,lgiommi/root,sawenzel/root,veprbl/root,dfunke/root,arch1tect0r/root,buuck/root,nilqed/root,tc3t/qoot,agarciamontoro/root,evgeny-boger/root,0x0all/ROOT,veprbl/root,sirinath/root,kirbyherm/root-r-tools,nilqed/root,perovic/root,simonpf/root,gganis/root,agarciamontoro/root,karies/root,0x0all/ROOT,sbinet/cxx-root,karies/root,mkret2/root,agarciamontoro/root,BerserkerTroll/root,mkret2/root,sawenzel/root,simonpf/root,karies/root,kirbyherm/root-r-tools,abhinavmoudgil95/root,thomaskeck/root,root-mirror/root,mkret2/root,gganis/root,nilqed/root,simonpf/root,thomaskeck/root,bbockelm/root,jrtomps/root,simonpf/root,olifre/root,mhuwiler/rootauto,abhinavmoudgil95/root,karies/root,agarciamontoro/root,evgeny-boger/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,pspe/root,esakellari/root,Duraznos/root,Dr15Jones/root,olifre/root,dfunke/root,sbinet/cxx-root,sbinet/cxx-root,dfunke/root,buuck/root,davidlt/root,CristinaCristescu/root,jrtomps/root,strykejern/TTreeReader,kirbyherm/root-r-tools,omazapa/root,mkret2/root,arch1tect0r/root,sbinet/cxx-root,pspe/root,vukasinmilosevic/root,abhinavmoudgil95/root,zzxuanyuan/root,evgeny-boger/root,mhuwiler/rootauto,krafczyk/root,esakellari/my_root_for_test,perovic/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,georgtroska/root,arch1tect0r/root,lgiommi/root,vukasinmilosevic/root,omazapa/root-old,vukasinmilosevic/root,dfunke/root,esakellari/root,buuck/root,zzxuanyuan/root,strykejern/TTreeReader,gganis/root,strykejern/TTreeReader,perovic/root,Duraznos/root,bbockelm/root,abhinavmoudgil95/root,ffurano/root5,gbitzes/root,Y--/root,olifre/root,sbinet/cxx-root,karies/root,jrtomps/root,zzxuanyuan/root,lgiommi/root,davidlt/root,dfunke/root,CristinaCristescu/root,omazapa/root-old,karies/root,BerserkerTroll/root,root-mirror/root,jrtomps/root,satyarth934/root,omazapa/root,omazapa/root-old,esakellari/root,strykejern/TTreeReader,davidlt/root,Y--/root,BerserkerTroll/root,sirinath/root,gganis/root,sirinath/root,beniz/root,dfunke/root,lgiommi/root,zzxuanyuan/root,omazapa/root,zzxuanyuan/root,tc3t/qoot,zzxuanyuan/root-compressor-dummy,Y--/root,arch1tect0r/root,satyarth934/root,tc3t/qoot,buuck/root,pspe/root,veprbl/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,georgtroska/root,evgeny-boger/root,krafczyk/root,mhuwiler/rootauto,mattkretz/root,CristinaCristescu/root,Duraznos/root,cxx-hep/root-cern,Dr15Jones/root,krafczyk/root,omazapa/root,0x0all/ROOT,buuck/root,sawenzel/root,vukasinmilosevic/root,Dr15Jones/root,thomaskeck/root,omazapa/root,mattkretz/root,alexschlueter/cern-root,mattkretz/root,sbinet/cxx-root,alexschlueter/cern-root,jrtomps/root,esakellari/root,evgeny-boger/root,0x0all/ROOT,esakellari/root,nilqed/root,gganis/root,alexschlueter/cern-root,omazapa/root-old,bbockelm/root,CristinaCristescu/root,pspe/root,gganis/root,tc3t/qoot,gbitzes/root,BerserkerTroll/root,buuck/root,simonpf/root,dfunke/root,esakellari/my_root_for_test,pspe/root,esakellari/my_root_for_test,arch1tect0r/root,tc3t/qoot,bbockelm/root,cxx-hep/root-cern,thomaskeck/root,buuck/root,sirinath/root,beniz/root,mattkretz/root,abhinavmoudgil95/root,esakellari/root,simonpf/root,zzxuanyuan/root,georgtroska/root,mhuwiler/rootauto,cxx-hep/root-cern,gganis/root,thomaskeck/root,sawenzel/root,mkret2/root,gganis/root,0x0all/ROOT,zzxuanyuan/root,sirinath/root,dfunke/root,nilqed/root,mkret2/root,BerserkerTroll/root,buuck/root,simonpf/root,agarciamontoro/root,smarinac/root,olifre/root,CristinaCristescu/root,mhuwiler/rootauto,georgtroska/root,satyarth934/root,omazapa/root,alexschlueter/cern-root,veprbl/root,zzxuanyuan/root-compressor-dummy,lgiommi/root,georgtroska/root,sbinet/cxx-root,smarinac/root,jrtomps/root,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,ffurano/root5,bbockelm/root,veprbl/root,gbitzes/root,krafczyk/root,smarinac/root,agarciamontoro/root,perovic/root,perovic/root,vukasinmilosevic/root,abhinavmoudgil95/root,omazapa/root-old,mattkretz/root,jrtomps/root,jrtomps/root,sawenzel/root,sirinath/root,veprbl/root,georgtroska/root,veprbl/root,perovic/root,root-mirror/root,lgiommi/root,pspe/root,pspe/root,thomaskeck/root,Duraznos/root,evgeny-boger/root,CristinaCristescu/root,omazapa/root-old,davidlt/root,root-mirror/root,omazapa/root-old,ffurano/root5,evgeny-boger/root,mkret2/root,gbitzes/root,omazapa/root,beniz/root,krafczyk/root,satyarth934/root,smarinac/root,Dr15Jones/root,mattkretz/root,olifre/root,tc3t/qoot
tutorials/eve/lineset_test.py
tutorials/eve/lineset_test.py
## Translated from 'lineset_test.C'. ## Run as: python -i lineset_test.py import ROOT ROOT.PyConfig.GUIThreadScheduleOnce += [ ROOT.TEveManager.Create ] def lineset_test(nlines = 40, nmarkers = 4): r = ROOT.TRandom(0) s = 100 ls = ROOT.TEveStraightLineSet() for i in range(nlines): ls.AddLine( r.Uniform(-s,s), r.Uniform(-s,s), r.Uniform(-s,s) , r.Uniform(-s,s), r.Uniform(-s,s), r.Uniform(-s,s)) nm = int(nmarkers*r.Rndm()) for m in range(nm): ls.AddMarker( i, r.Rndm() ) ls.SetMarkerSize(1.5) ls.SetMarkerStyle(4) ROOT.gEve.AddElement(ls) ROOT.gEve.Redraw3D() return ls if __name__=='__main__': ROOT.PyGUIThread.finishSchedule() lineset_test()
lgpl-2.1
Python
73f3fa2657485c4fce812f67c3430be553307413
Include fixtures for setting up the database
mattrobenolt/warehouse,mattrobenolt/warehouse,mattrobenolt/warehouse,robhudson/warehouse,robhudson/warehouse,techtonik/warehouse,techtonik/warehouse
tests/conftest.py
tests/conftest.py
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import random import string import alembic.config import alembic.command import pytest import sqlalchemy import sqlalchemy.pool from six.moves import urllib_parse def pytest_addoption(parser): group = parser.getgroup("warehouse") group._addoption( "--database-url", default=None, help="The url to connect when creating the test database.", ) parser.addini( "database_url", "The url to connect when creating the test database.", ) @pytest.fixture(scope="session") def _database(request): from warehouse.application import Warehouse def _get_name(): tag = "".join( random.choice(string.ascii_lowercase + string.digits) for x in range(7) ) return "warehousetest_{}".format(tag) def _check_name(engine, name): with engine.connect() as conn: results = conn.execute( "SELECT datname FROM pg_database WHERE datistemplate = false" ) return name not in [r[0] for r in results] database_url_ini = request.config.getini("database_url") database_url_option = request.config.getvalue("database_url") if not database_url_ini and not database_url_option: pytest.skip("No database provided") # Configure our engine so that we can create a database database_url = database_url_option or database_url_ini engine = sqlalchemy.create_engine( database_url, isolation_level="AUTOCOMMIT", poolclass=sqlalchemy.pool.NullPool ) # Make a random database name that doesn't exist name = _get_name() while not _check_name(engine, name): name = _get_name() # Create the database with engine.connect() as conn: conn.execute("CREATE DATABASE {}".format(name)) # Create a new database_url with the name replaced parsed = urllib_parse.urlparse(database_url) test_database_url = urllib_parse.urlunparse( parsed[:2] + ("/" + name,) + parsed[3:] ) # Create the database schema test_engine = sqlalchemy.create_engine( test_database_url, poolclass=sqlalchemy.pool.NullPool, ) app = Warehouse.from_yaml( override={"database": {"url": test_database_url}}, engine=test_engine, ) with app.engine.connect() as conn: conn.execute("CREATE EXTENSION IF NOT EXISTS citext") alembic_cfg = alembic.config.Config() alembic_cfg.set_main_option( "script_location", app.config.database.migrations, ) alembic_cfg.set_main_option("url", app.config.database.url) alembic.command.upgrade(alembic_cfg, "head") test_engine.dispose() # Drop the database at the end of the session def _drop_database(): with engine.connect() as conn: # Terminate all open connections to the test database conn.execute( """SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = %s """, [name], ) conn.execute("DROP DATABASE {}".format(name)) request.addfinalizer(_drop_database) return test_database_url @pytest.fixture def database(request, _database): # Create our engine engine = sqlalchemy.create_engine( _database, poolclass=sqlalchemy.pool.AssertionPool, ) # Get a connection to the database connection = engine.connect() connection.connect = lambda: connection # Start a transaction transaction = connection.begin() # Register a finalizer that will rollback the transaction and close the # connections def _end(): transaction.rollback() connection.close() engine.dispose() request.addfinalizer(_end) return connection
apache-2.0
Python
f681f6ac7764b0944434c69febb2b3b778f2aad7
add 2
weixsong/algorithm,weixsong/algorithm,weixsong/algorithm
leetcode/2.py
leetcode/2.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 == None: return l2 if l2 == None: return l1 head = res = ListNode(0) carrier = 0 while l1 != None and l2 != None: val = l1.val + l2.val + carrier carrier = val / 10 val = val % 10 head.next = ListNode(val) head = head.next l1 = l1.next l2 = l2.next while l1 != None: val = l1.val + carrier carrier = val / 10 val = val % 10 head.next = ListNode(val) head = head.next l1 = l1.next while l2 != None: val = l2.val + carrier carrier = val / 10 val = val % 10 head.next = ListNode(val) head = head.next l2 = l2.next if carrier != 0: head.next = ListNode(carrier) return res.next
mit
Python
45686564547ccf1f40516d2ecbcf550bb904d59c
Create lc1032.py
FiveEye/ProblemSet,FiveEye/ProblemSet
LeetCode/lc1032.py
LeetCode/lc1032.py
import queue class Node: def __init__(self, s=''): self.s = s self.end = False self.fail = None self.children = None def get(self, index): if self.children == None: return None return self.children[index] def set(self, index, node): if self.children == None: self.children = [None for _ in range(26)] self.children[index] = node def add(self, index): if self.children == None: self.children = [None for _ in range(26)] if self.children[index] == None: self.children[index] = Node(self.s + chr(ord('a') + index)) return self.children[index] def next(self, index): p = self while p.get(index) == None: #print("fail", p, p.fail) p = p.fail #print(p, p.get(index)) return p.get(index) def buildFail(root): q = queue.Queue() q.put(root) while not q.empty(): node = q.get() #print("node", node.s) if node.children == None: continue for i in range(26): cnode = node.get(i) if cnode == None: continue #print("cnode:", cnode.s) if node == root: cnode.fail = root else: p = node.fail while p != None: if p.get(i) == None: p = p.fail else: break if p == None: cnode.fail = root else: cnode.fail = p.get(i) #print("cnode fail:", cnode.s, cnode.fail.s) if cnode.end == False and cnode.fail.end == True: cnode.end = True q.put(cnode) for i in range(26): if root.get(i) == None: root.set(i, root) root.fail = root def c2i(c): return ord(c) - ord('a') class StreamChecker: def __init__(self, words: List[str]): self.words = words root = Node() for i in range(len(words)): p = root for j in range(len(words[i])): p = p.add(c2i(words[i][j])) p.end = True #print(root) buildFail(root) self.cur = root def query(self, letter: str) -> bool: #print('cur', self.cur, letter) self.cur = self.cur.next(c2i(letter)) #print("end", self.cur.end) return self.cur.end # Your StreamChecker object will be instantiated and called as such: # obj = StreamChecker(words) # param_1 = obj.query(letter)
mit
Python
2c2d594b7d8d5d74732e30c46859779b88621baa
Create __init__.py
TryCatchHCF/DumpsterFire
FireModules/__init__.py
FireModules/__init__.py
mit
Python
328274b6a938667326dbd435e7020c619cd80d3d
Add EmojiUtils.py
yaoms/EmojiCodec
EmojiUtils.py
EmojiUtils.py
# coding=utf-8 # 2015-11-19 # yaoms # emoji 表情符号转义 """ emoji 表情 编码/解码 类 encode_string_emoji(string) decode_string_emoji(string) """ import re def __is_normal_char(c): """ 判断字符是不是普通字符, 非普通字符, 认定为 emoji 字符 :param c: :return: 普通字符 True, Emoji 字符 False """ i = ord(c) return ( i == 0x0 or i == 0x9 or i == 0xA or i == 0xD or (i >= 0x20 and i <= 0xD7FF) or (i >= 0xE000 and i <= 0xFFFD) or (i >= 0x10000 and i <= 0x10FFFF) ) def __emoji_encode(c): """ Emoji 字符编码 :param c: :return: Emoji 代码 """ if __is_normal_char(c): return c else: return "[emj]%s[/emj]" % format(ord(c), 'x') def __emoji_decode(code): """ 解码 Emoji 代码 :param code: :return: Emoji 字符 """ m = re.match(r"\[emj\]([a-fA-F0-9]+)\[/emj\]", code) if m: h = m.group(1) return unichr(int(h, 16)) def encode_string_emoji(string): """ 遍历并转换其中的 Emoji 字符 :param string: :return: Emoji 代码字符串 """ return "".join([__emoji_encode(c) for c in string]) def decode_string_emoji(string): """ 解码 Emoji 代码 字符串 :param string: :return: 含有 Emoji 字符的字符串 """ p = re.compile(r"\[emj\][a-fA-F0-9]+\[/emj\]") new_string = "" n_start = 0 for m in p.finditer(string): new_string += string[n_start:m.start()] + \ __emoji_decode(string[m.start():m.end()]) n_start = m.end() if n_start < len(string): new_string += string[n_start:] return new_string if __name__ == '__main__': __string_raw = open("/tmp/emoji.txt").read().decode("utf-8") print __string_raw __s1 = encode_string_emoji(__string_raw) print __s1 __s2 = decode_string_emoji(__s1) print __s2
apache-2.0
Python
54a10f78a6c71d88e1c2441bb636e6b636f74613
add unit test
scottsilverlabs/raspberrystem,scottsilverlabs/raspberrystem,scottsilverlabs/raspberrystem,scottsilverlabs/raspberrystem
rstem/led2/test_unittest.py
rstem/led2/test_unittest.py
#!/usr/bin/python3 import unittest import os from rstem import led2 # TODO: single setup for all testcases???? # TODO: make hardware versions that you can optionally skip if __name__ == '__main__': unittest.main() def query(question): ret = int(input(question + " [yes=1,no=0]: ")) if ret == 1: return True elif ret == 0: return False else: raise ValueError("Please only provide 1 or 0. Thank You!") class PrivateFunctions(unittest.TestCase): def test_valid_color(self): for i in range(16): self.assertTrue(led2._valid_color(i)) self.assertTrue(led2._valid_color(hex(i)[2:])) self.assertTrue(led2._valid_color('-')) self.assertFalse(led2._valid_color(17)) self.assertFalse(led2._valid_color(-1)) # random invalid characters self.assertFalse(led2._valid_color('j')) self.assertFalse(led2._valid_color('%')) self.assertFalse(led2._valid_color('10')) #TODO : should we allow none hex versions? def test_convert_color(self): self.assertRaises(ValueError, led2._convert_color('J')) # FIXME: syntax correct? for i in range(16): self.assertEquals(led2._convert_color(hex(i)[2:]), i) self.assertEquals(led2._convert_color(i), i) class PrimativeFunctions(unittest.TestCase): def setUp(self): led2.initGrid(1,2) def tearDown(self): led2.close() def test_point(self): for y in range(8): for x in range(16): # test without a color self.assertEquals(led2.point(x,y), 1) self.assertEquals(led2.point((x,y)), 1) # test with all the colors for color in range(17): self.assertEquals(led2.point(x,y), 1) self.assertEquals(led2.point((x,y)), 1) self.assertEquals(led2.show(), 1) self.assertTrue(query("Is the entire matrix at full brightness?")) def test_line(self): self.assertEquals(led2.point((0,0),(15,7)), 1) self.assertEquals(led2.show(), 1) self.assertTrue(query("Is there a line from (0,0) to (15,7)?")) class TestingSprites(unittest.TestCase): def setUp(self): led2.initGrid(1,2) def tearDown(self): led2.close() def test_init_sprite(self): if font_path is None: # if none, set up default font location this_dir, this_filename = os.path.split(__file__) self.assertEquals(led2.sprite(this_dir + "/test_sprite"), 1) self.assertEquals(led2.show(), 1) self.assertTrue(query("Do you see the test pattern on the left led matrix?")) self.assertEquals(led2.fill(0), 1) self.assertEquals(led2.show(), 1) self.assertFalse(query("What about now?")) def test_text(self): self.assertNotEquals(led2.text("jon"), 0) self.assertEquals(led2.show(), 1) self.assertTrue(query("Is 'jon' displayed with large font?"))
apache-2.0
Python
f0587e44be1c7f85dbbf54e1d6c47458a4960d7c
Create date_time.py
cturko/Pyrus
date_time.py
date_time.py
#!/usr/bin/env python # -*_ coding: utf-8 -*- import datetime import sys def main(): now = datetime.datetime.now() while True: user_request = input("\nCurrent [time, day, date]: ") if user_request == "quit": sys.exit() if user_request == "time": second = str(now.second) time_request = (str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)) print("\nIt is: " + time_request) if user_request == "day": day_request = str(now.strftime("%A")) print("\nIt is " + day_request) if user_request == "date": date_request = (str(now.year) + "-" + str(now.month) + "-" + str(now.day)) print("\nIt is: " + date_request) if __name__ == '__main__': main()
mit
Python
c15f8805d3ce5eab9f46dc24a6845ce27b117ac3
Add TeamTest
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
dbaas/account/tests/test_team.py
dbaas/account/tests/test_team.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.test import TestCase from django.db import IntegrityError from . import factory from ..models import Team from drivers import base import logging LOG = logging.getLogger(__name__) class TeamTest(TestCase): def setUp(self): self.new_team = factory.TeamFactory() def test_create_new_team(self): """ Test new Team creation """ self.assertTrue(self.new_team.pk) def test_cant_create_a_new_user(self): self.team = Team() self.team.name = "Team1" self.team.role_id = factory.RoleFactory().pk self.assertFalse(self.team.save())
bsd-3-clause
Python
264863c1a8d60dd35babec22470626d13ebf3e66
Remove unused import.t
sidja/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,megcunningham/django-debug-toolbar,megcunningham/django-debug-toolbar,jazzband/django-debug-toolbar,stored/django-debug-toolbar,spookylukey/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,peap/django-debug-toolbar,Endika/django-debug-toolbar,calvinpy/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,peap/django-debug-toolbar,stored/django-debug-toolbar,spookylukey/django-debug-toolbar,Endika/django-debug-toolbar,tim-schilling/django-debug-toolbar,megcunningham/django-debug-toolbar,guilhermetavares/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,seperman/django-debug-toolbar,calvinpy/django-debug-toolbar,guilhermetavares/django-debug-toolbar,seperman/django-debug-toolbar,sidja/django-debug-toolbar,barseghyanartur/django-debug-toolbar,jazzband/django-debug-toolbar,Endika/django-debug-toolbar,sidja/django-debug-toolbar,ivelum/django-debug-toolbar,pevzi/django-debug-toolbar,peap/django-debug-toolbar,jazzband/django-debug-toolbar,pevzi/django-debug-toolbar,tim-schilling/django-debug-toolbar,guilhermetavares/django-debug-toolbar,tim-schilling/django-debug-toolbar,stored/django-debug-toolbar,ivelum/django-debug-toolbar,pevzi/django-debug-toolbar,seperman/django-debug-toolbar,barseghyanartur/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,barseghyanartur/django-debug-toolbar,calvinpy/django-debug-toolbar,ivelum/django-debug-toolbar,spookylukey/django-debug-toolbar
debug_toolbar/panels/__init__.py
debug_toolbar/panels/__init__.py
from __future__ import absolute_import, unicode_literals import warnings from django.template.loader import render_to_string class Panel(object): """ Base class for panels. """ # name = 'Base' # template = 'debug_toolbar/panels/base.html' # If content returns something, set to True in subclass has_content = False # We'll maintain a local context instance so we can expose our template # context variables to panels which need them: context = {} # Panel methods def __init__(self, toolbar, context={}): self.toolbar = toolbar self.context.update(context) def content(self): if self.has_content: context = self.context.copy() context.update(self.get_stats()) return render_to_string(self.template, context) @property def panel_id(self): return self.__class__.__name__ @property def enabled(self): return self.toolbar.request.COOKIES.get('djdt' + self.panel_id, 'on') == 'on' # URLs for panel-specific views @classmethod def get_urls(cls): return [] # Titles and subtitles def nav_title(self): """Title showing in sidebar""" raise NotImplementedError def nav_subtitle(self): """Subtitle showing under title in sidebar""" return '' def title(self): """Title showing in panel""" raise NotImplementedError # Enable and disable (expensive) instrumentation, must be idempotent def enable_instrumentation(self): pass def disable_instrumentation(self): pass # Store and retrieve stats (shared between panels for no good reason) def record_stats(self, stats): self.toolbar.stats.setdefault(self.panel_id, {}).update(stats) def get_stats(self): return self.toolbar.stats.get(self.panel_id, {}) # Standard middleware methods def process_request(self, request): pass def process_view(self, request, view_func, view_args, view_kwargs): pass def process_response(self, request, response): pass # Backward-compatibility for 1.0, remove in 2.0. class DebugPanel(Panel): def __init__(self, *args, **kwargs): warnings.warn("DebugPanel was renamed to Panel.", DeprecationWarning) super(DebugPanel, self).__init__(*args, **kwargs)
from __future__ import absolute_import, unicode_literals import warnings from django.template.defaultfilters import slugify from django.template.loader import render_to_string class Panel(object): """ Base class for panels. """ # name = 'Base' # template = 'debug_toolbar/panels/base.html' # If content returns something, set to True in subclass has_content = False # We'll maintain a local context instance so we can expose our template # context variables to panels which need them: context = {} # Panel methods def __init__(self, toolbar, context={}): self.toolbar = toolbar self.context.update(context) def content(self): if self.has_content: context = self.context.copy() context.update(self.get_stats()) return render_to_string(self.template, context) @property def panel_id(self): return self.__class__.__name__ @property def enabled(self): return self.toolbar.request.COOKIES.get('djdt' + self.panel_id, 'on') == 'on' # URLs for panel-specific views @classmethod def get_urls(cls): return [] # Titles and subtitles def nav_title(self): """Title showing in sidebar""" raise NotImplementedError def nav_subtitle(self): """Subtitle showing under title in sidebar""" return '' def title(self): """Title showing in panel""" raise NotImplementedError # Enable and disable (expensive) instrumentation, must be idempotent def enable_instrumentation(self): pass def disable_instrumentation(self): pass # Store and retrieve stats (shared between panels for no good reason) def record_stats(self, stats): self.toolbar.stats.setdefault(self.panel_id, {}).update(stats) def get_stats(self): return self.toolbar.stats.get(self.panel_id, {}) # Standard middleware methods def process_request(self, request): pass def process_view(self, request, view_func, view_args, view_kwargs): pass def process_response(self, request, response): pass # Backward-compatibility for 1.0, remove in 2.0. class DebugPanel(Panel): def __init__(self, *args, **kwargs): warnings.warn("DebugPanel was renamed to Panel.", DeprecationWarning) super(DebugPanel, self).__init__(*args, **kwargs)
bsd-3-clause
Python
4bfd69bc49b17e7844077949560bd6259ea33e9b
test the root scrubadub api
datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub
tests/test_api.py
tests/test_api.py
import unittest import scrubadub class APITestCase(unittest.TestCase): def test_clean(self): """Test the top level clean api""" self.assertEqual( scrubadub.clean("This is a test message for [email protected]"), "This is a test message for {{EMAIL}}", ) def test_clean_docuemnts(self): """Test the top level clean_docuemnts api""" self.assertEqual( scrubadub.clean_documents( { "first.txt": "This is a test message for [email protected]", "second.txt": "Hello Jane I am Tom.", } ), { "first.txt": "This is a test message for {{EMAIL}}", "second.txt": "Hello {{NAME}} I am {{NAME}}.", } ) def test_list_filth(self): """Test the top level list_filth api""" filths = scrubadub.list_filth("This is a test message for [email protected]") self.assertEqual( filths, [scrubadub.filth.EmailFilth(text='[email protected]', detector_name='email', beg=27, end=46)], ) def test_list_filth_docuemnts(self): """Test the top level list_filth_docuemnts api""" filths = scrubadub.list_filth_documents( { "first.txt": "This is a test message for [email protected]", "second.txt": "Hello Jane I am Tom.", } ) print(filths) self.assertEqual( filths, [ scrubadub.filth.EmailFilth(text='[email protected]', document_name='first.txt', detector_name='email', beg=27, end=46), scrubadub.filth.NameFilth(text='Jane', document_name='second.txt', detector_name='name', beg=6, end=10), scrubadub.filth.NameFilth(text='Tom', document_name='second.txt', detector_name='name', beg=16, end=19) ] )
mit
Python
cd906789b4ed339542722c04dd09f8aca04fd7ff
add missing revision
crowdresearch/daemo,crowdresearch/crowdsource-platform,crowdresearch/daemo,crowdresearch/daemo,crowdresearch/daemo,crowdresearch/crowdsource-platform,crowdresearch/crowdsource-platform,crowdresearch/crowdsource-platform
crowdsourcing/migrations/0170_task_price.py
crowdsourcing/migrations/0170_task_price.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-05-24 00:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crowdsourcing', '0169_auto_20170524_0002'), ] operations = [ migrations.AddField( model_name='task', name='price', field=models.FloatField(null=True), ), ]
mit
Python
369dff642883ded68eca98754ce81369634da94d
Add box tests
willmcgugan/rich
tests/test_box.py
tests/test_box.py
import pytest from rich.box import ASCII, DOUBLE, ROUNDED, HEAVY def test_str(): assert str(ASCII) == "+--+\n| ||\n|-+|\n| ||\n|-+|\n|-+|\n| ||\n+--+\n" def test_repr(): assert repr(ASCII) == "Box(...)" def test_get_top(): top = HEAVY.get_top(widths=[1, 2]) assert top == "┏━┳━━┓" def test_get_row(): head_row = DOUBLE.get_row(widths=[3, 2, 1], level="head") assert head_row == "╠═══╬══╬═╣" row = ASCII.get_row(widths=[1, 2, 3], level="row") assert row == "|-+--+---|" foot_row = ROUNDED.get_row(widths=[2, 1, 3], level="foot") assert foot_row == "├──┼─┼───┤" with pytest.raises(ValueError): ROUNDED.get_row(widths=[1, 2, 3], level="FOO") def test_get_bottom(): bottom = HEAVY.get_bottom(widths=[1, 2, 3]) assert bottom == "┗━┻━━┻━━━┛"
mit
Python
dbaad481ab9ddbdccd4430765e3eee0d0433fbd8
Create doc_check.py
kawaiigamer/py_parsers
doc_check.py
doc_check.py
import requests,json,ctypes,time tasks = [ # speciality_id, clinic_id, name '' - for any name, description (40,279,'','Невролог'), (2122,314,'Гусаров','Дерматолог'), ] h = { 'Host': 'gorzdrav.spb.ru', 'Connection': 'keep-alive', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36', 'Sec-Fetch-Mode': 'cors', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Origin': 'https://gorzdrav.spb.ru', 'Sec-Fetch-Site': 'same-origin', 'Referer': 'https://gorzdrav.spb.ru/signup/free/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'ru-RU,ru;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6'} def doc_check(): for task in tasks: r = requests.post("https://gorzdrav.spb.ru/api/doctor_list/", data="speciality_form-speciality_id="+str(task[0])+"&speciality_form-clinic_id=+"+str(task[1])+"&speciality_form-patient_id=&speciality_form-history_id=", headers=h) resp = json.loads(r.text) for doc in resp['response']: if doc['CountFreeTicket'] is not 0 and task[2] in doc['Name']: ctypes.windll.user32.MessageBoxW(0, "New ticket avalible!\n"+task[3]+" match: " + task[2], time.ctime(), 4096) if task[2] is '': break while True: doc_check() time.sleep(65)
unlicense
Python
8eec6e7596e8a5bd8159753be2aeaaffb53f613b
Add Python version
delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL,delight-im/ShortURL
Python/shorturl.py
Python/shorturl.py
class ShortURL: """ ShortURL: Bijective conversion between natural numbers (IDs) and short strings ShortURL.encode() takes an ID and turns it into a short string ShortURL.decode() takes a short string and turns it into an ID Features: + large alphabet (51 chars) and thus very short resulting strings + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') + unambiguous (removed 'I', 'l', '1', 'O' and '0') Example output: 123456789 <=> pgK8p Source: https://github.com/delight-im/ShortURL (Apache License 2.0) """ _alphabet = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_' _base = len(_alphabet) def encode(self, number): string = '' while(number > 0): string = self._alphabet[number % self._base] + string number //= self._base return string def decode(self, string): number = 0 for char in string: number = number * self._base + self._alphabet.index(char) return number
mit
Python
7a5ca2f63dab36664ace637b713d7772870a800a
Create make-fingerprint.py
tfukui95/tor-experiment,tfukui95/tor-experiment
make-fingerprint.py
make-fingerprint.py
mit
Python
cd7187dc916ebbd49a324f1f43b24fbb44e9c9dc
Create afstand_sensor.py
marcwagner/pi-robot,marcwagner/pi-robot,marcwagner/pi-robot,marcwagner/pi-robot,marcwagner/pi-robot
afstand_sensor.py
afstand_sensor.py
import gpiozero from time import sleep sensor = gpiozero.DistanceSensor(echo=18,trigger=17,max_distance=2, threshold_distance=0.5) led = gpiozero.LED(22) while True: afstand = round(sensor.distance*100) print('obstakel op', afstand, 'cm') if sensor.in_range: led.on() sleep(1) led.off()
mit
Python
f1bda6deeb97c50a5606bea59d1684d6d96b10b4
Create api_call.py
tme-dev/TME-API,tme-dev/TME-API,tme-dev/TME-API
PYTHON/api_call.py
PYTHON/api_call.py
def product_import_tme(request): # /product/product_import_tme/ token = '<your's token(Anonymous key:)>' app_secret = '<Application secret>' params = { 'SymbolList[0]': '1N4007', 'Country': 'PL', 'Currency': 'PLN', 'Language': 'PL', } response = api_call('Products/GetPrices', params, token, app_secret, True); response = json.loads(response) print response def api_call(action, params, token, app_secret, show_header=False): api_url = u'https://api.tme.eu/' + action + '.json'; params['Token'] = token; params = collections.OrderedDict(sorted(params.items())) encoded_params = urllib.urlencode(params, '') signature_base = 'POST' + '&' + urllib.quote(api_url, '') + '&' + urllib.quote(encoded_params, '') api_signature = base64.encodestring(hmac.new(app_secret, signature_base, hashlib.sha1).digest()).rstrip() params['ApiSignature'] = api_signature opts = {'http' : { 'method' : 'POST', 'header' : 'Content-type: application/x-www-form-urlencoded', 'content' : urllib.urlencode(params) } } http_header = { "Content-type": "application/x-www-form-urlencoded", } # create your HTTP request req = urllib2.Request(api_url, urllib.urlencode(params), http_header) # submit your request res = urllib2.urlopen(req) html = res.read() return html
mit
Python
1166ef7520ee26836402f028cb52ed95db7173e6
Add CTC_new_refund_limited_all_payroll migration file
OpenSourcePolicyCenter/PolicyBrain,OpenSourcePolicyCenter/PolicyBrain,OpenSourcePolicyCenter/PolicyBrain,OpenSourcePolicyCenter/webapp-public,OpenSourcePolicyCenter/webapp-public,OpenSourcePolicyCenter/webapp-public,OpenSourcePolicyCenter/webapp-public,OpenSourcePolicyCenter/PolicyBrain
webapp/apps/taxbrain/migrations/0058_taxsaveinputs_ctc_new_refund_limited_all_payroll.py
webapp/apps/taxbrain/migrations/0058_taxsaveinputs_ctc_new_refund_limited_all_payroll.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('taxbrain', '0057_jsonreformtaxcalculator_errors_warnings_text'), ] operations = [ migrations.AddField( model_name='taxsaveinputs', name='CTC_new_refund_limited_all_payroll', field=models.CharField(default=b'False', max_length=50, null=True, blank=True), ), ]
mit
Python
55d9610f519713b889ffb68daa3c72ef6c349d3d
Add ExportPPMs.py script.
adobe-type-tools/fontlab-scripts,moyogo/fontlab-scripts
TrueType/ExportPPMs.py
TrueType/ExportPPMs.py
#FLM: Export PPMs """ This script will write (or overwrite) a 'ppms' file in the same directory as the opened VFB file. This 'ppms' file contains the TrueType stem values and the ppm values at which the pixel jumps occur. These values can later be edited as the 'ppms' file is used as part of the conversion process. """ import os from FL import fl kPPMsFileName = "ppms" def collectPPMs(): ppmsList = ["#Name\tWidth\tppm2\tppm3\tppm4\tppm5\tppm6\n"] for x in fl.font.ttinfo.hstem_data: hstem = '%s\t%d\t%d\t%d\t%d\t%d\t%d\n' % ( x.name, x.width, x.ppm2, x.ppm3, x.ppm4, x.ppm5, x.ppm6) ppmsList.append(hstem) for y in fl.font.ttinfo.vstem_data: vstem = '%s\t%d\t%d\t%d\t%d\t%d\t%d\n' % ( y.name, y.width, y.ppm2, y.ppm3, y.ppm4, y.ppm5, y.ppm6) ppmsList.append(vstem) return ppmsList def writePPMsFile(content): # path to the folder where the font is contained and the font's file name: folderPath, fontFileName = os.path.split(fl.font.file_name) filePath = os.path.join(folderPath, kPPMsFileName) outfile = open(filePath, 'w') outfile.writelines(content) outfile.close() def run(): if len(fl): if (fl.font.file_name is None): print "ERROR: You must save the VFB first." return if len(fl.font.ttinfo.hstem_data): ppmsList = collectPPMs() writePPMsFile(ppmsList) print "Done!" else: print "ERROR: The font has no TT stems data." else: print "ERROR: No font opened." if __name__ == "__main__": run()
mit
Python
5aff575cec6ddb10cba2e52ab841ec2197a0e172
Add SignalTimeout context manager
MatthewCox/PyMoronBot,DesertBot/DesertBot
Utils/SignalTimeout.py
Utils/SignalTimeout.py
# Taken from https://gist.github.com/ekimekim/b01158dc36c6e2155046684511595d57 import os import signal import subprocess class Timeout(Exception): """This is raised when a timeout occurs""" class SignalTimeout(object): """Context manager that raises a Timeout if the inner block takes too long. Will even interrupt hard loops in C by raising from an OS signal.""" def __init__(self, timeout, signal=signal.SIGUSR1, to_raise=Timeout): self.timeout = float(timeout) self.signal = signal self.to_raise = to_raise self.old_handler = None self.proc = None def __enter__(self): self.old_handler = signal.signal(self.signal, self._on_signal) self.proc = subprocess.Popen('sleep {timeout} && kill -{signal} {pid}'.format( timeout = self.timeout, signal = self.signal, pid = os.getpid(), ), shell = True, ) def __exit__(self, *exc_info): if self.proc.poll() is None: self.proc.kill() my_handler = signal.signal(self.signal, self.old_handler) assert my_handler == self._on_signal, "someone else has been fiddling with our signal handler?" def _on_signal(self, signum, frame): if self.old_handler: self.old_handler(signum, frame) raise self.to_raise
mit
Python
e18ee4aacd42ec28b2d54437f61d592b1cfaf594
Create national_user_data_pull.py
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
custom/icds_reports/management/commands/national_user_data_pull.py
custom/icds_reports/management/commands/national_user_data_pull.py
import csv from django.core.management.base import BaseCommand from corehq.apps.reports.util import get_all_users_by_domain from custom.icds_reports.const import INDIA_TIMEZONE from custom.icds_reports.models import ICDSAuditEntryRecord from django.db.models import Max class Command(BaseCommand): help = "Custom data pull" def convert_to_ist(self, date): if date is None: return 'N/A' date = date.astimezone(INDIA_TIMEZONE) date_formatted = date.strftime(date, "%d/%m/%Y, %I:%M %p") return date_formatted def handle(self, *args, **options): users = get_all_users_by_domain('icds-cas') usernames = [] for user in users: if user.has_permission('icds-cas', 'access_all_locations'): usernames.append(user.username) usage_data = ICDSAuditEntryRecord.objects.filter(username__in=usernames).values('username').annotate(time=Max('time_of_use')) headers = ["S.No", "username", "time"] count = 1 rows = [headers] usernames_usage = [] for usage in usage_data: row_data = [ count, usage.username, self.convert_to_ist(usage.time) ] usernames_usage.append(usage.username) rows.append(row_data) count = count + 1 for user in usernames: if user not in usernames_usage: row_data = [ count, user, "N/A" ] rows.append(row_data) count = count + 1 fout = open('/home/cchq/National_users_data.csv', 'w') writer = csv.writer(fout) writer.writerows(rows)
bsd-3-clause
Python
ed157602d965be952aadc9fe33b2e517c7f98ccf
Add urls
funkybob/dumpling,funkybob/dumpling
dumpling/urls.py
dumpling/urls.py
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'css/(?P<name>.*)\.css$', views.styles, name='styles'), url(r'(?P<path>.*)', views.PageView.as_view()), ]
mit
Python
380178c585d4b9e2689ffdd72c9fa80be94fe3a9
add more calculation
kanhua/pypvcell
examples/ingap_gaas_radeta_paper.py
examples/ingap_gaas_radeta_paper.py
__author__ = 'kanhua' import numpy as np from scipy.interpolate import interp2d import matplotlib.pyplot as plt from scipy.io import savemat from iii_v_si import calc_2j_si_eta, calc_3j_si_eta if __name__=="__main__": algaas_top_ere=np.logspace(-7,0,num=50) algaas_mid_ere=np.logspace(-7,0,num=50) eta_array=np.zeros((algaas_top_ere.shape[0],algaas_mid_ere.shape[0])) for i,teg in enumerate(algaas_top_ere): for j,meg in enumerate(algaas_mid_ere): eta,_,_,_= calc_3j_si_eta(teg, meg, 1, top_band_gap=1.87, top_cell_qe=0.75, mid_band_gap=1.42, mid_cell_qe=0.75,bot_cell_qe=0.75,bot_cell_eta=5e-4) eta_array[i,j]=eta np.savez("ingap_gaas_ere_3J_paper.npz",tbg=algaas_top_ere,mbg=algaas_mid_ere,eta=eta_array) plt.pcolormesh(algaas_mid_ere,algaas_top_ere,eta_array) plt.colorbar() plt.xlabel("ERE of middle cell (eV)") plt.ylabel("ERE of top cell (eV)") plt.xlim([np.min(algaas_mid_ere),np.max(algaas_mid_ere)]) plt.ylim([np.min(algaas_top_ere),np.max(algaas_top_ere)]) plt.xscale("log") plt.yscale("log") plt.savefig("ingap_gaas_ere_3J_paper.pdf") plt.show()
apache-2.0
Python
93b38901b25f6c5db4700343050c5bb2fc6ef7e6
add utility to make digraph out of router
BrianHicks/emit,BrianHicks/emit,BrianHicks/emit
emit/graphviz.py
emit/graphviz.py
def make_digraph(router, name='router'): header = 'digraph %s {\n' % name footer = '\n}' lines = [] for origin, destinations in router.routes.items(): for destination in destinations: lines.append('"%s" -> "%s";' % (origin, destination)) return header + '\n'.join(lines) + footer
mit
Python
c16620dffd2cd6396eb6b7db76a9c29849a16500
Add support for cheminformatics descriptors
MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio
components/lie_structures/lie_structures/cheminfo_descriptors.py
components/lie_structures/lie_structures/cheminfo_descriptors.py
# -*- coding: utf-8 -*- """ file: cheminfo_molhandle.py Cinfony driven cheminformatics fingerprint functions """ import logging from twisted.logger import Logger from . import toolkits logging = Logger() def available_descriptors(): """ List available molecular descriptors for all active cheminformatics packages The webel toolkit has a descriptor service but the supported descriptors are not listed in Cinfony. The toolkit is available however. :rtype: :py:dict """ available_descs = {'webel': None} for toolkit, obj in toolkits.items(): if hasattr(obj, 'descs'): available_descs[toolkit] = obj.descs return available_descs
apache-2.0
Python
718b8dcb87ae2b78e5ce0aded0504a81d599daf7
Create envToFish.py
Sv3n/FishBashEnv,Sv3n/FishBashEnv
envToFish.py
envToFish.py
#!/usr/bin/env python import os import subprocess badKeys = ['HOME', 'PWD', 'USER', '_', 'OLDPWD'] with open('profile.fish', 'w') as f: for key, val in os.environ.items(): if key in badKeys: continue if key == 'PATH': f.write("set -e PATH\n") pathUnique = set(val.split(':')) for elem in pathUnique: f.write("set -gx PATH $PATH %s\n" % elem) else: f.write("set -gx %s '%s'\n" % (key, val))
unlicense
Python
01328db808d3f5f1f9df55117ef70924fb615a6a
Create config reader
braveheuel/python-escpos,python-escpos/python-escpos,belono/python-escpos
escpos/config.py
escpos/config.py
from __future__ import absolute_import import os import appdirs from localconfig import config from . import printer from .exceptions import * class Config(object): _app_name = 'python-escpos' _config_file = 'config.ini' def __init__(self): self._has_loaded = False self._printer = None self._printer_name = None self._printer_config = None def load(self, config_path=None): # If they didn't pass one, load default if not config_path: config_path = os.path.join( appdirs.user_config_dir(self._app_name), self._config_file ) # Deal with one config or a list of them # Configparser does this, but I need it for the list in the error message if isinstance(config_path, basestring): config_path = [config_path] files_read = config.read(config_path) if not files_read: raise ConfigNotFoundError('Couldn\'t read config at one or more of {config_path}'.format( config_path="\n".join(config_path), )) if 'printer' in config: # For some reason, dict(config.printer) raises # TypeError: attribute of type 'NoneType' is not callable self._printer_config = dict(list(config.printer)) self._printer_name = self._printer_config.pop('type').title() if not self._printer_name or not hasattr(printer, self._printer_name): raise ConfigSyntaxError('Printer type "{printer_name}" is invalid'.format( printer_name=self._printer_name, )) self._has_loaded = True def printer(self): if not self._has_loaded: self.load() if not self._printer: # We could catch init errors and make them a ConfigSyntaxError, # but I'll just let them pass self._printer = getattr(printer, self._printer_name)(**self._printer_config) return self._printer
mit
Python
0f43f3bdc9b22e84da51e490664aeedc4295c8c9
Add test for ELB
achiku/jungle
tests/test_elb.py
tests/test_elb.py
# -*- coding: utf-8 -*- from jungle import cli def test_elb_ls(runner, elb): """test for elb ls""" result = runner.invoke(cli.cli, ['elb', 'ls']) assert result.exit_code == 0 def test_elb_ls_with_l(runner, elb): """test for elb ls -l""" result = runner.invoke(cli.cli, ['elb', 'ls', '-l']) assert result.exit_code == 0
mit
Python
c1bf53c5c278cafa3b1c070f8a232d5820dcb7a4
add elb list test.
jonhadfield/acli,jonhadfield/acli
tests/test_elb.py
tests/test_elb.py
from __future__ import (absolute_import, print_function, unicode_literals) from acli.output.elb import (output_elb_info, output_elbs) from acli.services.elb import (elb_info, elb_list) from acli.config import Config from moto import mock_elb import pytest from boto3.session import Session session = Session(region_name="eu-west-1") @pytest.yield_fixture(scope='function') def elb_instances(): """ELB mock service""" mock = mock_elb() mock.start() client = session.client('elb') zones = ['eu-west-1a', 'eu-west-1b'] listeners = [{ 'Protocol': 'string', 'LoadBalancerPort': 123, 'InstanceProtocol': 'string', 'InstancePort': 123, 'SSLCertificateId': 'string'}] client.create_load_balancer(LoadBalancerName='my-lb', AvailabilityZones=zones, Listeners=listeners) yield client.describe_load_balancers() mock.stop() config = Config(cli_args={'--region': 'eu-west-1', '--access_key_id': 'AKIAIOSFODNN7EXAMPLE', '--secret_access_key': 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'}) def test_elb_list_service(elb_instances): with pytest.raises(SystemExit): assert elb_list(aws_config=config) # def test_elb_info_service(ec2_instances): # with pytest.raises(SystemExit): # assert elb_info(aws_config=config, elb_name=list(ec2_instances)[0].id)
mit
Python
ee3e04d32e39d6ac7ef4ac7abc2363a1ac9b8917
Add an example for the music module
derblub/pixelpi,marian42/pixelpi,derblub/pixelpi,derblub/pixelpi,marian42/pixelpi
example_music.py
example_music.py
from screenfactory import create_screen from modules.music import Music import config import time import pygame screen = create_screen() music = Music(screen) music.start() while True: if config.virtual_hardware: pygame.time.wait(10) for event in pygame.event.get(): pass else: time.sleep(0.01)
mit
Python
9be3bf6d71c54fe95db08c6bc1cd969dfbb2ebd1
Add Dia generated .py file
mteule/StationMeteo,mteule/StationMeteo
doc/StationMeteo.Diagram.py
doc/StationMeteo.Diagram.py
class Station : def __init__(self) : self.ser = SerialInput() # self.parser = InputParser() # self.datab = DatabManager() # self.input = None # str self.sensor_dict = dict('id': ,'name': ) # self.last_meterings_list = LastMeteringList() # pass def __get_serial_input_content (self, ser) : # returns pass def __parse (self, serial_input_content) : # returns pass def __store_meterings (self) : # returns pass def __connect_serial (self) : # returns pass def setup (self) : # returns pass def loop (self) : # returns pass class DatabManager : ''' http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#adding-new-objects''' def __init__(self) : self.engine_url = 'sqlite:///:memory:' # str self.engine = sqlalchemy.create_engine(engine_url, echo = True) # self.Session = sqlalchemy.orm.sessionmaker(bind=engine) # self.session = Session() # self.metering = Metering() # self.Sensors = Sensors() # pass class Sensors : ''' https://www.google.fr/#q=NVARCHAR+encodage+mysql https://stackoverflow.com/questions/612430/when-must-we-use-nvarchar-nchar-instead-of-varchar-char-in-sql-servers Nvarchar ne sert que pour les utilisateurs MS-SQL. ''' def __init__(self) : pass class Metering : ''' http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#declare-a-mapping >>> from sqlalchemy.ext.declarative import declarative_base >>> declarative_base() <class 'sqlalchemy.ext.declarative.Base'> >>> ''' def __init__(self) : pass class /dev/tty : def __init__(self) : self.name = None # string pass class SerialInput : ''' >>> from serial import Serial >>> Serial() Serial<id=0xb767eb6c, open=False>(port=None, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False) >>> help(Serial()) >>> help(Serial.readline()) >>> help(Serial.readlines()) ''' def __init__(self) : self.port = '/dev/ttyUSB0' # self.baudrate = 115200 # int pass def readline (self) : # returns str pass class InputParser : def __init__(self) : self.serial_input_content = None # str self.last_meterings_list = LastMeteringList() # pass def parse (self, ) : # returns pass class LastMeteringList : def __init__(self) : pass
mit
Python
54718d95c4398d816546b45ed3f6a1faf2cdace8
add modules/flexins/nsversion.py
maxli99/SmartChecker,maxli99/SmartChecker
modules/flexins/nsversion.py
modules/flexins/nsversion.py
"""Analysis and Check the FlexiNS software version. """ import re from libs.checker import ResultInfo,CheckStatus from libs.log_spliter import LogSpliter,LOG_TYPE_FLEXI_NS from libs.tools import read_cmdblock_from_log ## Mandatory variables ##-------------------------------------------- module_id = 'fnsbase.01' tag = ['flexins','base'] priority = 'normal' name = "Check the FNS software version" desc = __doc__ criteria = "FNS version is ['N5 1.19-3']." result = ResultInfo(name) ##-------------------------------------------- ## Optional variables ##-------------------------------------------- target_version = ['N5 1.19-3'] version_info = "Packages Info:\n %s" pat_pkgid= re.compile("\s+(BU|FB|NW)\s+.*?\n\s+(\w\d [\d\.-]+)") check_commands = [ ("ZWQO:CR;","show the NS packages information"), ] ## def check_version(logtxt): error = '' info = '' status = '' pkgid = dict(pat_pkgid.findall(str(logtxt))) try: if pkgid['BU'] in target_version: status = CheckStatus.PASSED else: status = CheckStatus.FAILED info = str(pkgid) except (KeyError,ValueError) as e: status = CheckStatus.UNKNOWN info = e return status,info,error ##-------------------------------------------- ## Mandatory function: run ##-------------------------------------------- def run(logfile): """The 'run' function is a mandatory fucntion. and it must return a ResultInfo. """ ns_command_end_mark = "COMMAND EXECUTED" logtxt = read_cmdblock_from_log(logfile,'ZWQO:CR;',ns_command_end_mark) if logtxt: status,info,error = check_version(logtxt) result.update(status=status,info=(version_info % info).split('\n'),error=error) else: status = CheckStatus.UNKNOWN error = "Can't find the version info in the log." result.update(status=status,info='',error=error) return result
mit
Python
8cb94efa41e5350fccdc606f4959f958fc309017
Add lldb debug visualizer
ChenJian345/realm-cocoa,lumoslabs/realm-cocoa,thdtjsdn/realm-cocoa,nathankot/realm-cocoa,xmartlabs/realm-cocoa,thdtjsdn/realm-cocoa,iOS--wsl--victor/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,Havi4/realm-cocoa,brasbug/realm-cocoa,yuuki1224/realm-cocoa,zilaiyedaren/realm-cocoa,brasbug/realm-cocoa,sunfei/realm-cocoa,Palleas/realm-cocoa,imjerrybao/realm-cocoa,isaacroldan/realm-cocoa,codyDu/realm-cocoa,iOSCowboy/realm-cocoa,neonichu/realm-cocoa,HuylensHu/realm-cocoa,bugix/realm-cocoa,brasbug/realm-cocoa,Havi4/realm-cocoa,neonichu/realm-cocoa,thdtjsdn/realm-cocoa,iOSCowboy/realm-cocoa,bestwpw/realm-cocoa,hejunbinlan/realm-cocoa,dilizarov/realm-cocoa,ul7290/realm-cocoa,bestwpw/realm-cocoa,nathankot/realm-cocoa,tenebreux/realm-cocoa,hejunbinlan/realm-cocoa,isaacroldan/realm-cocoa,yuuki1224/realm-cocoa,bestwpw/realm-cocoa,sunzeboy/realm-cocoa,bugix/realm-cocoa,kylebshr/realm-cocoa,bugix/realm-cocoa,thdtjsdn/realm-cocoa,Palleas/realm-cocoa,vuchau/realm-cocoa,nathankot/realm-cocoa,tenebreux/realm-cocoa,iOS--wsl--victor/realm-cocoa,yuuki1224/realm-cocoa,vuchau/realm-cocoa,vuchau/realm-cocoa,tenebreux/realm-cocoa,codyDu/realm-cocoa,ul7290/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,nathankot/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,kylebshr/realm-cocoa,kevinmlong/realm-cocoa,ChenJian345/realm-cocoa,ChenJian345/realm-cocoa,vuchau/realm-cocoa,xmartlabs/realm-cocoa,iOS--wsl--victor/realm-cocoa,xmartlabs/realm-cocoa,ChenJian345/realm-cocoa,sunzeboy/realm-cocoa,isaacroldan/realm-cocoa,imjerrybao/realm-cocoa,lumoslabs/realm-cocoa,kylebshr/realm-cocoa,isaacroldan/realm-cocoa,sunzeboy/realm-cocoa,Havi4/realm-cocoa,Havi4/realm-cocoa,hejunbinlan/realm-cocoa,ul7290/realm-cocoa,yuuki1224/realm-cocoa,bugix/realm-cocoa,iOS--wsl--victor/realm-cocoa,HuylensHu/realm-cocoa,sunfei/realm-cocoa,yuuki1224/realm-cocoa,zilaiyedaren/realm-cocoa,neonichu/realm-cocoa,iOSCowboy/realm-cocoa,codyDu/realm-cocoa,kevinmlong/realm-cocoa,thdtjsdn/realm-cocoa,tenebreux/realm-cocoa,sunfei/realm-cocoa,bugix/realm-cocoa,lumoslabs/realm-cocoa,HuylensHu/realm-cocoa,iOSCowboy/realm-cocoa,hejunbinlan/realm-cocoa,tenebreux/realm-cocoa,duk42111/realm-cocoa,HuylensHu/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,neonichu/realm-cocoa,ChenJian345/realm-cocoa,sunfei/realm-cocoa,ul7290/realm-cocoa,neonichu/realm-cocoa,hejunbinlan/realm-cocoa,dilizarov/realm-cocoa,Palleas/realm-cocoa,iOS--wsl--victor/realm-cocoa,ul7290/realm-cocoa,imjerrybao/realm-cocoa,dilizarov/realm-cocoa,sunzeboy/realm-cocoa,imjerrybao/realm-cocoa,sunfei/realm-cocoa,bestwpw/realm-cocoa,duk42111/realm-cocoa,kevinmlong/realm-cocoa,zilaiyedaren/realm-cocoa,iOSCowboy/realm-cocoa,xmartlabs/realm-cocoa,codyDu/realm-cocoa,duk42111/realm-cocoa,brasbug/realm-cocoa,sunzeboy/realm-cocoa,vuchau/realm-cocoa,AlexanderMazaletskiy/realm-cocoa,duk42111/realm-cocoa,isaacroldan/realm-cocoa,dilizarov/realm-cocoa,Palleas/realm-cocoa,Havi4/realm-cocoa,zilaiyedaren/realm-cocoa,Palleas/realm-cocoa,dilizarov/realm-cocoa,nathankot/realm-cocoa,kevinmlong/realm-cocoa,lumoslabs/realm-cocoa,kylebshr/realm-cocoa,brasbug/realm-cocoa,imjerrybao/realm-cocoa,kevinmlong/realm-cocoa,zilaiyedaren/realm-cocoa,kylebshr/realm-cocoa,HuylensHu/realm-cocoa,duk42111/realm-cocoa,bestwpw/realm-cocoa,xmartlabs/realm-cocoa,lumoslabs/realm-cocoa,codyDu/realm-cocoa
tools/rlm_lldb.py
tools/rlm_lldb.py
############################################################################## # # Copyright 2014 Realm Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## import lldb # command script import /src/rlm_lldb.py --allow-reload property_types = { 0: 'int64_t', 10: 'double', 1: 'bool', 9: 'float', } def to_str(val): return val.GetProcess().ReadCStringFromMemory(val.GetValueAsUnsigned(), 1024, lldb.SBError()) cached_schemas = {} class SyntheticChildrenProvider(object): def _eval(self, expr): frame = self.obj.GetThread().GetSelectedFrame() return frame.EvaluateExpression(expr) class RLMObject_SyntheticChildrenProvider(SyntheticChildrenProvider): def __init__(self, obj, _): self.obj = obj objectSchema = self._eval("((RLMObject *){})->_objectSchema".format(self.obj.GetAddress())).GetValueAsUnsigned() self.props = cached_schemas.get(objectSchema, None) if not self.props: properties = self._eval("((RLMObjectSchema *){})->_properties".format(objectSchema)).GetValueAsUnsigned() count = self._eval("(NSUInteger)[((NSArray *){}) count]".format(properties)).GetValueAsUnsigned() self.props = [self._get_prop(properties, i) for i in range(count)] cached_schemas[objectSchema] = self.props def num_children(self): return len(self.props) def has_children(self): return True def get_child_index(self, name): return next(i for i, (prop_name, _) in enumerate(self.props) if prop_name == name) def get_child_at_index(self, index): name, getter = self.props[index] value = self._eval(getter) return self.obj.CreateValueFromData(name, value.GetData(), value.GetType()) def update(self): pass def _get_prop(self, props, i): prop = self._eval("(NSUInteger)[((NSArray *){}) objectAtIndex:{}]".format(props, i)).GetValueAsUnsigned() name = to_str(self._eval("[((RLMProperty *){})->_name UTF8String]".format(prop))) type = self._eval("((RLMProperty *){})->_type".format(prop)).GetValueAsUnsigned() getter = "({})[(id){} {}]".format(property_types.get(type, 'id'), self.obj.GetAddress(), name) return name, getter def RLMArray_SummaryProvider(obj, _): className = to_str(eval_objc(obj, "(const char *)[(NSString *)[(RLMArray *){} objectClassName] UTF8String]")) count = eval_objc(obj, "(NSUInteger)[(RLMArray *){} count]").GetValueAsUnsigned() return "({}[{}])".format(className, count) class RLMArray_SyntheticChildrenProvider(SyntheticChildrenProvider): def __init__(self, valobj, _): self.obj = valobj self.addr = self.obj.GetAddress() def num_children(self): return self.count def has_children(self): return True def get_child_index(self, name): return int(name.lstrip('[').rstrip(']')) def get_child_at_index(self, index): value = self._eval('(id)[(id){} objectAtIndex:{}]'.format(self.addr, index)) return self.obj.CreateValueFromData('[' + str(index) + ']', value.GetData(), value.GetType()) def update(self): self.count = self._eval("(NSUInteger)[(RLMArray *){} count]".format(self.addr)).GetValueAsUnsigned() def __lldb_init_module(debugger, _): debugger.HandleCommand('type summary add RLMArray -F rlm_lldb.RLMArray_SummaryProvider') debugger.HandleCommand('type summary add RLMArrayLinkView -F rlm_lldb.RLMArray_SummaryProvider') debugger.HandleCommand('type summary add RLMArrayTableView -F rlm_lldb.RLMArray_SummaryProvider') debugger.HandleCommand('type synthetic add RLMArray --python-class rlm_lldb.RLMArray_SyntheticChildrenProvider') debugger.HandleCommand('type synthetic add RLMArrayLinkView --python-class rlm_lldb.RLMArray_SyntheticChildrenProvider') debugger.HandleCommand('type synthetic add RLMArrayTableView --python-class rlm_lldb.RLMArray_SyntheticChildrenProvider') debugger.HandleCommand('type synthetic add -x RLMAccessor_.* --python-class rlm_lldb.RLMObject_SyntheticChildrenProvider')
apache-2.0
Python
ec41564bb99c8e79bcee1baabd75d2282601415c
add refund
Shopify/shopify_python_api
shopify/resources/refund.py
shopify/resources/refund.py
from ..base import ShopifyResource class Refund(ShopifyResource): _prefix_source = "/admin/orders/$order_id/"
mit
Python
e7247c8c70a8cfefaee057e0c731aa5dab41ca9a
Create Contours.py
li8bot/OpenCV,li8bot/OpenCV
Contours.py
Contours.py
from PIL import Image from pylab import * #read image into an array im = array(Image.open('s9.jpg').convert('L')) #create a new figure figure() #don't use colors gray() #show contours contour(im,origin = 'image') axis('equal') axis('off') figure() hist(im.flatten(),128) show()
mit
Python
9315c59746e2be9f2f15ff2bae02e1b481e9a946
Create mr.py
umarags/test
mr.py
mr.py
Mapper: #!/usr/bin/python import sys while 1: line = sys.stdin.readline() if line == "": break fields = line.split(",") year = fields[1] runs = fields[8] if year == "1956": print runs Reducer: #!/usr/bin/python import sys total_count = 0 for line in sys.stdin: try: count = int(line) total_count += count except ValueError: # count was not a number, so silently # ignore/discard this line continue print total_count
artistic-2.0
Python
c91e231c8d71458a7c347088ad7ec6431df234d7
add ss.py to update proxy automatically
eilinx/lpthw
ss.py
ss.py
# -*- coding:utf8 -*- import urllib2 response = urllib2.urlopen("http://boafanx.tabboa.com/boafanx-ss/") html = response.read() print(html[:20000])
mit
Python
4015a16ec32660d25646f62772876d53166f46f2
Add files via upload
ma-compbio/PEP
PEP.py
PEP.py
#-*- coding: utf-8 -*- from optparse import OptionParser import genLabelData,genUnlabelData,mainEdit,genVecs import os.path def parse_args(): parser = OptionParser(usage="RNA editing prediction", add_help_option=False) parser.add_option("-f", "--feature", default="300", help="Set the number of features of Word2Vec model") parser.add_option("-g","--generate",default="true", help="Generate the Data or Use the ones before") parser.add_option("-t","--type",default="ep",help="eep data or ep data") parser.add_option("-c","--cell",default = "GM12878",help="Cell Line") parser.add_option("-k","--k",default="1",help="k") parser.add_option("-w","--word",default = "6") parser.add_option("-i","--integrate",default="false", help="Use integrated features or not") parser.add_option("-s","--sel",default=50, help="The number of motif feature to be used in the combination mode") parser.add_option("-e","--thresh_mode",default=1,help="The mode of estimating threshold:0-default;1-simple mode;2-cv mode") (opts, args) = parser.parse_args() return opts def run(word,num_features,generate,type,cell,k,integrate,sel): if(os.path.exists("./Data/Learning")==False): os.makedirs("./Data/Learning") print "parameters are as followed\n" \ "feature=%r\tgenerate=%r\n" \ "type=%r\tcell=%r\n" \ "k=%r\n"\ %(num_features,generate,type,cell,k) if generate == "true": if not os.path.isfile("./Data/Learning/supervised_"+str(cell)+"_"+str(type)): genLabelData.run(type,cell) if not os.path.isfile("./Data/Learning/unlabeled_train_promoter_"+str(cell)+"_"+str(type)): genUnlabelData.run(type,cell,word) if not os.path.isfile("./Datavecs/datavecs_"+str(cell)+"_"+str(type)+".npy"): genVecs.run(word,num_features,k,type,cell) if integrate == "false": mainPEP.run_word(word,num_features,k,type,cell) else: mainPEP.run_shuffle(word,num_features,k,type,cell,sel) def main(): opts = parse_args() run(opts.word,opts.feature,opts.generate,opts.type,opts.cell,opts.k,opts.integrate,opts.sel) if __name__ == '__main__': main()
mit
Python
8016dbc50238d2baf5f89c191ec3355df63af1a2
Implement basic flask app to add subscribers
sagnew/ISSNotifications,sagnew/ISSNotifications,sagnew/ISSNotifications
app.py
app.py
import iss from flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template() @app.route('/subscribe', methods=['POST']) def subscribe(): number = request.form['number'] lat = request.form['latitude'] lon = request.form['longitude'] iss.add_to_queue(number, lat, lon) return render_template() app.run(host='0.0.0.0')
mit
Python
341890bfff2d8a831e48ebb659ce7f31d4918773
Update utils.py
rishubhjain/commons,Tendrl/commons,r0h4n/commons
tendrl/commons/central_store/utils.py
tendrl/commons/central_store/utils.py
from tendrl.commons.etcdobj import fields def to_etcdobj(cls_etcd, obj): for attr, value in vars(obj).iteritems(): if attr.startswith("_"): continue if attr in ["attrs", "enabled", "obj_list", "obj_value", "atoms", "flows"]: continue setattr(cls_etcd, attr, to_etcd_field(attr, value)) return cls_etcd def to_etcd_field(name, value): type_to_etcd_fields_map = {dict: fields.DictField, str: fields.StrField, int: fields.IntField, bool: fields.StrField} return type_to_etcd_fields_map[type(value)](name)
from tendrl.commons.etcdobj import fields def to_etcdobj(cls_etcd, obj): for attr, value in vars(obj).iteritems(): if not attr.startswith("_"): setattr(cls_etcd, attr, to_etcd_field(attr, value)) return cls_etcd def to_etcd_field(name, value): type_to_etcd_fields_map = {dict: fields.DictField, str: fields.StrField, int: fields.IntField, bool: fields.StrField} return type_to_etcd_fields_map[type(value)](name)
lgpl-2.1
Python
9d41eba840f954595a5cebbacaf56846cd52c1f4
add new file
julia2288-cmis/julia2288-cmis-cs2
functions.py
functions.py
def add(a,b):
cc0-1.0
Python
3000a9c0b7213a3aeb9faa0c01e5b779b2db36d4
add a noisy bezier example (todo: should noise be part of the animation, or stay out of it?)
shimpe/pyvectortween,shimpe/pyvectortween
examples/example_bezier_noise.py
examples/example_bezier_noise.py
if __name__ == "__main__": import gizeh import moviepy.editor as mpy from vectortween.BezierCurveAnimation import BezierCurveAnimation from vectortween.SequentialAnimation import SequentialAnimation import noise def random_color(): import random return (random.uniform(0, 1) for _ in range(3)) W, H = 250, 250 # width, height, in pixels duration = 5 # duration of the clip, in seconds fps = 25 controlpoints_collections = [ [(120, 160), (35, 200), (220, 240), (220, 40)], [(220, 40), (120, 40), (10, 200)] ] b1 = BezierCurveAnimation(controlpoints=controlpoints_collections[0],tween=["easeOutBounce"]) b2 = BezierCurveAnimation(controlpoints=controlpoints_collections[1],tween=["easeOutBounce"]) b = SequentialAnimation([b1,b2]) colors = ((0,1,1),(1,1,0)) def make_frame(t): surface = gizeh.Surface(W, H) xy = b.make_frame(t, 0, 0, duration - 1, duration) curve_points = b.curve_points(0, t, 0.01, 0, 0, duration - 1, duration) # print (curve_points) xnoise = [] ynoise = [] result = [] for i,c in enumerate(curve_points): xnoise.append(2*noise.snoise3(c[0],c[1],0)) ynoise.append(2*noise.snoise3(c[0],c[1],1)) result.append([(c[0] + xnoise[i]), (c[1] + ynoise[i])]) if xy is not None and None not in xy: gizeh.circle(5, xy=[xy[0]+xnoise[i],xy[1]+ynoise[i]], fill=(0, 1, 0)).draw(surface) curve_points = result gizeh.polyline(curve_points, stroke=(0, 0, 1), stroke_width=2).draw(surface) for i, controlpoints in enumerate(controlpoints_collections): gizeh.polyline(controlpoints, stroke=colors[i], stroke_width=2).draw(surface) for cp in controlpoints: gizeh.circle(5, xy=cp, fill=(1, 1, 1)).draw(surface) return surface.get_npimage() clip = mpy.VideoClip(make_frame, duration=duration) clip.write_videofile("example_bezier_noise.mp4", fps=fps, codec="libx264")
mit
Python
05c7d62e0e26000440e72d0700c9806d7a409744
Add migrations for game change suggestions
lutris/website,lutris/website,lutris/website,lutris/website
games/migrations/0023_auto_20171104_2246.py
games/migrations/0023_auto_20171104_2246.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-11-04 21:46 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('games', '0022_installer_reason'), ] operations = [ migrations.AddField( model_name='game', name='change_for', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='games.Game'), ), migrations.AddField( model_name='gamesubmission', name='reason', field=models.TextField(blank=True, null=True), ), migrations.AlterField( model_name='game', name='slug', field=models.SlugField(blank=True, null=True, unique=True), ), ]
agpl-3.0
Python
ad073b043b2965fb6a1939682aeca8ac90259210
add daily import to database
kaija/taiwan_stockloader,kaija/taiwan_stockloader
daily.py
daily.py
import datetime import httplib import urllib import redis import json from datetime import timedelta #now = datetime.datetime.now(); #today = now.strftime('%Y-%m-%d') #print today rdb = redis.Redis('localhost') def isfloat(value): try: float(value) return True except ValueError: return False def convfloat(value): try: return float(value) except ValueError: return -1 def convint(value): try: return int(value) except ValueError: return 0 def save2redis(key, value): old = rdb.get("TW" + key) if old is None: val = [] val.append(value) rdb.set("TW"+key ,json.dumps(val)) else: l = json.loads(old) l.append(value) rdb.set("TW"+key ,json.dumps(l)) today = datetime.date.today() #today = datetime.date(2015, 5, 15) one_day = timedelta(days=1) dl_date = today httpreq = httplib.HTTPConnection('www.twse.com.tw') headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} date_str = str(dl_date.year - 1911 ) + dl_date.strftime("/%m/%d") form = urllib.urlencode({'download': 'csv', 'qdate': date_str, 'selectType': 'ALLBUT0999'}) httpreq.request("POST", "/ch/trading/exchange/MI_INDEX/MI_INDEX.php", form, headers); httpres = httpreq.getresponse() stock_csv = httpres.read() lines = stock_csv.split("\n") for line in lines: r = line.split('","') if len(r) == 16: head = r[0].split("\"") sid = head[1].strip(" ") obj = {"volume": convint(r[2]), "open": convfloat(r[5]), "high": convfloat(r[6]), "low": convfloat(r[7]), "val": convfloat(r[8]), "date": dl_date.strftime("%Y-%m-%d"), "per": convfloat(r[15]), "buyQuantity": convint(r[12]), "buyPrice": convint(r[11]), "saleQuantity": convint(r[14]), "salePrice": convint(r[13])} print sid print obj save2redis(sid, obj)
mit
Python
09d51aef1127b55fdc6bf595ca85285d9d7d64d1
Add wrapwrite utility method
Alir3z4/python-gignore
gignore/utils.py
gignore/utils.py
import sys def wrapwrite(text): """ :type text: str :rtype: str """ text = text.encode('utf-8') try: # Python3 sys.stdout.buffer.write(text) except AttributeError: sys.stdout.write(text)
bsd-3-clause
Python
617a44bcce3e6e19383065f7fcab5b44ceb82714
add logger
plazmer/micro-meta,plazmer/micro-meta
log.py
log.py
import logging import sys logger = logging.getLogger('micro-meta') logger.setLevel(logging.DEBUG) fh = logging.StreamHandler(sys.stdout) fh.setLevel(logging.DEBUG) logger.addHandler(fh) logger.debug('test') logger.info('test')
mit
Python
a38b313799b7c0cdc25ff68161c2b2890db8e16d
Create log.py
julioscalves/v-screen
log.py
log.py
import glob import pandas as pd logs = [log for log in glob.glob("*.log")] dataset = {"id": [], "pos": [], "affinity (kcal/mol)": [], "rmsd l.b.": [], "rmsd u.b.": []} for log in logs: with open(log) as dock: for line in dock.readlines(): if line.startswith(" ") and line.split()[0] != "|": dataset["id"].append(log[:-4]) dataset["pos"].append(line.split()[0]) dataset["affinity (kcal/mol)"].append(line.split()[1]) dataset["rmsd l.b."].append(line.split()[2]) dataset["rmsd u.b."].append(line.split()[3]) dataframe = pd.DataFrame(data=dataset) dataframe.to_csv("docks.csv")
mit
Python
7263d7546aec62834fa19f20854522eba4916159
add simple http server
nickweinberg/Yomi-Game-Range-Tool,nickweinberg/Yomi-Game-Range-Tool,nickweinberg/Yomi-Game-Range-Tool
run.py
run.py
import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" if sys.argv[1:]: port = int(sys.argv[1]) else: port = 8000 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
mit
Python
e6d420296b3f2234382bdcdf1122abc59af148ed
add plot function for classification
berkeley-stat222/mousestyles,changsiyao/mousestyles,togawa28/mousestyles
mousestyles/visualization/plot_classification.py
mousestyles/visualization/plot_classification.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt def plot_performance(model): """ Plots the performance of classification model.It is a side-by-side barplot. For each strain, it plots the precision, recall and F-1 measure. Parameters ---------- model: string The model used to classify the strain Returns ------- None """ if model is 'SVM': result = pd.DataFrame(np.load('SVM_result.npy')) elif model is 'RF': result = pd.DataFrame(np.load('RF_result.npy')) elif model is 'GB': result = pd.DataFrame(np.load('GB_result.npy')) N = 16 ind = np.arange(N) # the x locations for the groups width = 0.2 fig = plt.figure() ax = fig.add_subplot(111) precision = result.iloc[:, 0] rects1 = ax.bar(ind, precision, width, color='Coral') recall = result.iloc[:, 1] rects2 = ax.bar(ind+width, recall, width, color='LightSeaGreen') f1 = result.iloc[:, 2] rects3 = ax.bar(ind+width*2, f1, width, color='DodgerBlue') ax.set_ylabel('Accuracy') ax.set_xlabel('Strains') ax.set_xticks(ind+width) ax.set_xticklabels(range(16)) ax.legend((rects1[0], rects2[0], rects3[0]), ('precision', 'recall', 'F1')) plt.show() return()
bsd-2-clause
Python
a1ec669f4c494709dc9b8f3e47ff4f84b189b2e9
add get_workflow_name.py
googleapis/nodejs-redis,googleapis/nodejs-redis,googleapis/nodejs-redis
.circleci/get_workflow_name.py
.circleci/get_workflow_name.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Get workflow name for the current build using CircleCI API. Would be great if this information is available in one of CircleCI environment variables, but it's not there. https://circleci.ideas.aha.io/ideas/CCI-I-295 """ import json import os import sys import urllib2 def main(): try: username = os.environ['CIRCLE_PROJECT_USERNAME'] reponame = os.environ['CIRCLE_PROJECT_REPONAME'] build_num = os.environ['CIRCLE_BUILD_NUM'] except: sys.stderr.write( 'Looks like we are not inside CircleCI container. Exiting...\n') return 1 try: request = urllib2.Request( "https://circleci.com/api/v1.1/project/github/%s/%s/%s" % (username, reponame, build_num), headers={"Accept": "application/json"}) contents = urllib2.urlopen(request).read() except: sys.stderr.write('Cannot query CircleCI API. Exiting...\n') return 1 try: build_info = json.loads(contents) except: sys.stderr.write( 'Cannot parse JSON received from CircleCI API. Exiting...\n') return 1 try: workflow_name = build_info['workflows']['workflow_name'] except: sys.stderr.write( 'Cannot get workflow name from CircleCI build info. Exiting...\n') return 1 print workflow_name return 0 retval = main() exit(retval)
apache-2.0
Python
3abf7e60d3bd028f86cb6aa2e1e1f3d4fff95353
Create BinaryTreeMaxPathSum_001.py
Chasego/codirit,cc13ny/Allin,cc13ny/algo,Chasego/codirit,cc13ny/Allin,cc13ny/algo,cc13ny/algo,cc13ny/Allin,Chasego/codi,Chasego/codi,Chasego/codirit,Chasego/cod,cc13ny/algo,Chasego/codirit,Chasego/codi,Chasego/cod,cc13ny/Allin,Chasego/cod,Chasego/codi,Chasego/cod,cc13ny/algo,Chasego/codirit,cc13ny/Allin,Chasego/codi,Chasego/cod
leetcode/124-Binary-Tree-Maximum-Path-Sum/BinaryTreeMaxPathSum_001.py
leetcode/124-Binary-Tree-Maximum-Path-Sum/BinaryTreeMaxPathSum_001.py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ totMax, branchMax = self.maxBranchandPathSum(root) return totMax def maxBranchandPathSum(self, root): if root is None: return 0, 0 l, r = root.left, root.right if l is None and r is None: return root.val, root.val lTotMax, lBranchMax = self.maxBranchandPathSum(root.left) rTotMax, rBranchMax = self.maxBranchandPathSum(root.right) lRootBranchMax = root.val + max(lBranchMax, 0) rRootBranchMax = root.val + max(rBranchMax, 0) if l is None: rootTotMax = max(rTotMax, rRootBranchMax) return rootTotMax, rRootBranchMax if r is None: rootTotMax = max(lTotMax, lRootBranchMax) return rootTotMax, lRootBranchMax rootTreeMax = root.val + max(lBranchMax, 0) + max(rBranchMax, 0) rootTotMax = max(lTotMax, rTotMax, rootTreeMax) rootBranchMax = max(lRootBranchMax, rRootBranchMax) return rootTotMax, rootBranchMax
mit
Python
59fd4bf04c8c89cdc87673de94788c5d34d4e5fe
Create Goldbach.py
ManuComp/Gooldbach
Goldbach.py
Goldbach.py
import math #Funcion para saber si un numero es 3 o no def es_primo(a): contador = 0 verificar= False for i in range(1,a+1): if (a% i)==0: contador = contador + 1 if contador >= 3: verificar=True break if contador==2 or verificar==False: return True return False #Creacion de un lista con todos los primos del 1 al 10,000 def lista_primos(): primos = list(); for i in range (1,10000): if es_primo(i): primos.append(i) return primos def lista_impares(): impares = list(); for i in range (1,10000,2): if not es_primo(i): impares.append(i) primos = lista_primos() impares = lista_impares() a = 0 impar = 1 for primo in primos: for n in range (1,10000): a = primo + (2)*(math.pow(n,2)) if a != impar and n > 500000: print (impar) impar += 2
unlicense
Python
e33774beb2f2b1264f654605294f0ad837fa7e8b
Add message_link function
coala/corobo,coala/corobo
utils/backends.py
utils/backends.py
""" Handle backend specific implementations. """ def message_link(bot, msg): """ :param bot: Plugin instance. :param msg: Message object. :returns: Message link. """ backend = bot.bot_config.BACKEND.lower() if backend == 'gitter': return 'https://gitter.im/{uri}?at={idd}'.format(msg.frm.room.uri, msg.extras['id']) elif backend == 'slack': return msg.extras['url'] elif backend == 'telegram': return '' elif backend == 'text': return '' else: raise NotImplementedError
mit
Python
f509d556cc4a20b55be52f505fcee200c5d44ef2
add rehex util
thelazier/sentinel,ivansib/sentinel,dashpay/sentinel,dashpay/sentinel,ivansib/sentinel,thelazier/sentinel
scripts/rehex.py
scripts/rehex.py
import simplejson import binascii import sys import pdb from pprint import pprint import sys, os sys.path.append( os.path.join( os.path.dirname(__file__), '..' ) ) sys.path.append( os.path.join( os.path.dirname(__file__), '..', 'lib' ) ) import dashlib # ============================================================================ usage = "%s <hex>" % sys.argv[0] obj = None if len(sys.argv) < 2: print(usage) sys.exit(2) else: obj = dashlib.deserialise(sys.argv[1]) pdb.set_trace() 1
mit
Python
cf881dd1ba8c98dd116f2269bf0cfd38f14a7b40
add a reel OVSFtree
Vskilet/UMTS-Multiplexing,Vskilet/UMTS-Multiplexing
OVSFTree.py
OVSFTree.py
import math numberOfMobile=512 class Node: def __init__(self, val): self.l = None self.r = None self.v = val class Tree: def __init__(self): self.root = None self.root=Node(1) thislevel = [self.root] for i in range(0,math.ceil(math.log(numberOfMobile,2))): nextlevel=[] xornumber=pow(2,pow(2,i))-1 for n in thislevel: codesize=n.v.bit_length() n.l=Node((n.v<<codesize)+n.v) n.r=Node((n.v<<codesize)+(n.v^xornumber)) nextlevel.append(n.l) nextlevel.append(n.r) thislevel=nextlevel def getRoot(self): return self.root def deleteTree(self): # garbage collector will do this for us. self.root = None def traverse(self): thislevel = [self.root] while thislevel: nextlevel = [] for n in thislevel: print( str(bin(n.v)), end=" ") if n.l: nextlevel.append(n.l) if n.r: nextlevel.append(n.r) print(" ") thislevel = nextlevel tree1=Tree() tree1.traverse()
mit
Python
632c4dffe8a217ca07410d0a353455a4c6142d39
Solve problem 29
mazayus/ProjectEuler
problem029.py
problem029.py
#!/usr/bin/env python3 print(len(set(a**b for a in range(2, 101) for b in range(2, 101))))
mit
Python