commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
4d7dff1c335a49d13d420f3c62b1a2d2382351dd
trajprocess/tests/utils.py
trajprocess/tests/utils.py
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{cl...
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. def write_run_c...
Add note about how to generate trajectories
Add note about how to generate trajectories
Python
mit
mpharrigan/trajprocess,mpharrigan/trajprocess
34d1bbc36f7d5c66000eec0d6debfd3ede74366f
bottle_auth/custom.py
bottle_auth/custom.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from bottle import redirect log = logging.getLogger('bottle-auth.custom') class Custom(object): def __init__(self, login_url="/login", callback_url="http://127.0.0.1:8000"): self.login_url = login_url self.callback_url...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from bottle import redirect log = logging.getLogger('bottle-auth.custom') class Custom(object): def __init__(self, login_url="/login", callback_url="http://127.0.0.1:8000"): self.login_url = login_url self.callback_url...
Fix Custom class, user exit in beaker.session redirect to login page
Fix Custom class, user exit in beaker.session redirect to login page
Python
mit
avelino/bottle-auth
66edf9f04c1b23681fae4234a8b297868e66b7aa
osmaxx-py/osmaxx/excerptexport/models/excerpt.py
osmaxx-py/osmaxx/excerptexport/models/excerpt.py
from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Excerpt(models.Model): name = models.CharField(max_length=128, verbose_name=_('name'), blank=False) is_public = models.BooleanField(default=False, verbose_name=_('is public')) ...
from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Excerpt(models.Model): name = models.CharField(max_length=128, verbose_name=_('name')) is_public = models.BooleanField(default=False, verbose_name=_('is public')) is_active...
Remove value which is already default
Remove value which is already default
Python
mit
geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx
cddb0309eaa0c31569f791b8b9f2c8666b65b8b4
openrcv/test/test_models.py
openrcv/test/test_models.py
from openrcv.models import ContestInfo from openrcv.utiltest.helpers import UnitCase class ContestInfoTest(UnitCase): def test_get_candidates(self): contest = ContestInfo() contest.candidates = ["Alice", "Bob", "Carl"] self.assertEqual(contest.get_candidates(), range(1, 4))
from textwrap import dedent from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo from openrcv.utils import StringInfo from openrcv.utiltest.helpers import UnitCase class BallotsResourceTest(UnitCase): def test(self): ballots = [1, 3, 2] ballot_resource = BallotsResource...
Add tests for ballots resource classes.
Add tests for ballots resource classes.
Python
mit
cjerdonek/open-rcv,cjerdonek/open-rcv
771f429433d201463ab94439870d1bc803022722
nap/auth.py
nap/auth.py
from __future__ import unicode_literals # Authentication and Authorisation from functools import wraps from . import http def permit(test_func, response_class=http.Forbidden): '''Decorate a handler to control access''' def decorator(view_func): @wraps(view_func) def _wrapped_view(self, *args...
from __future__ import unicode_literals # Authentication and Authorisation from functools import wraps from . import http def permit(test_func, response_class=http.Forbidden): '''Decorate a handler to control access''' def decorator(view_func): @wraps(view_func) def _wrapped_view(self, *args...
Make it DRYer for people
Make it DRYer for people
Python
bsd-3-clause
limbera/django-nap
483800541ee66de006392c361e06177bc9db4784
kboard/board/urls.py
kboard/board/urls.py
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new...
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_...
Set url to serve uploaded file during development
Set url to serve uploaded file during development
Python
mit
guswnsxodlf/k-board,kboard/kboard,cjh5414/kboard,kboard/kboard,hyesun03/k-board,hyesun03/k-board,hyesun03/k-board,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board,cjh5414/kboard,kboard/kboard,guswnsxodlf/k-board
e09214068a12768e9aafd04363d353359ca7e1f3
src/actions/actions/timetracking/__init__.py
src/actions/actions/timetracking/__init__.py
#!/usr/bin/python ###################################################################### # Cloud Routes Bridge # ------------------------------------------------------------------- # Actions Module ###################################################################### import stathat import time import syslog def acti...
#!/usr/bin/python ###################################################################### # Cloud Routes Bridge # ------------------------------------------------------------------- # Actions Module ###################################################################### import stathat import time def action(**kwargs): ...
Convert reactions syslog to logger: timetracking
Convert reactions syslog to logger: timetracking
Python
unknown
dethos/cloudroutes-service,asm-products/cloudroutes-service,rbramwell/runbook,codecakes/cloudroutes-service,codecakes/cloudroutes-service,asm-products/cloudroutes-service,madflojo/cloudroutes-service,Runbook/runbook,codecakes/cloudroutes-service,asm-products/cloudroutes-service,codecakes/cloudroutes-service,madflojo/cl...
e399c0b1988ed8b2981ddc684a0a3652a73ea31e
pavelib/utils/test/utils.py
pavelib/utils/test/utils.py
""" Helper functions for test tasks """ from paver.easy import sh, task from pavelib.utils.envs import Env __test__ = False # do not collect @task def clean_test_files(): """ Clean fixture files used by tests and .pyc files """ sh("git clean -fqdx test_root/logs test_root/data test_root/staticfiles ...
""" Helper functions for test tasks """ from paver.easy import sh, task from pavelib.utils.envs import Env __test__ = False # do not collect @task def clean_test_files(): """ Clean fixture files used by tests and .pyc files """ sh("git clean -fqdx test_root/logs test_root/data test_root/staticfiles ...
Clean out the mako temp dirs before running tests
Clean out the mako temp dirs before running tests
Python
agpl-3.0
zofuthan/edx-platform,eemirtekin/edx-platform,TeachAtTUM/edx-platform,synergeticsedx/deployment-wipro,doismellburning/edx-platform,OmarIthawi/edx-platform,jolyonb/edx-platform,appliedx/edx-platform,philanthropy-u/edx-platform,msegado/edx-platform,pepeportela/edx-platform,JCBarahona/edX,lduarte1991/edx-platform,jamesblu...
f931a434839222bb00282a432d6d6a0c2c52eb7d
numpy/array_api/_typing.py
numpy/array_api/_typing.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", ...
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ from __future__ import annotations __all__ = [ "...
Replace `NestedSequence` with a proper nested sequence protocol
ENH: Replace `NestedSequence` with a proper nested sequence protocol
Python
bsd-3-clause
numpy/numpy,endolith/numpy,charris/numpy,rgommers/numpy,numpy/numpy,jakirkham/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,endolith/numpy,rgommers/numpy,mattip/numpy,mattip/numpy,seberg/numpy,pdebuyl/numpy,pdebuyl/numpy,endolith/numpy,endolith/numpy,mattip/numpy,jakirkham/numpy,charris/numpy,seberg/numpy,mhvk/numpy,...
718a04f14f3ede084a2d9391e187b4d943463c6f
yanico/session/__init__.py
yanico/session/__init__.py
"""Handle nicovideo.jp user_session.""" # Copyright 2015-2016 Masayuki Yamamoto # # 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 # # Un...
"""Handle nicovideo.jp user_session.""" # Copyright 2015-2016 Masayuki Yamamoto # # 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 # # Un...
Fix a typo of class docstring
Fix a typo of class docstring
Python
apache-2.0
ma8ma/yanico
889eed552f4e17797764a9d9a2da6bbaa6d5dd33
admin_panel/views.py
admin_panel/views.py
from django.views import View from django.views.generic import TemplateView from django.contrib import auth from django.contrib import messages from django import http class LoginView(TemplateView): template_name = "admin/login.html" def post(self, request): username = request.POST['username'] ...
from django.views import View from django.views.generic import TemplateView from django.contrib import auth from django.contrib import messages from django import http from django.urls import reverse class LoginView(TemplateView): template_name = "admin/login.html" def post(self, request): username =...
Use django reverse function to obtain url instead of hard-coding
Use django reverse function to obtain url instead of hard-coding
Python
mpl-2.0
Apo11onian/Apollo-Blog,Apo11onian/Apollo-Blog,Apo11onian/Apollo-Blog
0f35ed05d335e7c126675bc913b72aac3ac916df
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
Add check for fixture loading
Add check for fixture loading
Python
bsd-2-clause
barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api
f277007e46b7c6d8c978011d7356b7527ba91133
axes/utils.py
axes/utils.py
from axes.models import AccessAttempt def reset(ip=None, username=None): """Reset records that match ip or username, and return the count of removed attempts. """ count = 0 attempts = AccessAttempt.objects.all() if ip: attempts = attempts.filter(ip_address=ip) if username: ...
from django.core.cache import cache from axes.models import AccessAttempt def reset(ip=None, username=None): """Reset records that match ip or username, and return the count of removed attempts. """ count = 0 attempts = AccessAttempt.objects.all() if ip: attempts = attempts.filter(ip...
Delete cache key in reset command line
Delete cache key in reset command line
Python
mit
jazzband/django-axes,django-pci/django-axes
a3c131776678b8e91e1179cd0f3c3b4b3fbbf6fb
openid_provider/tests/test_code_flow.py
openid_provider/tests/test_code_flow.py
from django.core.urlresolvers import reverse from django.test import RequestFactory from django.test import TestCase from openid_provider.tests.utils import * from openid_provider.views import * class CodeFlowTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.user = create_...
from django.core.urlresolvers import reverse from django.test import RequestFactory from django.test import TestCase from openid_provider.tests.utils import * from openid_provider.views import * import urllib class CodeFlowTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self....
Add another test for Code Flow.
Add another test for Code Flow.
Python
mit
wayward710/django-oidc-provider,bunnyinc/django-oidc-provider,wayward710/django-oidc-provider,juanifioren/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oidc-provider,ByteInternet/django-oidc-provider,django-py/django-openid-provider,torreco/django-oidc-provider,django-py/django-openid...
4a38d0df3d72494e2a96ac776f13ce685b537561
lokar/bib.py
lokar/bib.py
# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') sel...
# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml self.init(xml) ...
Fix diffing on Py3 by comparing unicode strings
Fix diffing on Py3 by comparing unicode strings
Python
agpl-3.0
scriptotek/almar,scriptotek/lokar
1312dc95d9c25897c11c8e818edcb9cd2b6a32f7
ecommerce/extensions/app.py
ecommerce/extensions/app.py
from oscar import app class EdxShop(app.Shop): # URLs are only visible to users with staff permissions default_permissions = 'is_staff' application = EdxShop()
from oscar import app from oscar.core.application import Application class EdxShop(app.Shop): # URLs are only visible to users with staff permissions default_permissions = 'is_staff' # Override core app instances with blank application instances to exclude their URLs. promotions_app = Application() ...
Move the security fix into Eucalyptus
Move the security fix into Eucalyptus
Python
agpl-3.0
mferenca/HMS-ecommerce,mferenca/HMS-ecommerce,mferenca/HMS-ecommerce
1958165c7bf3b9fa45972658b980cefe6a742164
myhpom/validators.py
myhpom/validators.py
import re from django.core.exceptions import ValidationError from django.core.validators import EmailValidator, RegexValidator from django.contrib.auth.models import User # First Name, Last Name: At least one alphanumeric character. name_validator = RegexValidator( regex=r'\w', flags=re.U, message='Please ...
import re from django.core.exceptions import ValidationError from django.core.validators import EmailValidator, RegexValidator # First Name, Last Name: At least one alphanumeric character. name_validator = RegexValidator( regex=r'\w', flags=re.U, message='Please enter your name' ) # Email: valid email add...
Revert "[mh-14] "This import is ultimately just from django.contrib.auth.models import User - using that directly would probably address whatever circular import required that this import get put here, and make it clearer which model User is."-Dane"
Revert "[mh-14] "This import is ultimately just from django.contrib.auth.models import User - using that directly would probably address whatever circular import required that this import get put here, and make it clearer which model User is."-Dane" This reverts commit 7350c56339acaef416d03b6d7ae0e818ab8db182.
Python
bsd-3-clause
ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM
906950ec1bd1f5d0980116d10344f9f1b7d844ed
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search(...
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) imp_del_ids = imp_obj.search([(...
Kill "Ja existeix una factura amb el mateix.." too
Kill "Ja existeix una factura amb el mateix.." too
Python
agpl-3.0
Som-Energia/invoice-janitor
2e99893065abef2f751e3fb5f19a59bfee79a756
language_model_transcription.py
language_model_transcription.py
import metasentence import language_model import standard_kaldi import diff_align import json import os import sys vocab = metasentence.load_vocabulary('PROTO_LANGDIR/graphdir/words.txt') def lm_transcribe(audio_f, text_f): ms = metasentence.MetaSentence(open(text_f).read(), vocab) model_dir = language_mo...
import metasentence import language_model import standard_kaldi import diff_align import json import os import sys vocab = metasentence.load_vocabulary('PROTO_LANGDIR/graphdir/words.txt') def lm_transcribe(audio_f, text_f): ms = metasentence.MetaSentence(open(text_f).read(), vocab) model_dir = language_mo...
Use argparse for main python entrypoint args.
Use argparse for main python entrypoint args. Will make it easier to add proto_langdir as a flag argument in a future commit.
Python
mit
lowerquality/gentle,lowerquality/gentle,lowerquality/gentle,lowerquality/gentle
de15315b95f70e56d424d54637e3ac0d615ea0f0
proto/ho.py
proto/ho.py
from board import Board, BoardCanvas b = Board(19, 19) c = BoardCanvas(b)
#!/usr/bin/env python import platform import subprocess import sys from copy import deepcopy from board import Board, BoardCanvas def clear(): subprocess.check_call('cls' if platform.system() == 'Windows' else 'clear', shell=True) class _Getch: """ Gets a single character from standard input. Does no...
Add game loop to prototype
Add game loop to prototype
Python
mit
davesque/go.py
038b56134017b6b3e4ea44d1b7197bc5168868d3
safeopt/__init__.py
safeopt/__init__.py
""" The `safeopt` package provides... Main classes ============ .. autosummary:: SafeOpt SafeOptSwarm Utilities ========= .. autosummary:: sample_gp_function linearly_spaced_combinations plot_2d_gp plot_3d_gp plot_contour_gp """ from __future__ import absolute_import from .utilities import * fr...
""" The `safeopt` package provides... Main classes ============ These classes provide the main functionality for Safe Bayesian optimization. .. autosummary:: SafeOpt SafeOptSwarm Utilities ========= The following are utilities to make testing and working with the library more pleasant. .. autosummary:: s...
Add short comment to docs
Add short comment to docs
Python
mit
befelix/SafeOpt,befelix/SafeOpt
0d50f6663bbc7f366c9db6a9aeef5feb0f4cb5f2
src/ExampleNets/readAllFields.py
src/ExampleNets/readAllFields.py
import glob import os import SCIRunPythonAPI; from SCIRunPythonAPI import * def allFields(path): names = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith("fld"): names.append(os.path.join(dirname, filename)) return names dir = r"E:\scirun\trunk_ref\SCI...
import glob import os import time import SCIRunPythonAPI; from SCIRunPythonAPI import * def allFields(path): names = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith("fld"): names.append(os.path.join(dirname, filename)) return names def printList(list,...
Update script to print all field types to a file
Update script to print all field types to a file
Python
mit
moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,jcollfont/SCIRun,ajanson/SCIRun,jessdtate/SCIRun,ajanson/SCIRun,moritzdannhauer/SCIRunGUIPrototype,collint8/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,jessdtate/SCIRun,...
b1bd07038b0c6a6d801e686372996b3478c71af9
iss/management/commands/upsert_iss_organizations.py
iss/management/commands/upsert_iss_organizations.py
#!/usr/bin/env python """Upserts Organization records with data from Salesforce Accounts. """ import logging import os from django.core.management.base import BaseCommand import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): def add_argument...
#!/usr/bin/env python """Upserts Organization records with data from Salesforce Accounts. """ import logging import os from django.core.management.base import BaseCommand import iss.models import iss.salesforce import iss.utils logger = logging.getLogger(os.path.basename(__file__)) class Command(BaseCommand): ...
Add --include-aashe-in-website flag to org upsert
Add --include-aashe-in-website flag to org upsert
Python
mit
AASHE/iss
07f531c7e3bbc0149fad4cfda75d8803cbc48e1d
smserver/chatplugin.py
smserver/chatplugin.py
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ This module add the class needed for creating custom chat command :Example: Here's a simple ChatPlugin which will send a HelloWorld on use `` ChatHelloWorld(ChatPlugin): helper = "Display Hello World" cimmand def __call__...
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ This module add the class needed for creating custom chat command :Example: Here's a simple ChatPlugin which will send a HelloWorld on use `` ChatHelloWorld(ChatPlugin): helper = "Display Hello World" command = "hello" de...
Correct chat plugin example in docsctring
Correct chat plugin example in docsctring
Python
mit
ningirsu/stepmania-server,Nickito12/stepmania-server,ningirsu/stepmania-server,Nickito12/stepmania-server
83292a4b6f6bec00b20c623fa6f44e15aa82cd2a
runtests.py
runtests.py
#!/usr/bin/env python import sys from os.path import dirname, abspath import django from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'django.db.bac...
#!/usr/bin/env python import sys from os.path import dirname, abspath import django from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'django.db.bac...
Fix "AppRegistryNotReady: Models aren't loaded yet"
Fix "AppRegistryNotReady: Models aren't loaded yet"
Python
mit
coleifer/django-generic-m2m,coleifer/django-generic-m2m,coleifer/django-generic-m2m
e77042c914b9725da0fef7e56ede12635c1a876b
s3s3/api.py
s3s3/api.py
""" The API for s3s3. """ import tempfile from boto.s3.connection import S3Connection def create_connection(connection_args): connection_args = connection_args.copy() connection_args.pop('bucket_name') return S3Connection(**connection_args) def upload(source_key, dest_keys): """ `source_key` Th...
""" The API for s3s3. """ import tempfile from boto.s3.connection import S3Connection def create_connection(connection_args): connection_args = connection_args.copy() connection_args.pop('bucket_name') return S3Connection(**connection_args) def upload(source_key, dest_keys): """ `source_key` Th...
Fix typo. dest_key => dest_keys.
Fix typo. dest_key => dest_keys. modified: s3s3/api.py
Python
mit
lsst-sqre/s3s3,lsst-sqre/s3-glacier
ada7e2d2b98664fd6c481c4279677a4292e5bfef
openedx/features/idea/api_views.py
openedx/features/idea/api_views.py
from django.http import JsonResponse from django.shortcuts import get_object_or_404 from rest_framework import status from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from openedx.feature...
from django.http import JsonResponse from django.shortcuts import get_object_or_404 from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIVi...
Change authentication classes to cater inactive users
[LP-1965] Change authentication classes to cater inactive users
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
d6782066e3ed3f00e3c8dcffe2ffd0b9bad18d17
slave/skia_slave_scripts/render_pdfs.py
slave/skia_slave_scripts/render_pdfs.py
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia render_pdfs executable. """ from build_step import BuildStep, BuildStepWarning import sys class RenderPdfs(Bu...
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia render_pdfs executable. """ from build_step import BuildStep import sys class RenderPdfs(BuildStep): def _R...
Revert "Skip RenderPdfs until the crash is fixed"
Revert "Skip RenderPdfs until the crash is fixed" This reverts commit fd03af0fbcb5f1b3656bcc78d934c560816d6810. https://codereview.chromium.org/15002002/ fixes the crash. R=borenet@google.com Review URL: https://codereview.chromium.org/14577010 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9019 2bbb7eff-a52...
Python
bsd-3-clause
Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbo...
bf91e50b02ff8ef89e660e3c853cc2f30646f32d
bash_runner/tasks.py
bash_runner/tasks.py
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
Change the status string in riemann
Change the status string in riemann
Python
apache-2.0
rantav/cosmo-plugin-bash-runner
c568cf4b1be5e38b92f7d3a9131e67ff9eff764e
lib/ctf_gameserver/lib/helper.py
lib/ctf_gameserver/lib/helper.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- def convert_arg_line_to_args(arg_line): """argparse helper for splitting input from config Allows comment lines in configfiles and allows both argument and value on the same line """ if arg_line.strip().startswith('#'): return [] else: ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import shlex def convert_arg_line_to_args(arg_line): """argparse helper for splitting input from config Allows comment lines in configfiles and allows both argument and value on the same line """ return shlex.split(arg_line, comments=True)
Improve config argument splitting to allow quoted spaces
Improve config argument splitting to allow quoted spaces
Python
isc
fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver
a234b8dfc45d9e08a452ccc4f275283eb1eb5485
dataactbroker/scripts/loadFSRS.py
dataactbroker/scripts/loadFSRS.py
import logging import sys from dataactcore.models.baseInterface import databaseSession from dataactbroker.fsrs import ( configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT) logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) with databaseSession() a...
import logging import sys from dataactcore.interfaces.db import databaseSession from dataactbroker.fsrs import ( configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT) logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) with databaseSession() as sess:...
Switch to using dbSession in db.py instead of baseInterface.py
Switch to using dbSession in db.py instead of baseInterface.py This is another file that should have been included in PR #272, where we transitioned all existing non-Flask db access to a db connection using the new contextmanager. Originally missed this one because it *is* using a contextmanager, but it's using one in...
Python
cc0-1.0
fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend
0022726e9f2d122ff84eb19ed2807649ab96f931
deployment/cfn/utils/constants.py
deployment/cfn/utils/constants.py
EC2_INSTANCE_TYPES = [ 't2.micro', 't2.small', 't2.medium', 't2.large' ] RDS_INSTANCE_TYPES = [ 'db.t2.micro', 'db.t2.small', 'db.t2.medium', 'db.t2.large' ] ALLOW_ALL_CIDR = '0.0.0.0/0' VPC_CIDR = '10.0.0.0/16' HTTP = 80 HTTPS = 443 POSTGRESQL = 5432 SSH = 22 AMAZON_ACCOUNT_ID = 'am...
EC2_INSTANCE_TYPES = [ 't2.micro', 't2.small', 't2.medium', 't2.large', 'm3.medium' ] RDS_INSTANCE_TYPES = [ 'db.t2.micro', 'db.t2.small', 'db.t2.medium', 'db.t2.large' ] ALLOW_ALL_CIDR = '0.0.0.0/0' VPC_CIDR = '10.0.0.0/16' HTTP = 80 HTTPS = 443 POSTGRESQL = 5432 SSH = 22 AMAZON...
Add m3.medium to EC2 instance types
Add m3.medium to EC2 instance types This is the lowest `m3` family instance type with ephemeral storage.
Python
apache-2.0
azavea/raster-foundry,aaronxsu/raster-foundry,kdeloach/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,kdeloach/raster-foundry,raster-foundry/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,kdeloach/raster-foundry,kdeloa...
4d5d4665f2b46e12618b7762246d84884447e99e
redash/cli/organization.py
redash/cli/organization.py
from flask_script import Manager from redash import models manager = Manager(help="Organization management commands.") @manager.option('domains', help="comma separated list of domains to allow") def set_google_apps_domains(domains): organization = models.Organization.select().first() organization.settings[m...
from flask_script import Manager from redash import models manager = Manager(help="Organization management commands.") @manager.option('domains', help="comma separated list of domains to allow") def set_google_apps_domains(domains): organization = models.Organization.select().first() organization.settings[m...
Add 'manage.py org list' command
Add 'manage.py org list' command 'org list' simply prints out the organizations.
Python
bsd-2-clause
pubnative/redash,pubnative/redash,pubnative/redash,pubnative/redash,pubnative/redash
c23cd25247974abc85c66451737f4de8d8b19d1b
lib/rapidsms/backends/backend.py
lib/rapidsms/backends/backend.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 class Backend(object): def log(self, level, message): self.router.log(level, message) def start(self): raise NotImplementedError def stop(self): raise NotImplementedError def send(self): raise NotImpleme...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 class Backend(object): def __init__ (self, router): self.router = router def log(self, level, message): self.router.log(level, message) def start(self): raise NotImplementedError def stop(self): raise NotImple...
Add a constructor method for Backend
Add a constructor method for Backend
Python
bsd-3-clause
dimagi/rapidsms,ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,ken-muturi/rapidsms,lsgunth/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,catalpainternational/rapidsms,eHealthAfrica/rapidsms,ken-muturi/rapidsms,ken-muturi/rapidsms,lsgunth/rapidsms,unicefuganda/edtrac,lsgunth/rapidsms,ehealthafrica-ci/rapi...
7a37e3afa29410636c75408bc649e70c519e07f1
test/user_profile_test.py
test/user_profile_test.py
import json from pymessenger.user_profile import UserProfileApi from test_env import * upa = UserProfileApi(PAGE_ACCESS_TOKEN, app_secret=APP_SECRET) def test_fields_blank(): user_profile = upa.get(TEST_USER_ID) assert user_profile is not None def test_fields(): fields = ['first_name', 'last_name'] ...
import json import sys, os sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/..")) from pymessenger.user_profile import UserProfileApi TOKEN = os.environ.get('TOKEN') APP_SECRET = os.environ.get('APP_SECRET') TEST_USER_ID = os.environ.get('RECIPIENT_ID') upa = UserProfileApi(TOKEN, app_secret=APP_SECRET) ...
Fix user profile test to include same environment variables
Fix user profile test to include same environment variables
Python
mit
karlinnolabs/pymessenger,Cretezy/pymessenger2,davidchua/pymessenger
2fec4b3ffa1619f81088383c9f565b51f6171fd6
seaborn/miscplot.py
seaborn/miscplot.py
from __future__ import division import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt __all__ = ["palplot", "dogplot"] def palplot(pal, size=1): """Plot the values in a color palette as a horizontal array. Parameters ---------- pal : sequence of matplotlib colors color...
from __future__ import division import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt __all__ = ["palplot", "dogplot"] def palplot(pal, size=1): """Plot the values in a color palette as a horizontal array. Parameters ---------- pal : sequence of matplotlib colors color...
Update to reflect new example data
Update to reflect new example data
Python
bsd-3-clause
arokem/seaborn,mwaskom/seaborn,anntzer/seaborn,arokem/seaborn,mwaskom/seaborn,anntzer/seaborn
a4c5e9a970a297d59000468dde8423fa9db00c0f
packs/fixtures/actions/scripts/streamwriter-script.py
packs/fixtures/actions/scripts/streamwriter-script.py
#!/usr/bin/env python import argparse import sys import ast from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'STDERR': ...
#!/usr/bin/env python import argparse import sys import ast import re from lib.exceptions import CustomException class StreamWriter(object): def run(self, stream): if stream.upper() == 'STDOUT': sys.stdout.write('STREAM IS STDOUT.') return stream if stream.upper() == 'S...
Fix streamwriter action so it doesn't include "u" type prefix in the object result.
Fix streamwriter action so it doesn't include "u" type prefix in the object result. This way it works consistently and correctly under Python 2 and Python 3.
Python
apache-2.0
StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests
0fa23851cbe33ba0d3bddb8367d7089545de6847
setup.py
setup.py
#! /usr/bin/env python from distutils.core import setup setup( name = 'qless-py', version = '0.10.0', description = 'Redis-based Queue Management', long_description = ''' Redis-based queue management, with heartbeating, job tracking, stats, notifications, and ...
#! /usr/bin/env python from distutils.core import setup setup( name = 'qless-py', version = '0.10.0', description = 'Redis-based Queue Management', long_description = ''' Redis-based queue management, with heartbeating, job tracking, stats, notifications, and ...
Fix for "No module named decorator" on fresh environment installs.
Fix for "No module named decorator" on fresh environment installs. Fixes regression from 4b26b5837ced0c2f76495b05b87e63e05f81c2af.
Python
mit
seomoz/qless-py,seomoz/qless-py
5476145559e0e47dac47b41dd4bfdb9fd41bfe29
setup.py
setup.py
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" from distutils.core import setup from pyparsing import __version__ setup(# Distribution meta-data name = "pyparsing", version = __version__, description = "Python parsing module", author = "Paul McGuire", author_...
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" from distutils.core import setup from pyparsing import __version__ setup(# Distribution meta-data name = "pyparsing", version = __version__, description = "Python parsing module", author = "Paul McGuire", ...
Add change to ship both pyparsing and pyparsing_py3 modules.
Add change to ship both pyparsing and pyparsing_py3 modules.
Python
mit
5monkeys/pyparsing
af1d3b67bb6428a298e5028b7c86624d2f7f00c8
setup.py
setup.py
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run th...
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run th...
Add rst long description for pypi
Add rst long description for pypi
Python
isc
miedzinski/steamodd,Lagg/steamodd
d815c8de309239e3c6f28e54793c9973ca9acc39
twilio/values.py
twilio/values.py
unset = object() def of(d): return {k: v for k, v in d.iteritems() if v != unset}
from six import iteritems unset = object() def of(d): return {k: v for k, v in iteritems(d) if v != unset}
Replace iteritems with six helper
Replace iteritems with six helper
Python
mit
twilio/twilio-python,tysonholub/twilio-python
2989c7074853266fd134a10df4afdcb700499203
analyticsdataserver/urls.py
analyticsdataserver/urls.py
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from analyticsdataserver import views urlpatterns = [ url(r'^$', RedirectView.as_view(url='/docs')), # pylint: disable=no-value-for-parameter url(r'^api-a...
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from analyticsdataserver import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ url(r'^$', RedirectView.as_view(url='/docs'))...
Update string arg to url() to callable
Update string arg to url() to callable
Python
agpl-3.0
Stanford-Online/edx-analytics-data-api,edx/edx-analytics-data-api,Stanford-Online/edx-analytics-data-api,edx/edx-analytics-data-api,Stanford-Online/edx-analytics-data-api
ef516fb03db9bdaa0f0bea97526a65c319b8e43c
tohu/v3/utils.py
tohu/v3/utils.py
from collections import namedtuple __all__ = ['identity', 'print_generated_sequence'] def identity(x): """ Helper function which returns its argument unchanged. That is, `identity(x)` returns `x` for any input `x`. """ return x def print_generated_sequence(gen, num, *, sep=", ", seed=None): ...
from collections import namedtuple __all__ = ['identity', 'print_generated_sequence'] def identity(x): """ Helper function which returns its argument unchanged. That is, `identity(x)` returns `x` for any input `x`. """ return x def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=No...
Allow passing format option to helper function
Allow passing format option to helper function
Python
mit
maxalbert/tohu
f12beb5d2fbdc72c12f473c5cac04716f4893666
test/viz/test_volcano.py
test/viz/test_volcano.py
from sequana.viz import Volcano def test1(): import numpy as np fc = np.random.randn(1000) pvalue = np.random.randn(1000) v = Volcano(fc, -np.log10(pvalue**2), pvalue_threshold=3) v.plot() v.plot(logy=True)
from sequana.viz import Volcano import pandas as pd def test1(): import numpy as np fc = np.random.randn(1000) pvalue = np.random.randn(1000) df = pd.DataFrame({"log2FoldChange": fc, "padj": pvalue ** 2}) v = Volcano(data=df, pvalue_threshold=3) v.plot() v.plot(logy=True)
Update test for volcano plot
Update test for volcano plot
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
3d1969ebf187ed0f0ee52e84e951f65b108ce4cf
l10n_br_coa_simple/hooks.py
l10n_br_coa_simple/hooks.py
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_simple_tmpl = env.ref( 'l10n_br_co...
# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, tools, SUPERUSER_ID def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) coa_simple_tmpl = env.ref( 'l10n_br_co...
Use admin user to create COA
[FIX] l10n_br_coa_simple: Use admin user to create COA
Python
agpl-3.0
akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil
f43f71cb016bc71ea32e80c2fd86f05b6af38468
snoop/ipython.py
snoop/ipython.py
import ast from snoop import snoop from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): filename = self.shell.compile.cache(cell) code = self.shell.compile(cell, filename, 'exec') tracer = sn...
import ast from snoop import snoop from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): filename = self.shell.compile.cache(cell) code = self.shell.compile(cell, filename, 'exec') tracer = sn...
Hide modules from variables traced by %%snoop
Hide modules from variables traced by %%snoop
Python
mit
alexmojaki/snoop,alexmojaki/snoop
e63a914457fc10d895eb776a164939da3ddd9464
waftools/gogobject.py
waftools/gogobject.py
from waflib.Task import Task from waflib.TaskGen import extension class gogobject(Task): run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}' @extension('.go.in') def gogobject_hook(self, node): tg = self.bld.get_tgen_by_name('go-gobject-gen') ggg = tg.link_task.outputs[0] if not self.env.GGG: s...
from waflib.Task import Task from waflib.TaskGen import extension class gogobject(Task): run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}' @extension('.go.in') def gogobject_hook(self, node): tg = self.bld.get_tgen_by_name('go-gobject-gen') ggg = tg.link_task.outputs[0] if not self.env.GGG: s...
Use config.json as a go-gobject-gen dependency as well.
Use config.json as a go-gobject-gen dependency as well.
Python
mit
nsf/gogobject,nsf/gogobject,nsf/gogobject,nsf/gogobject
ef048131d586812c2d73edd6297dfae4305b6074
website/exceptions.py
website/exceptions.py
class OSFError(Exception): """Base class for exceptions raised by the Osf application""" pass class NodeError(OSFError): """Raised when an action cannot be performed on a Node model""" pass class NodeStateError(NodeError): """Raised when the Node's state is not suitable for the requested action ...
class OSFError(Exception): """Base class for exceptions raised by the Osf application""" pass class NodeError(OSFError): """Raised when an action cannot be performed on a Node model""" pass class NodeStateError(NodeError): """Raised when the Node's state is not suitable for the requested action ...
Update Sanction exception error message and docstrings
Update Sanction exception error message and docstrings
Python
apache-2.0
alexschiller/osf.io,amyshi188/osf.io,felliott/osf.io,cwisecarver/osf.io,ckc6cz/osf.io,TomBaxter/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,RomanZWang/osf.io,doublebits/osf.io,adlius/osf.io,ticklemepierce/osf.io,danielneis/osf.io,samchrisinger/osf.io,baylee-d/osf.io,sloria/osf.io,asanfilippo7/osf.io,R...
04807105282211ff4ad79e8b4e9b13442e083c86
planex_globals.py
planex_globals.py
import os.path BUILD_ROOT_DIR = "planex-build-root" [SPECS_DIR, SOURCES_DIR, SRPMS_DIR, RPMS_DIR, BUILD_DIR] = map( lambda x: os.path.join(BUILD_ROOT_DIR, x), ['SPECS', 'SOURCES', 'SRPMS', 'RPMS', 'BUILD']) SPECS_GLOB = os.path.join(SPECS_DIR, "*.spec")
import os.path BUILD_ROOT_DIR = "planex-build-root" [SPECS_DIR, SOURCES_DIR, SRPMS_DIR, RPMS_DIR, BUILD_DIR] = [ os.path.join(BUILD_ROOT_DIR, dir_name) for dir_name in ['SPECS', 'SOURCES', 'SRPMS', 'RPMS', 'BUILD']] SPECS_GLOB = os.path.join(SPECS_DIR, "*.spec")
Replace deprecated 'map' builtin with list comprehension
globals: Replace deprecated 'map' builtin with list comprehension Signed-off-by: Euan Harris <c3b6e83069c8e9e3af49a38fec6026be89559638@citrix.com>
Python
lgpl-2.1
djs55/planex,jonludlam/planex,djs55/planex,simonjbeaumont/planex,euanh/planex-cleanhistory,euanh/planex-cleanhistory,simonjbeaumont/planex,djs55/planex,jonludlam/planex,jonludlam/planex,simonjbeaumont/planex,euanh/planex-cleanhistory
42a4d5959524875fd39c190f6119eb06a97eabf2
build/setenv.py
build/setenv.py
import os,sys #General vars CURDIR=os.path.dirname(os.path.abspath(__file__)) TOPDIR=os.path.dirname(CURDIR) DOWNLOAD_DIR=TOPDIR+'\\downloads' #Default vars PY_VER='Python27' BIN_DIR=TOPDIR+'\\bin' PY_DIR=BIN_DIR+'\\'+PY_VER #Don't mess with PYTHONHOME ####################################################...
import os,sys #General vars CURDIR=os.path.dirname(os.path.abspath(__file__)) TOPDIR=os.path.dirname(os.path.dirname(CURDIR)) DOWNLOAD_DIR=os.path.join(TOPDIR,'downloads') #Default vars PY_VER='Python27' BIN_DIR=os.path.join(TOPDIR,'bin') PY_DIR=os.path.join(BIN_DIR,PY_VER) #Don't mess with PYTHONHOME ##...
Change path following import of build folder
Change path following import of build folder
Python
mit
lpinner/metageta
cdc4f79210b69f131926374aff61be72ab573c46
scripts/import_queued_submissions.py
scripts/import_queued_submissions.py
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script from acoustid.data.submission import import_queued_submissions def main(script, opts, args): conn = script.engine.connect() with conn.begin(...
#!/usr/bin/env python # Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. from acoustid.script import run_script from acoustid.data.submission import import_queued_submissions def main(script, opts, args): conn = script.engine.connect() with conn.begin(...
Raise the import batch size to 100
Raise the import batch size to 100
Python
mit
lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server
bebb1d9bc44300e7c65fba90d6c2eb76243ea372
scripts/cm2lut.py
scripts/cm2lut.py
#!/usr/bin/env python """ Script used to create lut lists used by mayavi from matplotlib colormaps. This requires matlplotlib to be installed and should not be ran by the user, but only once in a while to synchronize with MPL developpement. """ # Authors: Frederic Petit <fredmfp@gmail.com>, # Gael Varoquaux <...
#!/usr/bin/env python """ Script used to create lut lists used by mayavi from matplotlib colormaps. This requires matlplotlib to be installed and should not be ran by the user, but only once in a while to synchronize with MPL developpement. """ # Authors: Frederic Petit <fredmfp@gmail.com>, # Gael Varoquaux <...
Add a modified lut-data-generating script to use pickle, rather than npz
ENH: Add a modified lut-data-generating script to use pickle, rather than npz
Python
bsd-3-clause
dmsurti/mayavi,liulion/mayavi,alexandreleroux/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,liulion/mayavi
fece0019a54534b56960a30785bb70edb5d205bf
example_base/forms.py
example_base/forms.py
# -*- encoding: utf-8 -*- from base.form_utils import RequiredFieldForm from .models import Document from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): ...
# -*- encoding: utf-8 -*- from django import forms from base.form_utils import RequiredFieldForm, FileDropInput from .models import Document class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): ...
Add examples of ways to use FileDropInput
Add examples of ways to use FileDropInput
Python
apache-2.0
pkimber/base,pkimber/base,pkimber/base,pkimber/base
1e17e868ff332003da959a397b8846c9386b35e8
API_to_backend.py
API_to_backend.py
from multiprocessing import Queue, Process import time import backend command_queue = Queue() response_queue = Queue() def start_backend(): if handler: handler.stop() handler = Process(target=backend.start, args=(command_queue, response_queue)) handler.start() def get_for(url, queue, timeout): ...
from multiprocessing import Queue, Process import time import backend command_queue = Queue() response_queue = Queue() def start_backend(): handler = Process(target=backend.start, args=(command_queue, response_queue)) handler.start() def get_for(url, queue, timeout): beginning = time.time() result =...
Revert "Quit Backend If Running"
Revert "Quit Backend If Running" This reverts commit a00432191e2575aba0f20ffb1a96a323699ae4fc.
Python
mit
IAPark/PITherm
7c18cbf6dced0435537fb4067dfa878ae9ccc6af
accounts/models.py
accounts/models.py
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User) def __str__(self): return self.user.get_full_name() or self.user.username
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User) def __str__(self): return self.user.get_full_name() or self.user.username def create_user_profile(sender, instance, ...
Create profile if user is created
Create profile if user is created
Python
mit
lockhawksp/beethoven,lockhawksp/beethoven
6034265dfdfb2a7e1e4881076cc0f011ff0e639d
netbox/extras/migrations/0022_custom_links.py
netbox/extras/migrations/0022_custom_links.py
# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to_tag'), ] op...
# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion import extras.models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to...
Add limit_choices_to to CustomLink.content_type field
Add limit_choices_to to CustomLink.content_type field
Python
apache-2.0
lampwins/netbox,lampwins/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,lampwins/netbox,lampwins/netbox,digitalocean/netbox
32f38eb01c3a203ae35d70b485fcee7b13f1acde
tests/help_generation_test.py
tests/help_generation_test.py
# Copyright 2016 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Copyright 2016 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
Call FLAGS.get_help if it's available.
Call FLAGS.get_help if it's available.
Python
apache-2.0
GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker
d8c15667e76ce6d0dfa96a16312e75b83c63479b
tests/test_response.py
tests/test_response.py
"""Unit test some basic response rendering functionality. These tests use the unittest.mock mechanism to provide a simple Assistant instance for the _Response initialization. """ from unittest.mock import patch from flask import Flask from flask_assistant import Assistant from flask_assistant.response import _Respons...
"""Unit test some basic response rendering functionality. These tests use the unittest.mock mechanism to provide a simple Assistant instance for the _Response initialization. """ from flask import Flask from flask_assistant import Assistant from flask_assistant.response import _Response import pytest patch = pytest.i...
Disable test for py27 (mock not available)
Disable test for py27 (mock not available)
Python
apache-2.0
treethought/flask-assistant
4b578fb7683054727444f1ed5c2a7d9732a3d8e9
ci_scripts/installPandoc.py
ci_scripts/installPandoc.py
import os from subprocess import call, check_output import sys from shutil import copy2 platform = sys.platform def checkAndInstall(): try: check_output('pandoc -v'.split()) except OSError: cudir = os.path.abspath(os.curdir) os.chdir(os.path.abspath(os.path.join(os.path.pardir, 'downl...
import os from subprocess import call, check_output import sys from shutil import copy2 platform = sys.platform def checkAndInstall(): try: check_output('pandoc -v'.split()) except OSError: def getFile(): from requests import get with open(pandocFile, "wb") as file: ...
Fix build wheels with Pandoc 2.
Fix build wheels with Pandoc 2.
Python
bsd-3-clause
jr-garcia/AssimpCy,jr-garcia/AssimpCy
afa94ea297c6042f4444c0ce833c9b1ee02373c1
stowaway.py
stowaway.py
import time import socket import datetime from ipaddress import ip_address import zmq import yaml import quick2wire.i2c as i2c from database import Writer from database import Temperature, Base if __name__ == '__main__': context = zmq.Context() publisher = context.socket(zmq.PUB) database = context.soc...
import time import socket import datetime from ipaddress import ip_address import zmq import yaml import quick2wire.i2c as i2c from database import Writer from database import Temperature, Base if __name__ == '__main__': context = zmq.Context() publisher = context.socket(zmq.PUB) database = context.soc...
Send timestamp to the outside world
Send timestamp to the outside world
Python
bsd-3-clause
CojoCompany/stowaway
34369635a22bf05abbabe47e708a2ed80db258e5
MeetingMinutes.py
MeetingMinutes.py
import sublime, sublime_plugin from .mistune import markdown class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='strict') html_source = '<!DOCTYPE html><html><hea...
import sublime, sublime_plugin import os import re from subprocess import call from .mistune import markdown class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='s...
Save the created html in a HTML file.
Save the created html in a HTML file.
Python
mit
Txarli/sublimetext-meeting-minutes,Txarli/sublimetext-meeting-minutes
fbad1649e9939a3be4194e0d508ff5889f48bb6f
unleash/plugins/utils_assign.py
unleash/plugins/utils_assign.py
import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. :param data: Source to search in. ...
from unleash.exc import PluginError import re # regular expression for finding assignments _quotes = "['|\"|\"\"\"]" BASE_ASSIGN_PATTERN = r'({}\s*=\s*[ubr]?' + _quotes + r')(.*?)(' +\ _quotes + r')' def find_assign(data, varname): """Finds a substring that looks like an assignment. ...
Raise PluginErrors instead of ValueErrors in versions.
Raise PluginErrors instead of ValueErrors in versions.
Python
mit
mbr/unleash
f339af2e48f0e485f13d368dad47f541264c4f58
web/processors/user.py
web/processors/user.py
from django.contrib.auth.models import User from django_countries import countries def get_user(user_id): user = User.objects.get(id=user_id) return user def get_user_profile(user_id): user = User.objects.get(id=user_id) return user.profile def get_ambassadors(): ambassadors = [] aambassadors = Use...
from django.contrib.auth.models import User from django_countries import countries def get_user(user_id): user = User.objects.get(id=user_id) return user def get_user_profile(user_id): user = User.objects.get(id=user_id) return user.profile def get_ambassadors(): ambassadors = [] aambassadors = Use...
Sort listed ambassadors by date_joined
Sort listed ambassadors by date_joined
Python
mit
ercchy/coding-events,michelesr/coding-events,joseihf/coding-events,ioana-chiorean/coding-events,joseihf/coding-events,codeeu/coding-events,michelesr/coding-events,joseihf/coding-events,ercchy/coding-events,codeeu/coding-events,ercchy/coding-events,michelesr/coding-events,ioana-chiorean/coding-events,codeeu/coding-event...
bb2234447039df6bee80842749b0ecdb19fb62fc
aerende/models.py
aerende/models.py
import uuid class Note(object): """ A note. Currently has a title, tags, texr and a priority.""" def __init__(self, title, tags, text, priority=1, unique_id=None): if unique_id is None: self.id = str(uuid.uuid4()) else: self.id = unique_id self.title = ...
import uuid class Note(object): """ A note. Currently has a title, tags, texr and a priority.""" def __init__(self, title, tags, text, priority=1, unique_id=None): if unique_id is None: self.id = str(uuid.uuid4()) else: self.id = unique_id self.title = ...
Remove duplicate tags during init
Remove duplicate tags during init
Python
mit
Autophagy/aerende
83919e74b7d20688811a4f782d4fccaf3bc3c055
comics/comics/hijinksensue.py
comics/comics/hijinksensue.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" class Crawler(CrawlerBase): ...
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "HijiNKS Ensue" language = "en" url = "http://hijinksensue.com/" start_date = "2007-05-11" rights = "Joel Watson" active = False class Crawl...
Update "HijiNKS Ensue" after feed change
Update "HijiNKS Ensue" after feed change
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics
7e025a5fa40d5f7ba5721ad01951ad2020ed2485
phoxpy/tests/test_client.py
phoxpy/tests/test_client.py
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import unittest from phoxpy import client from phoxpy.tests.lisserver import MockHttpSession class Ses...
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Alexander Shorin # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import unittest from phoxpy import client from phoxpy.server import MockHttpSession, SimpleLISServer ...
Update tests for new environment.
Update tests for new environment.
Python
bsd-3-clause
kxepal/phoxpy
20b13d500ea1cfa4b06413f0f02114bed60ca98f
apps/challenges/auth.py
apps/challenges/auth.py
OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']] class SubmissionBackend(object): """Provide custom permission logic for submissions.""" supports_object_permissions = True supports_anonymous_user = True def authenticate(self): """This backend doesn't pr...
OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']] class SubmissionBackend(object): """Provide custom permission logic for submissions.""" supports_object_permissions = True supports_anonymous_user = True def authenticate(self): """This backend doesn't pr...
Remove 'is_live' from draft visibility check.
Remove 'is_live' from draft visibility check.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
ba4c2dc22aae5dd4f862aad7c388eecf36acfbd8
app/main/forms.py
app/main/forms.py
from flask_wtf import Form from wtforms.validators import DataRequired, Email from dmutils.forms import StripWhitespaceStringField class EmailAddressForm(Form): email_address = StripWhitespaceStringField('Email address', validators=[ DataRequired(message="Email can not be empty"), Email(message="P...
from flask_wtf import Form from wtforms import validators from dmutils.forms import StripWhitespaceStringField class EmailAddressForm(Form): email_address = StripWhitespaceStringField('Email address', validators=[ validators.DataRequired(message="Email can not be empty"), validators.Email(message...
Change import to indicate function of imported classes
Change import to indicate function of imported classes
Python
mit
alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
b167b1c8099dc184c366416dab9a7c6e5be7423a
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.view...
Handle cases where there are multiple values for a field.
Handle cases where there are multiple values for a field.
Python
apache-2.0
Ghalko/osf.io,caneruguz/osf.io,felliott/osf.io,binoculars/osf.io,icereval/osf.io,ticklemepierce/osf.io,caneruguz/osf.io,mattclark/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,laurenrevere/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,caseyrygt/osf.io,doublebits/osf.io,Nesiehr/osf.io,kch8qx/osf.io,acs...
0155ed7c37fd4cafa2650911d4f902a3a8982761
test/test_bot.py
test/test_bot.py
import re import unittest from gather.bot import ListenerBot class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = unittest.mock.Mock() bot.register_action(regex, action) self...
import asyncio import re import unittest from unittest import mock from gather.bot import ListenerBot def async_test(f): # http://stackoverflow.com/a/23036785/304210 def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop()...
Add a test for on_message
Add a test for on_message
Python
mit
veryhappythings/discord-gather
158f1101c3c13db5df916329a66517c7bb85e132
plata/context_processors.py
plata/context_processors.py
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_inclu...
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_inclu...
Add current value for price_includes_tax to context
Add current value for price_includes_tax to context
Python
bsd-3-clause
armicron/plata,armicron/plata,armicron/plata
22c7da6d3de76cf6c36b4206f204a9ee979ba5f7
strides/graphs.py
strides/graphs.py
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys import os.path figdir = "figures" df = pd.read_csv(sys.stdin, " ", header=None, index_col=0, names=[2**(i) for i in range(6)]+["rand"]) print(df) #print(df["X2"]/2**df.index) df.plot(logy=True) plt....
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) print(df) print(df["X2"]/2**df.index) df.plot(logy=True) plt.savefig("graph.pdf")
Add perelement figures write figures into subdirectory
Add perelement figures write figures into subdirectory
Python
bsd-3-clause
jpfairbanks/cse6140,jpfairbanks/cse6140,jpfairbanks/cse6140
1579eb8d2de5aa49ad7012ab08350659a20725e1
basis/managers.py
basis/managers.py
from django.db import models class BasisModelManager(models.Manager): def get_query_set(self): return super(BasisModelManager, self).get_query_set().filter(deleted=False)
from django.db import models from .compat import DJANGO16 if DJANGO16: class BasisModelManager(models.Manager): def get_queryset(self): return super(BasisModelManager, self).get_queryset().filter(deleted=False) else: class BasisModelManager(models.Manager): def get_query_set(self):...
Fix deprecation warning for get_query_set
Fix deprecation warning for get_query_set get_query_set was renamed get_queryset in django 1.6
Python
mit
frecar/django-basis
4b000960edc30d9917b80646a0374fb8bf99efcb
storage/tests/testtools.py
storage/tests/testtools.py
""" Test tools for the storage service. """ import unittest from storage.storage import app as storage_app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): storage_app.config['TESTING'] = ...
""" Test tools for the storage service. """ import unittest from storage.storage import app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): app.config['TESTING'] = True app.config...
Remove unnecessary rename on input
Remove unnecessary rename on input
Python
mit
jenca-cloud/jenca-authentication
505456fed7bdbd6b2cd78eae10b3b64657cd377b
tests/unit/test_commands.py
tests/unit/test_commands.py
import pytest from pip._internal.commands import commands_dict, create_command def test_commands_dict__order(): """ Check the ordering of commands_dict. """ names = list(commands_dict) # A spot-check is sufficient to check that commands_dict encodes an # ordering. assert names[0] == 'inst...
import pytest from pip._internal.cli.req_command import ( IndexGroupCommand, RequirementCommand, SessionCommandMixin, ) from pip._internal.commands import commands_dict, create_command def check_commands(pred, expected): """ Check the commands satisfying a predicate. """ commands = [creat...
Test the command class inheritance for each command.
Test the command class inheritance for each command.
Python
mit
pradyunsg/pip,xavfernandez/pip,pfmoore/pip,rouge8/pip,xavfernandez/pip,pypa/pip,sbidoul/pip,pfmoore/pip,pypa/pip,rouge8/pip,rouge8/pip,pradyunsg/pip,xavfernandez/pip,sbidoul/pip
e183578b6211d7311d62100ad643cbaf8408de99
tests/__init__.py
tests/__init__.py
import unittest.mock def _test_module_init(module, main_name="main"): with unittest.mock.patch.object(module, main_name, return_value=0): with unittest.mock.patch.object(module, "__name__", "__main__"): with unittest.mock.patch.object(module.sys, "exit") as exit: module.module_...
import unittest.mock def _test_module_init(module, main_name="main"): with unittest.mock.patch.object( module, main_name, return_value=0 ), unittest.mock.patch.object( module, "__name__", "__main__" ), unittest.mock.patch.object( module.sys, "exit" ) as exit: module.mod...
Use multiple context managers on one with statement (thanks Anna)
Use multiple context managers on one with statement (thanks Anna)
Python
mpl-2.0
rfinnie/2ping,rfinnie/2ping
d96e52c346314622afc904a2917416028c6784e3
swampdragon_live/models.py
swampdragon_live/models.py
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from .tasks import push_new_content @receiver(post_save) def post_save_handler(sender, instance, **kwargs): instance_type = ContentType.objects.get_...
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from .tasks import push_new_content @receiver(post_save) def post_save_handler(sender, instance, **kwargs): if ContentType.objects.exists(): ...
Fix initial migration until ContentType is available
Fix initial migration until ContentType is available
Python
mit
mback2k/swampdragon-live,mback2k/swampdragon-live
1c2b6c0daea1d04985ef6ddff35527ba207ec191
qual/tests/test_calendar.py
qual/tests/test_calendar.py
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
Check that a certain date is invalid.
Check that a certain date is invalid. This distinguishes correctly between the proleptic Gregorian calendar, and the historical or astronomical calendars, where this date would be valid.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
e50655479c0d3a96edd4005f834541889839fca3
binary_to_text.py
binary_to_text.py
#! /usr/bin/env python import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys def binary_to_text(binary_file, text_file): msg = pb2.NetParameter() with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.M...
#! /usr/bin/env python import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys class ParameterTypeException(Exception): pass def binary_to_text(binary_file, text_file, parameter_type): if (parameter_type == "Net"): msg = pb2.NetParameter() elif (parameter_type == "Solver...
Add option to process SolverParameters.
Add option to process SolverParameters.
Python
bsd-3-clause
BeautifulDestinations/dnngraph,BeautifulDestinations/dnngraph
86ac48a3dcb71a4e504dcf04e30a00262d168e5f
test/parseJaguar.py
test/parseJaguar.py
import os from cclib.parser import Jaguar os.chdir(os.path.join("..","data","Jaguar","basicJaguar")) os.chdir("eg01") for file in ["dvb_gopt.out"]: t = Jaguar(file) t.parse() print t.moenergies[0,:] print t.homos[0] print t.moenergies[0,t.homos[0]]
import os from cclib.parser import Jaguar os.chdir(os.path.join("..","data","Jaguar","basicJaguar")) files = [ ["eg01","dvb_gopt.out"], ["eg02","dvb_sp.out"], ["eg03","dvb_ir.out"], ["eg06","dvb_un_sp.out"] ] for f in files: t = Jaguar(os.path.join(f[0],f[1])) t.pars...
Test the parsing of all of the uploaded Jaguar files
Test the parsing of all of the uploaded Jaguar files
Python
bsd-3-clause
jchodera/cclib,ben-albrecht/cclib,Schamnad/cclib,cclib/cclib,berquist/cclib,jchodera/cclib,berquist/cclib,gaursagar/cclib,ben-albrecht/cclib,Clyde-fare/cclib,andersx/cclib,berquist/cclib,andersx/cclib,gaursagar/cclib,ATenderholt/cclib,ghutchis/cclib,Schamnad/cclib,cclib/cclib,langner/cclib,cclib/cclib,Clyde-fare/cclib,...
651663d2af72f46e7952d2835126f1512741f635
UserInput.py
UserInput.py
"""Like the raw_input built-in, but with bells and whistles.""" import getpass def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False): """Prompt user for input until a value is retrieved or default is accepted. Return the input. Arguments: field Descript...
"""Like the input built-in, but with bells and whistles.""" import getpass # Use raw_input for Python 2.x try: input = raw_input except NameError: pass def user_input(field, default='', choices=None, password=False, empty_ok=False, accept=False): """Prompt user for input until a value is retrieved or def...
Fix for Python 2.6 and Python 3.
Fix for Python 2.6 and Python 3.
Python
mit
vmlaker/coils
58fc39ae95522ce152b4ff137071f74c5490e14e
chatterbot/constants.py
chatterbot/constants.py
""" ChatterBot constants """ ''' The maximum length of characters that the text of a statement can contain. This should be enforced on a per-model basis by the data model for each storage adapter. ''' STATEMENT_TEXT_MAX_LENGTH = 400 ''' The maximum length of characters that the text label of a conversation can contai...
""" ChatterBot constants """ ''' The maximum length of characters that the text of a statement can contain. The number 255 is used because that is the maximum length of a char field in most databases. This value should be enforced on a per-model basis by the data model for each storage adapter. ''' STATEMENT_TEXT_MAX_...
Change statement text max-length to 255
Change statement text max-length to 255
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
27021bfa7062219a41ad29c40b97643ecf16f72b
doc/mkapidoc.py
doc/mkapidoc.py
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Gen...
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Gen...
Hide AbstractMethod class from the docs.
Hide AbstractMethod class from the docs.
Python
mit
knipknap/exscript,maximumG/exscript,knipknap/exscript,maximumG/exscript
208760340d3314f666d7e6437817cc96e0e16194
organizer/urls/tag.py
organizer/urls/tag.py
from django.conf.urls import url from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', TagCreate.as_view(), name='organizer_tag_create'), url(r'^(?P<slug...
from django.conf.urls import url from django.contrib.auth.decorators import \ login_required from ..views import ( TagCreate, TagDelete, TagDetail, TagList, TagUpdate) urlpatterns = [ url(r'^$', TagList.as_view(), name='organizer_tag_list'), url(r'^create/$', login_required...
Use login_required decorator in URL pattern.
Ch20: Use login_required decorator in URL pattern.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
1f253c5bdf90055ff2d00a3b8d18c152c3b7031f
versions.py
versions.py
#!/usr/bin/env python import os import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) def test_for_version(filename): stdin, stdout = os.popen4('%s -V' % filename, 'r') response = stdout.read() if response.find('command not found') > 0: return False return '.'.join(res...
#!/usr/bin/env python import os import warnings warnings.filterwarnings('ignore', category=DeprecationWarning) def test_for_version(filename): stdin, stdout = os.popen4('%s -V' % filename, 'r') response = stdout.read() if response.find('command not found') > 0: return False return '.'.join(res...
Check for Python 2.7 as well
Check for Python 2.7 as well
Python
bsd-3-clause
hugoxia/pika,vrtsystems/pika,vitaly-krugl/pika,fkarb/pika-python3,Tarsbot/pika,Zephor5/pika,zixiliuyue/pika,renshawbay/pika-python3,reddec/pika,jstnlef/pika,skftn/pika,pika/pika,shinji-s/pika,knowsis/pika,benjamin9999/pika
539bd8a9df362f285bda375732ec71b3df1bcaae
orbeon_xml_api/tests/test_runner.py
orbeon_xml_api/tests/test_runner.py
from .test_common import CommonTestCase from ..runner import Runner, RunnerForm from ..utils import xml_from_file class RunnerTestCase(CommonTestCase): def setUp(self): super(RunnerTestCase, self).setUp() self.runner_xml = xml_from_file('tests/data', 'test_controls_runner.xml') self.buil...
from xmlunittest import XmlTestCase from .test_common import CommonTestCase from ..runner import Runner, RunnerForm from ..utils import xml_from_file class RunnerTestCase(CommonTestCase, XmlTestCase): def setUp(self): super(RunnerTestCase, self).setUp() self.runner_xml = xml_from_file('tests/da...
Add Runner unit-tests: constructor with validation.
Add Runner unit-tests: constructor with validation.
Python
mit
bobslee/orbeon-xml-api
cde7dbd5a1bb83e85e15559120189d108f6f66aa
tortilla/utils.py
tortilla/utils.py
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): return getattr(__builtins__, "__IPYTHON__", False) ...
# -*- coding: utf-8 -*- import six from formats import FormatBank, discover_json, discover_yaml formats = FormatBank() discover_json(formats, content_type='application/json') discover_yaml(formats, content_type='application/x-yaml') def run_from_ipython(): return getattr(__builtins__, "__IPYTHON__", False) ...
Fix super() call for python <= 3.2
Fix super() call for python <= 3.2
Python
mit
redodo/tortilla
0de0818e5a0c52dde8c841d8e8254e2f4a3f9633
app/sense.py
app/sense.py
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.0 class Handler: def __init__(self, display, logger, sensor): self.display = display self.lo...
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.25 class Handler: def __init__(self, display, logger, sensor): self.display = display self.l...
Allow PiSense readings to be toggled on/off
Allow PiSense readings to be toggled on/off
Python
mit
gizmo-cda/g2x,thelonious/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x
990f4f3ec850525ac4fcb78b33031b60dbe25ce4
versebot/verse.py
versebot/verse.py
""" VerseBot for reddit By Matthieu Grieger verse.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ class Verse: """ Class that holds the properties and methods of a Verse object. """ def __init__(self, book, chapter, verse, translation): """ Initializes a Verse object with book, chapter, v...
""" VerseBot for reddit By Matthieu Grieger verse.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ class Verse: """ Class that holds the properties and methods of a Verse object. """ def __init__(self, book, chapter, verse, translation): """ Initializes a Verse object with book, chapter, v...
Remove spaces and set to lowercase
Remove spaces and set to lowercase
Python
mit
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
fd87d09b03be003dcd13d778c175f796c4fdf7d6
test_http2_server.py
test_http2_server.py
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very ...
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very ...
Change directory test to look for link, rather than just file name
Change directory test to look for link, rather than just file name
Python
mit
jwarren116/network-tools,jwarren116/network-tools
666d9c999ebf0cc388d8f045a04756424c2d9b62
gdemo/util.py
gdemo/util.py
"""Share utility functions.""" from urllib import parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/')
"""Share utility functions.""" try: from urllib import parse except ImportError: import urllib as parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/')
Make it work for Python 2
Make it work for Python 2 Gabbi is designed to work with both Python 2.7 and 3.4.
Python
apache-2.0
cdent/gabbi-demo,cdent/gabbi-demo
f60363b3d24d2f4af5ddb894cc1f6494b371b18e
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py
############################################################################## # # Copyright (C) 2020 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
############################################################################## # # Copyright (C) 2020 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
FIX opt_out prevention for mailchimp export
FIX opt_out prevention for mailchimp export
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland
3ef1531f6934055a416cdddc694f6ca75694d649
voltron/common.py
voltron/common.py
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers'...
import logging import logging.config LOG_CONFIG = { 'version': 1, 'formatters': { 'standard': {'format': 'voltron: [%(levelname)s] %(message)s'} }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'formatter': 'standard' } }, 'loggers'...
Make use of expanduser() more sane
Make use of expanduser() more sane
Python
mit
snare/voltron,snare/voltron,snare/voltron,snare/voltron
22207247c286ad3c656c3f6b550d869cf92f6e92
fs/sshfs/__init__.py
fs/sshfs/__init__.py
from __future__ import absolute_import from __future__ import unicode_literals from .sshfs import SSHFS
from __future__ import absolute_import from __future__ import unicode_literals from .sshfs import SSHFS from ..opener import Opener, registry @registry.install class SSHOpener(Opener): protocols = ['ssh'] def open_fs(self, fs_url, parse_result, writeable, create, cwd): #from .sshfs import SSHFS ...
Add fs Opener based on the builtin FTPFS opener
Add fs Opener based on the builtin FTPFS opener
Python
lgpl-2.1
althonos/fs.sshfs
d0bf235af3742a17c722488fe3679d5b73a0d945
thinc/neural/_classes/softmax.py
thinc/neural/_classes/softmax.py
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'so...
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'so...
Fix gemm calls in Softmax
Fix gemm calls in Softmax
Python
mit
spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
246971d8dd7d6c5fdc480c55e4e79ffd7a840b9b
Cura/View/View.py
Cura/View/View.py
#Abstract for all views class View(object): def __init__(self): self._renderer = None
#Abstract for all views class View(object): def __init__(self): self._renderer = None def render(self, glcontext): pass
Add a render method to view that should be reimplemented
Add a render method to view that should be reimplemented
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
ca674b743b6d48593f45d999335ae893cf2a90d6
base/config/production.py
base/config/production.py
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # auth.oauth # ---------- OAUTH_TWITTER = dict( ...
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # auth.oauth # ---------- OAUTH_TWITTER = dict( ...
Add github and facebook oauth credentials.
Add github and facebook oauth credentials.
Python
bsd-3-clause
klen/Flask-Foundation,klen/fquest,klen/tweetchi
6722e16aef43f9cfe03e7e76fc578582139721f6
vint/linting/env.py
vint/linting/env.py
import os import os.path import re import logging from pathlib import Path VIM_SCRIPT_FILE_NAME_PATTERNS = r'(?:[\._]g?vimrc|.*\.vim$)' def build_environment(cmdargs): return { 'cmdargs': cmdargs, 'home_path': _get_home_path(cmdargs), 'cwd': _get_cwd(cmdargs), 'file_paths': _get_f...
import os import os.path from pathlib import Path from vint.linting.file_filter import find_vim_script def build_environment(cmdargs): return { 'cmdargs': cmdargs, 'home_path': _get_home_path(cmdargs), 'cwd': _get_cwd(cmdargs), 'file_paths': _get_file_paths(cmdargs) } def _ge...
Split file collecting algorithm to FileFilter
Split file collecting algorithm to FileFilter
Python
mit
Kuniwak/vint,RianFuro/vint,RianFuro/vint,Kuniwak/vint
ba8e567592c96dacb697e067004dc71799e4e93f
ctypeslib/test/stdio.py
ctypeslib/test/stdio.py
import os from ctypeslib.dynamic_module import include from ctypes import * if os.name == "nt": _libc = CDLL("msvcrt") else: _libc = CDLL(None) include("""\ #include <stdio.h> #ifdef _MSC_VER # include <fcntl.h> #else # include <sys/fcntl.h> #endif """, persist=False)
import os from ctypeslib.dynamic_module import include from ctypes import * if os.name == "nt": _libc = CDLL("msvcrt") else: _libc = CDLL(None) _gen_basename = include("""\ #include <stdio.h> #ifdef _MSC_VER # include <fcntl.h> #else # include <sys/fcntl.h> #endif /* Silly comment */ """, persist=...
Store the basename of the generated files, to allow the unittests to clean up in the tearDown method.
Store the basename of the generated files, to allow the unittests to clean up in the tearDown method.
Python
mit
sugarmanz/ctypeslib
1ff4dab34d4aa6935d4d1b54aa354882790b9b44
astroquery/astrometry_net/__init__.py
astroquery/astrometry_net/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ <Put Your Tool Name Here> ------------------------- :author: <your name> (<your email>) """ # Make the URL of the server, timeout and other items configurable # See <http://docs.astropy.org/en/latest/config/index.html#developer-usage> # for docs and...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ <Put Your Tool Name Here> ------------------------- :author: <your name> (<your email>) """ # Make the URL of the server, timeout and other items configurable # See <http://docs.astropy.org/en/latest/config/index.html#developer-usage> # for docs and...
Add config items for server, timeout
Add config items for server, timeout
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery