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 |
|---|---|---|---|---|---|---|---|---|---|
5a4f52348d8174e9cb3c4c0b8bfe0baa50f70f31 | tests/test_bot.py | tests/test_bot.py | from mock import patch
import logging
import congressbot
@patch('congressbot.house_collection')
@patch('congressbot.Reddit')
def test_feed_parse(reddit_mock, house_mock):
house_mock.find_one.return_value = False
congressbot.parse()
assert False
| from mock import patch
import logging
import congressbot
@patch('congressbot.house_collection')
@patch('congressbot.Reddit')
def test_feed_parse(reddit_mock, house_mock):
house_mock.find_one.return_value = False
congressbot.parse()
assert False
def test_google_feed():
# Will need to be updated in the... | Add test for google feed | Add test for google feed
| Python | unlicense | koshea/congressbot |
e88a0a27a4960f6b41170cffa0809423987db888 | tests/test_transpiler.py | tests/test_transpiler.py | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pass
transpiler.main(["--ou... | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except OSError:
pass
transpiler.main(["--output-dir",... | Fix error testing on python 2.7 | Fix error testing on python 2.7
| Python | mit | WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler |
cddcc7e5735022c7a4faeee5331e7b80a6349406 | src/functions.py | src/functions.py | def getTableColumnLabel(c):
label = ''
while True:
label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26]
if c <= 26:
break
c = int(c/26)
return label
def parseTableColumnLabel(label):
ret = 0
for c in map(ord, reversed(label)):
if 0x41 <= c <= 0x5A:
ret = ret*26 + (c-0x41)
else:
... | def getTableColumnLabel(c):
label = ''
while True:
label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label
if c < 26:
break
c = c//26-1
return label
def parseTableColumnLabel(label):
if not label:
raise ValueError('Invalid label: %s' % label)
ret = -1
for c in map(ord, label):
if 0x4... | Fix (parse|generate) table header label function | Fix (parse|generate) table header label function
| Python | mit | takumak/tuna,takumak/tuna |
c4d4ba61d1948bebecfadd540a77603fc9dda204 | benchfunk/core/plotters.py | benchfunk/core/plotters.py | import numpy as np
from jug import TaskGenerator
import ezplot
__all__ = ['plot_stack']
@TaskGenerator
def plot_stack(stack_results, problems=None, policies=None, name=''):
problems = problems if problems is not None else stack_results.key()
nfigs = len(problems)
fig = ezplot.figure(figsize=(5*nfigs, 4... | import matplotlib
matplotlib.use('Agg')
import numpy as np
from jug import TaskGenerator
import ezplot
__all__ = ['plot_stack']
@TaskGenerator
def plot_stack(stack_results, problems=None, policies=None, name=''):
problems = problems if problems is not None else stack_results.key()
nfigs = len(problems)
... | Fix plotter to use 'Agg'. | Fix plotter to use 'Agg'.
| Python | bsd-2-clause | mwhoffman/benchfunk |
c970661c4525e0f3a9c77935ccfbef62742b18d4 | csympy/__init__.py | csympy/__init__.py | from .lib.csympy_wrapper import (Symbol, Integer, sympify, SympifyError, Add,
Mul, Pow, sin, cos, sqrt, function_symbol, I)
from .utilities import var
| from .lib.csympy_wrapper import (Symbol, Integer, sympify, SympifyError, Add,
Mul, Pow, sin, cos, sqrt, function_symbol, I)
from .utilities import var
def test():
import pytest, os
return not pytest.cmdline.main(
[os.path.dirname(os.path.abspath(__file__))])
| Add test function so tests can be run from within python terminal | Add test function so tests can be run from within python terminal
import csympy
csympy.test()
| Python | mit | symengine/symengine.py,bjodah/symengine.py,bjodah/symengine.py,symengine/symengine.py,symengine/symengine.py,bjodah/symengine.py |
fc350215a32586ac2233749924fa61078e8c780a | cosmic_ray/testing/unittest_runner.py | cosmic_ray/testing/unittest_runner.py | from itertools import chain
import unittest
from .test_runner import TestRunner
class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods
"""A TestRunner using `unittest`'s discovery mechanisms.
This treats the first element of `test_args` as a directory. This discovers
all tes... | from itertools import chain
import unittest
from .test_runner import TestRunner
class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods
"""A TestRunner using `unittest`'s discovery mechanisms.
This treats the first element of `test_args` as a directory. This discovers
all tes... | Return a list of strings for unittest results, not list of tuples | Return a list of strings for unittest results, not list of tuples
This is needed so the reporter can print a nicely formatted
traceback when the job is killed.
| Python | mit | sixty-north/cosmic-ray |
f0ed7130172a3c5c70c2147919b6e213f065c2c2 | open_journal.py | open_journal.py | import sublime, sublime_plugin
import os, string
import re
from datetime import date
try:
from MarkdownEditing.wiki_page import *
except ImportError:
from wiki_page import *
try:
from MarkdownEditing.mdeutils import *
except ImportError:
from mdeutils import *
class OpenJournalComm... | import sublime, sublime_plugin
import os, string
import re
from datetime import date
try:
from MarkdownEditing.wiki_page import *
except ImportError:
from wiki_page import *
try:
from MarkdownEditing.mdeutils import *
except ImportError:
from mdeutils import *
DEFAULT_DATE_FORMAT = '... | Add parameter to choose journal date format | Add parameter to choose journal date format
This allows for other journal date formats to be permissible, adding an optional date format parameter to the setting file. | Python | mit | SublimeText-Markdown/MarkdownEditing |
7a2fd849a80db2407fb6c734c02c21a2a9b9a66e | forms/management/commands/assign_missing_perms.py | forms/management/commands/assign_missing_perms.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group
from django.contrib import admin
from gmmp.models import Monitor
from forms.admin import (
RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin,
NewspaperSheetAdmin, TelevisionSheetAdmin)
from forms.mo... | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group
from django.contrib import admin
from gmmp.models import Monitor
from forms.admin import (
RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin,
NewspaperSheetAdmin, TelevisionSheetAdmin)
from forms.mo... | Revert "Clean up a bit" | Revert "Clean up a bit"
This reverts commit 4500b571e2fd7a35cf722c3c9cc2fab7ea942cba.
| Python | apache-2.0 | Code4SA/gmmp,Code4SA/gmmp,Code4SA/gmmp |
2a99fc24fec47b741359e3118969ba0f4d874e41 | SettingsObject.py | SettingsObject.py | """
This class is used in kaggle competitions
"""
import json
class Settings():
train_path = None
test_path = None
model_path = None
submission_path = None
string_train_path = "TRAIN_DATA_PATH"
string_test_path = "TEST_DATA_PATH"
string_model_path = "MODEL_PATH"
string_submission_path ... | """
This class is used in kaggle competitions
"""
import json
class Settings():
train_path = None
test_path = None
model_path = None
submission_path = None
string_train_path = "TRAIN_DATA_PATH"
string_test_path = "TEST_DATA_PATH"
string_model_path = "MODEL_PATH"
string_submission_path ... | Remove not necessary code in Setting class | Remove not necessary code in Setting class
| Python | apache-2.0 | Gabvaztor/TFBoost |
ec032ab20de8d3f4d56d7d6901dd73c2bc2ada56 | back_end/api.py | back_end/api.py | from bottle import get, route
import redis
import json
from datetime import datetime
RED = redis.ConnectionPool(host='redis_01',port=6379,db=0)
#RED = redis.ConnectionPool(host='tuchfarber.com',port=6379,db=0)
LENGTH_OF_PREG = 280
@get('/api/test')
def index():
return {'status':'fuck you'}
@get('/api/onthislay/<da... | from bottle import get, route
import redis
import json
import sys
import random
from datetime import date, timedelta
#RED = redis.ConnectionPool(host='redis_01',port=6379,db=0)
RED = redis.ConnectionPool(host='tuchfarber.com',port=6379,db=0)
LENGTH_OF_PREG = 280
WEEK = 7
@get('/api/test')
def index():
return {'stat... | Return details from possible conception date | Return details from possible conception date
| Python | mit | tuchfarber/tony-hawkathon-2016,tuchfarber/tony-hawkathon-2016,tuchfarber/tony-hawkathon-2016 |
41e426457c93fc5e0a785614c090a24aaf2e37f5 | py/foxgami/user.py | py/foxgami/user.py | from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'https://google.com'
... | from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'http://flubstep.com/imag... | Make stub image url a real one | Make stub image url a real one
| Python | mit | flubstep/foxgami.com,flubstep/foxgami.com |
171b0c16698b47a6b0771f2ec2de01079c9a8041 | src/armet/connectors/cyclone/http.py | src/armet/connectors/cyclone/http.py | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from armet import utils
from armet.http import request, response
class Request(request.Request):
"""Implements the request abstraction for cyclone.
"""
@property
@utils.memoize_single
def method(self):
... | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from armet.http import request, response
class Request(request.Request):
"""Implements the request abstraction for cyclone.
"""
def __init__(self, handler):
self.handler = handler
# This is the pyth... | Implement the cyclone request/response object | Implement the cyclone request/response object
| Python | mit | armet/python-armet |
ce9f5551ec7173cc132eb1271e0fc2c1bbfaa7ce | apps/worker/src/main/core/node.py | apps/worker/src/main/core/node.py | from syft.core.node.vm.vm import VirtualMachine
node = VirtualMachine(name="om-vm")
| from syft.core.node.device.device import Device
from syft.grid.services.vm_management_service import CreateVMService
node = Device(name="om-device")
node.immediate_services_with_reply.append(CreateVMService)
node._register_services() # re-register all services including SignalingService
| ADD CreateVMService at Device APP | ADD CreateVMService at Device APP
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
a4dc87b5a9b555f74efa9bfe2bd16af5340d1199 | googlesearch/googlesearch.py | googlesearch/googlesearch.py | #!/usr/bin/python
import json
import urllib
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_results)
dat... | #!/usr/bin/python
import json
import urllib
import sys
def showsome(searchfor):
query = urllib.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.urlopen(url)
search_results = search_response.read()
results = json.loads(search_res... | Update of the google search code to be a command line program. | Update of the google search code to be a command line program.
| Python | apache-2.0 | phpsystems/code,phpsystems/code |
afb58da6ecc11a1c92d230bc2dcbb06464cc4f32 | percept/workflows/commands/run_flow.py | percept/workflows/commands/run_flow.py | """
Given a config file, run a given workflow
"""
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
import logging
log = logging.getLogger... | """
Given a config file, run a given workflow
"""
from percept.management.commands import BaseCommand
from percept.utils.registry import registry, find_in_registry
from percept.workflows.base import NaiveWorkflow
from percept.utils.workflow import WorkflowWrapper, WorkflowLoader
from optparse import make_option
import... | Add in a way to start a shell using the results of a workflow | Add in a way to start a shell using the results of a workflow
| Python | apache-2.0 | VikParuchuri/percept,VikParuchuri/percept |
3a9359660ff4c782e0de16e8115b754a3e17d7e7 | inthe_am/taskmanager/models/usermetadata.py | inthe_am/taskmanager/models/usermetadata.py | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.ForeignKey(
User, related_name="metadata", unique=True, on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted... | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.OneToOneField(
User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.... | Change mapping to avoid warning | Change mapping to avoid warning
| Python | agpl-3.0 | coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am |
81756324744334de39a0b151d9acac9e24774b9d | api/management/commands/deleteuselessactivities.py | api/management/commands/deleteuselessactivities.py | from django.core.management.base import BaseCommand, CommandError
from api import models
from django.db.models import Count, Q
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
if 'NR' in args:
print 'Delete activities of N/R cards'
act... | from django.core.management.base import BaseCommand, CommandError
from api import models
from django.db.models import Count, Q
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
if 'NR' in args:
print 'Delete activities of N/R cards'
act... | Use list of values and not subquery (less efficient but do not use limit) | Use list of values and not subquery (less efficient but do not use limit)
| Python | apache-2.0 | rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,laurenor/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,laurenor/SchoolIdolAPI,laurenor/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,dburr/SchoolIdolAPI,rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI |
faa0e5fd214151e8b0bb8fb18772807aa020c4bf | infrastructure/crowdin/crowdin_bot_python_package/crowdin_bot/get_crowdin_languages.py | infrastructure/crowdin/crowdin_bot_python_package/crowdin_bot/get_crowdin_languages.py | """Script to print list of all crowdin language codes for project."""
from crowdin_bot import api
NS_DICT = {
'ns': "urn:oasis:names:tc:xliff:document:1.2"
}
def get_project_languages():
"""Get list of crowdin language codes.
Returns:
(list) list of project crowdin language codes
"""
inf... | """Script to print list of all crowdin language codes for project."""
from crowdin_bot import api
NS_DICT = {
'ns': "urn:oasis:names:tc:xliff:document:1.2"
}
def get_project_languages():
"""Get list of crowdin language codes.
Returns:
(list) list of project crowdin language codes
"""
act... | Modify crowdin_bot to only include languages that have >0 translations | Modify crowdin_bot to only include languages that have >0 translations
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged |
d5cfb72626d486276af842b152d19c19d6d7b58c | bika/lims/subscribers/objectmodified.py | bika/lims/subscribers/objectmodified.py | from Products.CMFCore.utils import getToolByName
def ObjectModifiedEventHandler(obj, event):
""" Various types need automation on edit.
"""
if not hasattr(obj, 'portal_type'):
return
if obj.portal_type == 'Calculation':
pr = getToolByName(obj, 'portal_repository')
uc = getToolB... | from Products.CMFCore.utils import getToolByName
from Products.CMFCore import permissions
def ObjectModifiedEventHandler(obj, event):
""" Various types need automation on edit.
"""
if not hasattr(obj, 'portal_type'):
return
if obj.portal_type == 'Calculation':
pr = getToolByName(obj, ... | Fix missing import in Client modified subscriber | Fix missing import in Client modified subscriber
| Python | agpl-3.0 | anneline/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS |
0cb3aa5947b5c5da802c05ae16bc138441c2c921 | accounts/views.py | accounts/views.py | from django.shortcuts import render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return render(request, 'account/user_home.html')
| from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return redirect(reverse('quizzes:index'))
| Use quiz index as user home temporarily | Use quiz index as user home temporarily
| Python | mit | lockhawksp/beethoven,lockhawksp/beethoven |
b02c5736a6a0875da7e7feeaa433f4870d1f4bca | indra/sources/eidos/eidos_reader.py | indra/sources/eidos/eidos_reader.py | from indra.java_vm import autoclass, JavaException
from .scala_utils import get_python_json
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings ... | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
in... | Simplify Eidos reader, use Eidos JSON String call | Simplify Eidos reader, use Eidos JSON String call
| Python | bsd-2-clause | sorgerlab/belpy,bgyori/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra |
f34d0d43311e51bcb04c5cbdf5bb31b7a8093feb | pyconde/tagging.py | pyconde/tagging.py | """
This abstracts some of the functionality provided by django-taggit in order
to normalize the tags provided by the users.
"""
from taggit import managers as taggit_managers
def _normalize_tag(t):
if isinstance(t, unicode):
return t.lower()
return t
class _TaggableManager(taggit_managers._Taggabl... | """
This abstracts some of the functionality provided by django-taggit in order
to normalize the tags provided by the users.
"""
from taggit import managers as taggit_managers
def _normalize_tag(t):
if isinstance(t, unicode):
return t.lower()
return t
class _TaggableManager(taggit_managers._Taggabl... | Fix regression introduced by updating taggit (27971d6eed) | Fix regression introduced by updating taggit (27971d6eed)
django-taggit 0.11+ introduced support for prefetch_related which breaks
our taggit wrapping: alex/django-taggit@4f2e47f833
| Python | bsd-3-clause | pysv/djep,pysv/djep,EuroPython/djep,pysv/djep,pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep,EuroPython/djep |
65d8715705e07dc7f091e2da47a7ada923c6cfbb | release.py | release.py | """
Setuptools is released using 'jaraco.packaging.release'. To make a release,
install jaraco.packaging and run 'python -m jaraco.packaging.release'
"""
import os
import subprocess
import pkg_resources
pkg_resources.require('jaraco.packaging>=2.0')
pkg_resources.require('wheel')
def before_upload():
Bootstrap... | """
Setuptools is released using 'jaraco.packaging.release'. To make a release,
install jaraco.packaging and run 'python -m jaraco.packaging.release'
"""
import os
import subprocess
import pkg_resources
pkg_resources.require('jaraco.packaging>=2.0')
pkg_resources.require('wheel')
def before_upload():
Bootstrap... | Remove lingering reference to linked changelog. | Remove lingering reference to linked changelog.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
ae3d94fbc9a53df6bbeb0fedf6bb660ba6cd4b40 | rpy2_helpers.py | rpy2_helpers.py | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
latti... | #! /usr/bin/env python2.7
"""Avoid some boilerplate rpy2 usage code with helpers.
Mostly I wrote this so that I can use xyplot without having
to remember a lot of details.
"""
import click
from rpy2.robjects import DataFrame, Formula, globalenv
from rpy2.robjects.packages import importr
grdevices = importr('grDevi... | Make DataFrame available to module user | Make DataFrame available to module user
| Python | mit | ecashin/rpy2_helpers |
13d1895a979cfb210e097e4d471238bf36c88c65 | website/db_create.py | website/db_create.py | #!/usr/bin/env python3
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.')
... | #!/usr/bin/env python3
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.')
... | Use store true in db creation script | Use store true in db creation script
| Python | lgpl-2.1 | reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visua... |
e12eb10d699fce8e0081acc44025035f703b4dc5 | crits/core/user_migrate.py | crits/core/user_migrate.py | def migrate_user(self):
"""
Migrate to latest schema version.
"""
migrate_1_to_2(self)
migrate_2_to_3(self)
def migrate_1_to_2(self):
"""
Migrate from schema 1 to schema 2.
"""
if self.schema_version == 1:
self.schema_version = 2
notify_email = getattr(self.unsupp... | def migrate_user(self):
"""
Migrate to latest schema version.
"""
migrate_1_to_2(self)
migrate_2_to_3(self)
def migrate_1_to_2(self):
"""
Migrate from schema 1 to schema 2.
"""
if self.schema_version == 1:
self.schema_version = 2
notify_email = getattr(self.unsupp... | Add default exploit to user migration. | Add default exploit to user migration.
| Python | mit | cdorer/crits,DukeOfHazard/crits,korrosivesec/crits,Lambdanaut/crits,DukeOfHazard/crits,jinverar/crits,jinverar/crits,jhuapl-marti/marti,korrosivesec/crits,Magicked/crits,kaoscoach/crits,blaquee/crits,kaoscoach/crits,blaquee/crits,ckane/crits,HardlyHaki/crits,Magicked/crits,cdorer/crits,korrosivesec/crits,cfossace/crits... |
f09f33a6ddf0cf397838068e9cc3bc82464bf699 | labelme/labelme/spiders/__init__.py | labelme/labelme/spiders/__init__.py | # This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
| # This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import scrapy
ANNOTATION_URL = 'http://people.csail.mit.edu/brussell/research/LabelMe/Annotations/'
IMG_URL = 'http://people.csail.mit.edu/brussell/research/L... | Add a scaffold for spiders to crawl annotations and images | Add a scaffold for spiders to crawl annotations and images
| Python | mit | paopow/LabelMeCrawler |
ba8de67d006c461b736f98f2bb1fcb876ec06830 | svs_interface.py | svs_interface.py | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.text.pack()
menu = Menu(master)
root.config(menu=menu)
... | #!/usr/bin/env python
import subprocess
from Tkinter import *
from tkFileDialog import *
import os
GPG = 'gpg2'
SERVER_KEY = '' # replace with gpg key ID of server key
class GpgApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.tex... | Add method to encrypt files | Add method to encrypt files
| Python | agpl-3.0 | mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream |
2be69ba584b76134fc055ea17b476ce32ce5bf1e | haas/drivers/__init__.py | haas/drivers/__init__.py | """Network switch drivers for the HaaS.
This package provides HaaS drivers for various network switches. The
functions in the top-level module should not be used; they only exist
as a place to document the interface shared by all of the drivers.
Port IDs and network IDs should both be strings. The content of them wi... | """Network switch drivers for the HaaS.
This package provides HaaS drivers for various network switches. The
functions in the top-level module should not be used; they only exist
as a place to document the interface shared by all of the drivers.
Port IDs and network IDs should both be strings. The content of them wi... | Document reason for previous change | Document reason for previous change
| Python | apache-2.0 | meng-sun/hil,henn/haas,kylehogan/hil,henn/hil,henn/hil_sahil,henn/hil,kylehogan/hil,SahilTikale/haas,lokI8/haas,CCI-MOC/haas,meng-sun/hil,apoorvemohan/haas,kylehogan/haas,SahilTikale/switchHaaS,apoorvemohan/haas,henn/hil_sahil |
82ba04d609c80fd2bf8034cf38654d10bb72aca5 | src/app/actions/psmtable/filter_confidence.py | src/app/actions/psmtable/filter_confidence.py | from app.readers import tsv as tsvreader
def filter_psms(psms, confkey, conflvl, lower_is_better):
for psm in psms:
if passes_filter(psm, conflvl, confkey, lower_is_better):
yield psm
def passes_filter(psm, threshold, confkey, lower_is_better):
if psm[confkey] in ['NA', '', None, False]:... | from app.readers import tsv as tsvreader
def filter_psms(psms, confkey, conflvl, lower_is_better):
for psm in psms:
if passes_filter(psm, conflvl, confkey, lower_is_better):
yield psm
def passes_filter(psm, threshold, confkey, lower_is_better):
try:
confval = float(psm[confkey])
... | Fix confidence filtering removed confidence=0 (False) items | Fix confidence filtering removed confidence=0 (False) items
| Python | mit | glormph/msstitch |
6a754b4a52619f84346a1cc89148884cefb3bc78 | motobot/irc_level.py | motobot/irc_level.py | class IRCLevel:
""" Enum class (Not really) for userlevels. """
user = 0
voice = 1
hop = 2
op = 3
aop = 4
sop = 5
def get_userlevels(nick):
""" Return the userlevels in a list from a nick. """
mapping = {
'+': IRCLevel.voice,
'%': IRCLevel.hop,
'@': IRCLevel... | class IRCLevel:
""" Enum class (Not really) for userlevels. """
user = 0
vop = 1
hop = 2
aop = 3
sop = 4
owner = 5
master = 6
| Update IRCLevel and remove get_userlevels | Update IRCLevel and remove get_userlevels
| Python | mit | Motoko11/MotoBot |
ac725f0d96cfe6ef989d3377e5e7ed9e339fe7e5 | djangoautoconf/auth/ldap_backend_wrapper.py | djangoautoconf/auth/ldap_backend_wrapper.py | from django_auth_ldap.backend import LDAPBackend
class LDAPBackendWrapper(LDAPBackend):
# def authenticate(self, identification, password, **kwargs):
# return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs)
def authenticate(self, **kwargs):
if "username" in kwa... | from django_auth_ldap.backend import LDAPBackend
class LDAPBackendWrapper(LDAPBackend):
# def authenticate(self, identification, password, **kwargs):
# return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs)
def authenticate(self, **kwargs):
if "username" in kwa... | Update codes for ldap wrapper so the username and password are passed to authenticate correctly. | Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf |
bc2246e8efa3a8d196c95ceb6d028f3b655b70c5 | hooks/pre_gen_project.py | hooks/pre_gen_project.py | import re
MODULE_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$"
ENVIRON_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$"
PYTHONVERSION_REGEX = r"^(3)\.[6-9]$"
module_name = "{{ cookiecutter.project_slug}}"
if not re.match(MODULE_REGEX, module_name):
raise ValueError(
f"""
ERROR: The project slug ({module_name}) is not a valid... | import re
MODULE_REGEX = r"^[-_a-zA-Z0-9]*$"
ENVIRON_REGEX = r"^[-_a-zA-Z0-9]*$"
PYTHONVERSION_REGEX = r"^(3)\.[6-9]$"
module_name = "{{ cookiecutter.project_slug}}"
if not re.match(MODULE_REGEX, module_name):
raise ValueError(
f"""
ERROR: The project slug ({module_name}) is not a valid name.
Please d... | Allow for minus signs in project slug. | Allow for minus signs in project slug.
| Python | bsd-3-clause | hmgaudecker/econ-project-templates,hmgaudecker/econ-project-templates,hmgaudecker/econ-project-templates |
7e44e92e574efe110546a9d3a5e4807fa74fec6e | sympy/interactive/ipythonprinting.py | sympy/interactive/ipythonprinting.py | """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console ... | """
A print function that pretty prints SymPy objects.
:moduleauthor: Brian Granger
Usage
=====
To use this extension, execute:
%load_ext sympy.interactive.ipythonprinting
Once the extension is loaded, SymPy Basic objects are automatically
pretty-printed in the terminal and rendered in LaTeX in the Qt console ... | Fix testing error when IPython not installed | Fix testing error when IPython not installed
| Python | bsd-3-clause | moble/sympy,jaimahajan1997/sympy,pbrady/sympy,yukoba/sympy,cccfran/sympy,asm666/sympy,kaushik94/sympy,jbbskinny/sympy,garvitr/sympy,lindsayad/sympy,dqnykamp/sympy,oliverlee/sympy,abloomston/sympy,dqnykamp/sympy,grevutiu-gabriel/sympy,hrashk/sympy,maniteja123/sympy,liangjiaxing/sympy,rahuldan/sympy,Designist/sympy,debug... |
3b21be6f0711163fdb6f1cf99514fae04f395b62 | romanesco/plugins/swift/tests/swift_test.py | romanesco/plugins/swift/tests/swift_test.py | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | import os
import romanesco
import shutil
import unittest
def setUpModule():
global _tmp
global _cwd
_cwd = os.getcwd()
_tmp = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'tmp', 'swift')
if not os.path.isdir(_tmp):
os.makedirs(_tmp)
os.chdir(_tmp)
def tearDownMod... | Clean up after swift run | Clean up after swift run
| Python | apache-2.0 | girder/girder_worker,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,girder/girder_worker |
f2fd224b5e3c8cb4a919e082c47c603d4469a564 | jacquard/buckets/tests/test_bucket.py | jacquard/buckets/tests/test_bucket.py | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Use an explicit test here | Use an explicit test here
| Python | mit | prophile/jacquard,prophile/jacquard |
7a0ed88e1775429ce283cc315cc05ea3dbde229f | tests/response_construction_tests.py | tests/response_construction_tests.py | from django.test.client import RequestFactory
from mock import Mock
from unittest2 import TestCase
from .helpers import RequestPatchMixin
from .test_views import TestProxy
class ResponseConstructionTest(TestCase, RequestPatchMixin):
def setUp(self):
self.proxy = TestProxy.as_view()
self.browser_r... | from django.test.client import RequestFactory
from mock import Mock
from unittest2 import TestCase
from .helpers import RequestPatchMixin
from .test_views import TestProxy
class ResponseConstructionTest(TestCase, RequestPatchMixin):
def get_request(self):
return RequestFactory().get('/')
def setUp(s... | Add test coverage for 1.10 CONTENT_LENGTH hack | Add test coverage for 1.10 CONTENT_LENGTH hack
| Python | mit | thomasw/djproxy |
83ca7677ac77d55f9ba978f2988b18faa9e74424 | secondhand/urls.py | secondhand/urls.py | from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tracker.api import UserResource, TaskResource, WorkSessionResource
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
# tracker API.
v1_api = Api(api_name='v1')
v1_api.regis... | from django.conf.urls import patterns, include, url
from tastypie.api import Api
from tracker.api import UserResource, TaskResource, WorkSessionResource, \
RegistrationResource
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
# tracker API.
v1_api = Api... | Fix minor issue, reorganize imports, and register the RegistrationResource with the API. | Fix minor issue, reorganize imports, and register the RegistrationResource with the API.
| Python | mit | GeneralMaximus/secondhand |
06f10e09f5b1c5766815b6e7eb219b4e33082709 | check_urls.py | check_urls.py | #!/usr/bin/env python2.7
import re, sys, markdown, requests, bs4 as BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf8')
def check_url(url):
try:
return bool(requests.head(url, allow_redirects=True))
except Exception as e:
print 'Error checking URL %s: %s' % (url, e)
return False
... | #!/usr/bin/env python2.7
from __future__ import print_function
import re, sys, markdown, requests, bs4 as BeautifulSoup
try: # Python 2
reload
except NameError: # Python 3
from importlib import reload
reload(sys)
sys.setdefaultencoding('utf8')
def check_url(url):
try:
return bool(... | Add Python 3 compatibility and flake8 testing | Add Python 3 compatibility and flake8 testing | Python | unlicense | ligurio/free-software-testing-books |
c5ff897355fb7fce5022127bcae756e8c68dc864 | data/views.py | data/views.py | import os
from django.shortcuts import render, redirect
from django.template import Context
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from chemtools.extractor import CORES, RGROUPS, ARYL
from data.models import JobTemplate
def frag_index(request):
xrnames = ["H", "... | import os
from django.shortcuts import render, redirect
from django.template import Context
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from chemtools.extractor import CORES, RGROUPS, ARYL
from data.models import JobTemplate
def frag_index(request):
xrnames = ["H", "... | Add new fragments to data.frag_index | Add new fragments to data.frag_index
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp |
edec252d9a050ead0084280f9772f05a2a3d7608 | preferences/forms.py | preferences/forms.py | from registration.forms import RegistrationFormUniqueEmail
class RegistrationUserForm(RegistrationFormUniqueEmail):
class Meta:
model = User
fields = ("email")
| from django import forms
from registration.forms import RegistrationFormUniqueEmail
from preferences.models import Preferences
# from django.forms import ModelForm
# class RegistrationUserForm(RegistrationFormUniqueEmail):
# class Meta:
# model = User
# fields = ("email")
class PreferencesForm... | Add preferences form built off model | Add preferences form built off model
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
e6026134e02f516cc84e499494205efa0ad7441f | tests/test_autoconfig.py | tests/test_autoconfig.py | # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.getcwd(), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' == config('KEY... | # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' ... | Replace cwd with current module's path | Replace cwd with current module's path | Python | mit | mrkschan/python-decouple,flaviohenriqu/python-decouple,henriquebastos/django-decouple,liukaijv/python-decouple,henriquebastos/python-decouple |
ec884c9db173f093d1398de54d00f1c36f22d8e4 | examples/random_valid_test_generator.py | examples/random_valid_test_generator.py | import sys
import time
from random import shuffle
from FairDistributor import FairDistributor
def main():
# User input for the number of targets and objects.
number_of_targets = int(sys.argv[1])
number_of_objects = int(sys.argv[2])
# Generate dummy lists for objects, targets and dummy matrix for weigh... | import sys
import time
from random import shuffle
from vania.fair_distributor import FairDistributor
def main():
# User input for the number of targets and objects.
number_of_targets = int(sys.argv[1])
number_of_objects = int(sys.argv[2])
# Generate dummy lists for objects, targets and dummy matrix f... | Reformat random generator reformat code | Reformat random generator reformat code
| Python | mit | Hackathonners/vania |
a55bd9116114b546c06685e413209ab4279aaef5 | genes/terraform/main.py | genes/terraform/main.py | from genes.mac.traits import is_osx
from genes.brew import brew
def main():
if is_osx():
brew.install()
| from genes.mac.traits import is_osx
from genes.brew.command import Brew
def main():
if is_osx():
brew = Brew()
brew.install()
| Change the brew instruction. kinda dumb | Change the brew instruction. kinda dumb
| Python | mit | hatchery/genepool,hatchery/Genepool2 |
49fc55369d4755148d3db58c593d0b6f4d60582d | run_tests.py | run_tests.py | import sys
import os
import unittest
import subprocess
import time
cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000'
p = subprocess.Popen(cmd)
time.sleep(2)
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib')))
sys.path.append(os.path.abspath(os.path.join(os.path.dir... | import sys
import os
import unittest
import subprocess
import time
import shlex
cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000'
p = subprocess.Popen(shlex.split(cmd))
time.sleep(2)
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib')))
sys.path.append(os.path.abspat... | Fix test run on linux / travis | Fix test run on linux / travis
| Python | mit | ucoin-io/cutecoin,ucoin-io/cutecoin,ucoin-io/cutecoin |
6297eddaceb996a2c76825295af6a37e81d5c2fb | ain7/organizations/autocomplete_light_registry.py | ain7/organizations/autocomplete_light_registry.py | # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2015 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of ... | # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2015 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of ... | Allow to autocomplete on office & organization names | Allow to autocomplete on office & organization names
| Python | lgpl-2.1 | ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org |
5fef3e5a5425ab71abb4c3b8a36a2273c9947b2e | bcbio/chipseq/__init__.py | bcbio/chipseq/__init__.py | from bcbio.ngsalign.bowtie2 import filter_multimappers
import bcbio.pipeline.datadict as dd
def clean_chipseq_alignment(data):
aligner = dd.get_aligner(data)
data["raw_bam"] = dd.get_work_bam(data)
if aligner:
assert aligner == "bowtie2", "ChIP-seq only supported for bowtie2."
unique_bam = ... | from bcbio.ngsalign.bowtie2 import filter_multimappers
import bcbio.pipeline.datadict as dd
def clean_chipseq_alignment(data):
aligner = dd.get_aligner(data)
data["raw_bam"] = dd.get_work_bam(data)
if aligner:
assert aligner == "bowtie2", "ChIP-seq only supported for bowtie2."
unique_bam = ... | Add warning when aligner is false | Chipseq: Add warning when aligner is false
| Python | mit | biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,brainstorm/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,brain... |
5b616f5b3d605b1831d4ca8ca0a9be561f399a89 | falmer/events/admin.py | falmer/events/admin.py | from django.contrib import admin
from django.contrib.admin import register
from falmer.events.models import Event
@register(Event)
class EventModelAdmin(admin.ModelAdmin):
pass
| from django.contrib import admin
from django.contrib.admin import register
from falmer.events.models import Event, MSLEvent
@register(Event)
class EventModelAdmin(admin.ModelAdmin):
list_display = ('title', 'start_time', 'end_time', )
@register(MSLEvent)
class MSLEventModelAdmin(admin.ModelAdmin):
pass
| Improve list display of events | Improve list display of events
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
cbb6f7495123f1745284d0b098dcfaae0b31c5f3 | bin/commands/utils/git.py | bin/commands/utils/git.py | """A collection of common git actions."""
from subprocess import check_output, PIPE, Popen, STDOUT
def is_valid_reference(reference):
"""Determines if a reference is valid.
:param str reference: name of the reference to validate
:return bool: whether or not the reference is valid
"""
show_ref_... | """A collection of common git actions."""
import os
from subprocess import check_output, PIPE, Popen, STDOUT
def is_valid_reference(reference):
"""Determines if a reference is valid.
:param str reference: name of the reference to validate
:return bool: whether or not the reference is valid
"""
... | Add type checking and piping to /dev/null | Add type checking and piping to /dev/null
| Python | mit | Brickstertwo/git-commands |
25e2c37bb9dc17f0c10ae744b1554b94c4e5a7ff | doj/monkey/__init__.py | doj/monkey/__init__.py | # -*- coding: utf-8 -*-
import doj.monkey.django_utils_functional_lazy
import doj.monkey.django_http_response_streaminghttpresponse
import doj.monkey.inspect_getcallargs
def install_monkey_patches():
doj.monkey.django_utils_functional_lazy.install()
doj.monkey.django_http_response_streaminghttpresponse.insta... | # -*- coding: utf-8 -*-
import doj.monkey.django_utils_functional_lazy
import doj.monkey.django_http_response_streaminghttpresponse
import doj.monkey.inspect_getcallargs
def install_monkey_patches():
# Make sure we install monkey patches only once
if not getattr(install_monkey_patches, 'installed', False):
... | Make sure we install monkey patches only once | Make sure we install monkey patches only once
| Python | bsd-3-clause | beachmachine/django-jython |
109018326b317a160e0ba555b23b7b4401f44ed3 | website/views.py | website/views.py | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from news.models import Article, Event
from door.models import DoorStatus
from datetime import datetime
from itertools import chain
def index(request):
number_of_news = 3
# Sorts the ... | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from news.models import Article, Event
from door.models import DoorStatus
from datetime import datetime
from itertools import chain
def index(request):
number_of_news = 3
# Sorts the ... | Change redirect to application redirect | Change redirect to application redirect
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website |
198a941c8c71802b72c33f5ef89d1d4d46e52eac | scripts/fetch_all_urls_to_disk.py | scripts/fetch_all_urls_to_disk.py | import urllib
import os
import hashlib
with open('media_urls.txt','r') as f:
for url in f:
imagename = os.path.basename(url)
m = hashlib.md5(url).hexdigest()
if '.jpg' in url:
shortname = m + '.jpg'
elif '.png' in url:
shortname = m + '.png'
else:
print ... | import urllib
import os
import hashlib
with open('media_urls.txt','r') as f:
for url in f:
imagename = os.path.basename(url)
m = hashlib.md5(url).hexdigest()
if '.jpg' in url:
shortname = m + '.jpg'
elif '.png' in url:
shortname = m + '.png'
else:
print ... | Add continue when no extension ".jpg" nor ".png" is found in URL | Add continue when no extension ".jpg" nor ".png" is found in URL
| Python | mit | mixbe/kerstkaart2013,mixbe/kerstkaart2013 |
1c1c7dd151b3b7894fff74b31c15bded4ac4dc96 | lintrain/solvers/ridgeregression.py | lintrain/solvers/ridgeregression.py | from solver import Solver
import numpy as np
class RidgeRegression(Solver):
"""
Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains
coefficients and can be effective in situations where over- or under-fitting arise.
Based off of:
https... | from solver import Solver
import numpy as np
class RidgeRegression(Solver):
"""
Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains
coefficients and can be effective in situations where over- or under-fitting arise. Parameters `alpha`
is t... | Allow setting ridge regression parameters during creation | Allow setting ridge regression parameters during creation
| Python | mit | nathanntg/lin-train,nathanntg/lin-train |
f8b4f4a2c5a7f529816f78344509a3536a0f3254 | datapipe/targets/filesystem.py | datapipe/targets/filesystem.py | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
de... | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
de... | Fix another situation where targets didn't get rebuilt | Fix another situation where targets didn't get rebuilt
| Python | mit | ibab/datapipe |
7bb93bfdf2b75ba8df0983d058854a1d00d75c16 | geotrek/feedback/tests/test_commands.py | geotrek/feedback/tests/test_commands.py | from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from geotrek.feedback.models import Report
from geotrek.feedback.factories import ReportFactory
class TestRemoveEmailsOlders(TestCase):
"""Test command erase_emails, if olde... | from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from geotrek.feedback.models import Report
from geotrek.feedback.factories import ReportFactory
class TestRemoveEmailsOlders(TestCase):
"""Test command erase_emails, if olde... | Test dry run mode in erase_mail | Test dry run mode in erase_mail
| Python | bsd-2-clause | makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin |
924766a6b56aba3a462600a70e5f4b7b322c677e | test/test_utils.py | test/test_utils.py | from piper.utils import DotDict
from piper.utils import dynamic_load
import pytest
class TestDotDict(object):
def test_get_nonexistant_raises_keyerror(self):
with pytest.raises(KeyError):
dd = DotDict({})
dd.does_not_exist
def test_get_item(self):
dd = DotDict({'dange... | from piper.utils import DotDict
from piper.utils import dynamic_load
import pytest
class TestDotDict(object):
def test_get_nonexistant_raises_keyerror(self):
with pytest.raises(KeyError):
dd = DotDict({})
dd.does_not_exist
def test_get_item(self):
dd = DotDict({'dange... | Add extra DotDict subscriptability test | Add extra DotDict subscriptability test
| Python | mit | thiderman/piper |
0515f71d861529262aada1ad416c626277e11d9e | django_excel_to_model/forms.py | django_excel_to_model/forms.py | from django.utils.translation import ugettext_lazy as _
from django import forms
from models import ExcelImportTask
from django.forms import ModelForm
class ExcelFormatTranslateForm(forms.Form):
# title = forms.CharField(max_length=50)
import_file = forms.FileField(
label=_('File to import')
)
... | from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django import forms
from models import ExcelImportTask
from django.forms import ModelForm
class ExcelFormatTranslateForm(forms.Form):
# title = forms.CharField(max_length=50)
import_file = f... | Sort content for data import. | Sort content for data import.
| Python | bsd-3-clause | weijia/django-excel-to-model,weijia/django-excel-to-model |
ef9d7cbbd79078e494faed730318a18f995f3a78 | cla_public/libs/zendesk.py | cla_public/libs/zendesk.py | # -*- coding: utf-8 -*-
"Zendesk"
import json
import requests
from flask import current_app
TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json'
def create_ticket(payload):
"Create a new Zendesk ticket"
return requests.post(
TICKETS_URL,
data=json.dumps(payload),
... | # -*- coding: utf-8 -*-
"Zendesk"
import json
import requests
from flask import current_app
TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json'
def zendesk_auth():
return (
'{username}/token'.format(
username=current_app.config['ZENDESK_API_USERNAME']),
current... | Refactor Zendesk client code for smoketest | Refactor Zendesk client code for smoketest
| Python | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public |
0722b517f5b5b9a84b7521b6b7d350cbc6537948 | src/core/models.py | src/core/models.py | from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
"""
presumed_type = super().db_type(connection)
if presumed_type == 'integer':
return 'bigint'
... | from django.apps import apps
from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
Django's AutoField is actually an IntegerField (SQL integer field),
but in some cases we are ... | Add some explaination on BigForeignKey | Add some explaination on BigForeignKey
| Python | mit | uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016 |
e6fcb5122b7132e03257ac5c883f5e44ccdd1ef5 | quokka/ext/before_request.py | quokka/ext/before_request.py | # coding: utf-8
def configure(app):
@app.before_first_request
def initialize():
print "Called only once, when the first request comes in"
| # coding: utf-8
from quokka.core.models import Channel
def configure(app):
@app.before_first_request
def initialize():
print "Called only once, when the first request comes in"
if not Channel.objects.count():
# Create homepage if it does not exists
Channel.objects.crea... | Create channel homepage if not exists in before request | Create channel homepage if not exists in before request
| Python | mit | fdumpling/quokka,lnick/quokka,CoolCloud/quokka,Ckai1991/quokka,felipevolpone/quokka,romulocollopy/quokka,cbeloni/quokka,ChengChiongWah/quokka,cbeloni/quokka,CoolCloud/quokka,romulocollopy/quokka,fdumpling/quokka,fdumpling/quokka,maurobaraldi/quokka,maurobaraldi/quokka,Ckai1991/quokka,lnick/quokka,ChengChiongWah/quokka,... |
cf626539192ff60a0c2ffd06c61fb35f2d8861a1 | tests/test_data.py | tests/test_data.py | from unittest import TestCase
from chatterbot_corpus import corpus
class CorpusUtilsTestCase(TestCase):
"""
This test case is designed to make sure that all
corpus data adheres to a few general rules.
"""
def test_character_count(self):
"""
Test that no line in the corpus exceeds ... | from unittest import TestCase
from chatterbot_corpus import corpus
class CorpusUtilsTestCase(TestCase):
"""
This test case is designed to make sure that all
corpus data adheres to a few general rules.
"""
def test_character_count(self):
"""
Test that no line in the corpus exceeds ... | Add test for data type validation | Add test for data type validation
| Python | bsd-3-clause | gunthercox/chatterbot-corpus |
876ff2e147aaa751d2ab2f5423b30fcfcc02fba9 | tests/test_main.py | tests/test_main.py | import os
import sys
import pytest
from hypothesis_auto import auto_pytest_magic
from isort import main
auto_pytest_magic(main.sort_imports)
def test_is_python_file():
assert main.is_python_file("file.py")
assert main.is_python_file("file.pyi")
assert main.is_python_file("file.pyx")
assert not main... | import os
import sys
import pytest
from hypothesis_auto import auto_pytest_magic
from isort import main
from isort.settings import DEFAULT_CONFIG
auto_pytest_magic(main.sort_imports)
def test_iter_source_code(tmpdir):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
assert tuple(mai... | Add test case for iter_source_code | Add test case for iter_source_code
| Python | mit | PyCQA/isort,PyCQA/isort |
de97d95d7746cbbf6c2c53a660553ce56d294288 | tests/test_unit.py | tests/test_unit.py | # -*- coding: utf-8 -*-
"""
tests.test_unit
~~~~~~~~~~~~~~~
Module dedicated to testing the unit utility functions.
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import (division, unicode_literals, print_function,... | # -*- coding: utf-8 -*-
"""
tests.test_unit
~~~~~~~~~~~~~~~
Module dedicated to testing the unit utility functions.
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import (division, unicode_literals, print_function,... | Add missing test for to_float applied on a float (when pint is present). | Add missing test for to_float applied on a float (when pint is present).
| Python | bsd-3-clause | MatthieuDartiailh/lantz_core |
f8aa722b9b56ca543f73a40f22fd682a1c71fb4c | clowder_server/management/commands/send_alerts.py | clowder_server/management/commands/send_alerts.py | import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_server.emailer import send_alert
from clowder_server.models import Alert
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **options):
alerts = Alert.objects.filter(notif... | import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_account.models import ClowderUser
from clowder_server.emailer import send_alert
from clowder_server.models import Alert, Ping
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **... | Delete old unused pings from users | Delete old unused pings from users
| Python | agpl-3.0 | keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,framewr/clowder_server |
10d09367111d610e82344e9616aab98815bf9397 | capture_chessboard.py | capture_chessboard.py | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Capture calibration chessboard
#
# External dependencies
import time
import cv2
import Calibration
# Calibration pattern size
pattern_size = ( 9, 6 )
# Get the camera
camera = cv2.VideoCapture( 1 )
# Acquisition loop
while( True ) :
# Capture image-by-image
_... | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Capture calibration chessboard
#
# External dependencies
import time
import cv2
import numpy as np
import Calibration
# Calibration pattern size
pattern_size = ( 9, 6 )
# Get the camera
camera = cv2.VideoCapture( 0 )
# Acquisition loop
while( True ) :
# Capture i... | Change camera index, and fix the chessboard preview. | Change camera index, and fix the chessboard preview.
| Python | mit | microy/RobotVision,microy/RobotVision |
e7825da0f8467717aac9857bbc046d946aa2ce66 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '56984fa0e4c3c745652510f342c0fb2724d846c2'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
... | #!/usr/bin/env python
import platform
import sys
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '2dfdf169b582e3f051e1fec3dd7df2bc179e1aa6'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
... | Upgrade libchromiumcontent to discard iframe security settings | Upgrade libchromiumcontent to discard iframe security settings
| Python | mit | astoilkov/electron,tylergibson/electron,yalexx/electron,bruce/electron,stevekinney/electron,kikong/electron,beni55/electron,nagyistoce/electron-atom-shell,GoooIce/electron,xiruibing/electron,timruffles/electron,thomsonreuters/electron,thomsonreuters/electron,gabrielPeart/electron,stevemao/electron,baiwyc119/electron,jc... |
21f152589550c1c168a856798690b9cf957653db | akanda/horizon/routers/views.py | akanda/horizon/routers/views.py | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
# Note(rods): Right now we a... | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
# Note(rods): Filter off the... | Modify the interfaces listing view to filter only the port on the mgt network | Modify the interfaces listing view to filter only the port on
the mgt network
DHC-1512
Change-Id: If7e5aebf7cfd7e87df0dea8cd749764c142f1676
Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
| Python | apache-2.0 | dreamhost/akanda-horizon,dreamhost/akanda-horizon |
c1e17f9501fb9afc69f9fba288fa9e4cfac262e2 | tviit/models.py | tviit/models.py | from __future__ import unicode_literals
from django.conf import settings
import uuid
from django.db import models
class Tviit(models.Model):
uuid = models.CharField(unique=True, max_length=40, default=uuid.uuid4().int, editable=False)
sender = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_d... | from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils.deconstruct import deconstructible
from django.dispatch import receiver
from django.forms import ModelForm
import uuid, os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@dec... | Add image into Tviit Model Add PathAndRename function to rename image path Add TviitForm | Add image into Tviit Model
Add PathAndRename function to rename image path
Add TviitForm
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys |
030a786db1c0602125bfe4093c6a5709b0202858 | app/hooks/views.py | app/hooks/views.py | from __future__ import absolute_import
from __future__ import unicode_literals
from app import app, webhooks
@webhooks.hook(app.config.get('GITLAB_HOOK'), handler='gitlab')
class Gitlab:
def issue(self, data):
pass
def push(self, data):
pass
def tag_push(self, data):
pass
de... | from __future__ import absolute_import
from __future__ import unicode_literals
from app import app, webhooks
@webhooks.hook(
app.config.get('GITLAB_HOOK','/hooks/gitlab'),
handler='gitlab')
class Gitlab:
def issue(self, data):
pass
def push(self, data):
pass
def tag_push(self, da... | Add default hook url for gitlab | Add default hook url for gitlab
| Python | apache-2.0 | pipex/gitbot,pipex/gitbot,pipex/gitbot |
99580712595402cc84db3eed37e913b18cae1703 | examples/marginal_ticks.py | examples/marginal_ticks.py | """
Scatterplot with marginal ticks
===============================
_thumb: .68, .32
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", color_codes=True)
# Generate a random bivariate dataset
rs = np.random.RandomState(9)
mean = [0, 0]
cov = [(1, 0), (0, 2)]
x, y = rs.... | """
Scatterplot with marginal ticks
===============================
_thumb: .62, .39
"""
import numpy as np
import seaborn as sns
sns.set(style="white", color_codes=True)
# Generate a random bivariate dataset
rs = np.random.RandomState(9)
mean = [0, 0]
cov = [(1, 0), (0, 2)]
x, y = rs.multivariate_normal(mean, cov, 1... | Fix thumbnail on gallery page | Fix thumbnail on gallery page
| Python | bsd-3-clause | mwaskom/seaborn,arokem/seaborn,anntzer/seaborn,mwaskom/seaborn,anntzer/seaborn,arokem/seaborn |
8d339d610b57b40534af2a8d7cdbdaec041a995a | test/TestNGrams.py | test/TestNGrams.py | import unittest
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... | import unittest
import sys
sys.path.append('../src')
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... | Add path in test to src | Add path in test to src
| Python | bsd-2-clause | ambidextrousTx/RNLTK |
0243b5d468593edda6c207aaa124e8911a824751 | src/argparser.py | src/argparser.py | """ArgumentParser with Italian translation."""
import argparse
import sys
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
class ArgParser(argparse.ArgumentParser):
def __init__(self,
prog=None,
usage=None,
description=None,... | """ArgumentParser with Italian translation."""
import argparse
import sys
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
class ArgParser(argparse.ArgumentParser):
def __init__(self, **kwargs):
if kwargs.get('parent', None) is None:
kwargs['parents'] = [... | Fix crash in python 3.8 due to a mismatch on the ArgumentParser parameter | Fix crash in python 3.8 due to a mismatch on the ArgumentParser parameter
| Python | mit | claudio-unipv/pvcheck,claudio-unipv/pvcheck |
314ba088f0c2cb8e47da22a8841127a17e4e222d | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields
'''
This module create model of Course
'''
class Course(models.Model):
'''
this class model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True)
description = fields.Text(string='Description')
re... | from openerp import api, models, fields
'''
This module create model of Course
'''
class Course(models.Model):
'''
this class model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True)
description = fields.Text(string='Description')
... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | GavyMG/openacademy-proyect |
bad66654ee2a2688a4931dc88c617ea962c8cdf4 | hairball/plugins/duplicate.py | hairball/plugins/duplicate.py | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateChecks(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateChecks, se... | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... | Change class name to DuplicateScripts | Change class name to DuplicateScripts
| Python | bsd-2-clause | thsunmy/hairball,jemole/hairball,ucsb-cs-education/hairball,thsunmy/hairball,jemole/hairball,ucsb-cs-education/hairball |
311549ce2dd126063b5e0b1e3476cbae78a4d6d5 | tests/__init__.py | tests/__init__.py | from flexmock import flexmock
from flask.ext.storage import MockStorage
from flask_uploads import init
created_objects = []
added_objects = []
deleted_objects = []
committed_objects = []
class MockModel(object):
def __init__(self, **kw):
created_objects.append(self)
for key, val in kw.iteritems()... | from flexmock import flexmock
from flask.ext.storage import MockStorage
from flask_uploads import init
class TestCase(object):
added_objects = []
committed_objects = []
created_objects = []
deleted_objects = []
def setup_method(self, method, resizer=None):
init(db_mock, MockStorage, resiz... | Fix problems in test init. | Fix problems in test init.
| Python | mit | FelixLoether/flask-uploads,FelixLoether/flask-image-upload-thing |
d48a15c9585dfdb4441a0ca58041d064defe19b2 | libs/utils.py | libs/utils.py | from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.appen... | from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.appen... | Add cache key in HTML source | Add cache key in HTML source
| Python | mit | daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban |
4612f10a8d4dcd0ec7133b12411387c74becbdb7 | tests/__init__.py | tests/__init__.py | import sublime
import os
import os.path
import unittest
class CommandTestCase(unittest.TestCase):
def setUp(self):
self.project_data = {
'code_search': {'csearchindex': 'test_csearchindex'},
'folders': [{'path': '.'}]}
sublime.active_window().run_command('new_window')
self.window = sub... | import sublime
import os
import os.path
import unittest
class CommandTestCase(unittest.TestCase):
def setUp(self):
path = '{0}/YetAnotherCodeSearch'.format(sublime.packages_path())
self.project_data = {
'code_search': {'csearchindex': 'test_csearchindex'},
'folders': [{'path': path}]}
... | Set the test path to the project in Packages. | Set the test path to the project in Packages.
| Python | mit | pope/SublimeYetAnotherCodeSearch,pope/SublimeYetAnotherCodeSearch |
8a645abd1880fdac72e36f7366ae81fa13bf78ae | app/main/views/digital_outcomes_and_specialists.py | app/main/views/digital_outcomes_and_specialists.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from app import data_api_client
from flask import abort, render_template
from ...helpers.buyers_helpers import get_framework_and_lot
from ...main import main
@main.route('/buyers/frameworks/<framework_slug>/requirements/user-research-studios', methods=[... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from app import data_api_client
from flask import abort, render_template
from ...helpers.buyers_helpers import get_framework_and_lot
from ...main import main
@main.route('/buyers/frameworks/<framework_slug>/requirements/user-research-studios', methods=[... | Check framework has the studios lot before showing start page | Check framework has the studios lot before showing start page
| Python | mit | AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-di... |
993c4c98fb9529946669b4d13e6c5a9ff4ab3f67 | tests/test_mpi.py | tests/test_mpi.py | from mpi4py import MPI
import pytest
from devito import Grid, Function, Distributor
@pytest.mark.parallel(nprocs=2)
def test_hello_mpi():
size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()
print("Hello, World! I am rank %d of %d on %s" % (rank, size, n... | from mpi4py import MPI
import pytest
from devito import Grid, Function
@pytest.mark.parallel(nprocs=2)
def test_hello_mpi():
size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
name = MPI.Get_processor_name()
print("Hello, World! I am rank %d of %d on %s" % (rank, size, name), flush=T... | Check domain decomposition over Functions | tests: Check domain decomposition over Functions
| Python | mit | opesci/devito,opesci/devito |
654219bf00dc4a029d9e42779c3ad2d552948596 | plim/extensions.py | plim/extensions.py | from docutils.core import publish_string
import coffeescript
from scss import Scss
from stylus import Stylus
from .util import as_unicode
def rst_to_html(source):
# This code was taken from http://wiki.python.org/moin/ReStructuredText
# You may also be interested in http://www.tele3.cz/jbar/rest/about.html
... | from docutils.core import publish_parts
import coffeescript
from scss import Scss
from stylus import Stylus
from .util import as_unicode
def rst_to_html(source):
# This code was taken from http://wiki.python.org/moin/ReStructuredText
# You may also be interested in http://www.tele3.cz/jbar/rest/about.html
... | Fix ReStructuredText extension in Python3 environment | Fix ReStructuredText extension in Python3 environment
| Python | mit | kxxoling/Plim |
7b33941dc14e2be4940a425107d668a8913eed53 | ovp_users/serializers.py | ovp_users/serializers.py | from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name', 'email', 'password']
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['na... | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name', 'email', 'pas... | Validate user password on creation | Validate user password on creation
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users |
5346741d0d5360cdf776252dcbe400ff839ab9fc | hs_core/tests/api/rest/test_resource_types.py | hs_core/tests/api/rest/test_resource_types.py | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
from hs_core.hydroshare.utils import get_resource_types
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
def test_resource_typelist(se... | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
# Use a static list so that this test breaks when a resource type is
# add... | Make resource type list static | Make resource type list static
| Python | bsd-3-clause | FescueFungiShare/hydroshare,hydroshare/hydroshare,FescueFungiShare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,RENCI/xDCIShare,FescueFungiShare/hydroshare,hydroshare/hydroshare,hydroshare/... |
987c94a2a7d283ba4b231f332d0362f47c2e7a2a | BootstrapUpdater.py | BootstrapUpdater.py | #!/usr/bin/python3
# -*- coding: utf8 -*-
import os
import shutil
import subprocess
bootstrap_updater_version = 1
BootstrapDownloads = 'BootstrapDownloads/'
BootstrapPrograms = 'BootstrapPrograms/'
bootstrap = 'https://www.dropbox.com/s/0zhbgb1ftspcv9w/polygon4.zip?dl=1'
bootstrap_zip = BootstrapDownloads + 'boots... | #!/usr/bin/python3
# -*- coding: utf8 -*-
import os
import shutil
import subprocess
bootstrap_updater_version = 1
BootstrapDownloads = 'BootstrapDownloads/'
BootstrapPrograms = 'BootstrapPrograms/'
bootstrap = 'https://www.dropbox.com/s/0zhbgb1ftspcv9w/polygon4.zip?dl=1'
bootstrap_zip = BootstrapDownloads + 'boots... | Create download directory if not exists. | Create download directory if not exists.
| Python | agpl-3.0 | aimrebirth/BootstrapPy |
776c1dbda3871c2b94d849ea59db25f93bb59525 | src/mmw/apps/water_balance/views.py | src/mmw/apps/water_balance/views.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.shortcuts import render_to_response
def home_page(request):
return render_to_response('home_page/index.html')
| # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.shortcuts import render_to_response
from django.template import RequestContext
def home_page(request):
return render_to_response('home_page/index.html', RequestContext... | Add RequestContext to Micro site | Add RequestContext to Micro site
This allows us to populate settings variables such as Google Analytics
codes. See original work done for #769.
Refs #920
| Python | apache-2.0 | lliss/model-my-watershed,WikiWatershed/model-my-watershed,kdeloach/model-my-watershed,lliss/model-my-watershed,lliss/model-my-watershed,kdeloach/model-my-watershed,project-icp/bee-pollinator-app,kdeloach/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,lliss/model-my-watershed,WikiWa... |
670a72728ea7462972f3578b62cf33c5740187c2 | locust/rpc/protocol.py | locust/rpc/protocol.py | import msgpack
class Message(object):
def __init__(self, message_type, data, node_id):
self.type = message_type
self.data = data
self.node_id = node_id
def serialize(self):
return msgpack.dumps((self.type, self.data, self.node_id))
@classmethod
def unserialize(cls, da... | import msgpack
class Message(object):
def __init__(self, message_type, data, node_id):
self.type = message_type
self.data = data
self.node_id = node_id
def __repr__(self):
return "<Message %s:%s>" % (self.type, self.node_id)
def serialize(self):
return msgpack... | Add Message.__repr__ for better debugging | Add Message.__repr__ for better debugging | Python | mit | mbeacom/locust,mbeacom/locust,locustio/locust,mbeacom/locust,locustio/locust,mbeacom/locust,locustio/locust,locustio/locust |
0286a26fc19b0474a45ecd4a8a6d0bb1e6afab02 | tests/acceptance/response_test.py | tests/acceptance/response_test.py | from .request_test import test_app
def test_200_for_normal_response_validation():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.enable_swagger_spec_validation': False,
'pyramid_swagger.enable_response_validation': True,
}
test_a... | from .request_test import test_app
def test_200_for_normal_response_validation():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.enable_swagger_spec_validation': False,
'pyramid_swagger.enable_response_validation': True,
}
test_a... | Disable spec validation on 3x | Disable spec validation on 3x
| Python | bsd-3-clause | prat0318/pyramid_swagger,analogue/pyramid_swagger,striglia/pyramid_swagger,brianthelion/pyramid_swagger,striglia/pyramid_swagger |
828215d3de3ddd2febdd190de067b0f6e5c2e9e1 | query/migrations/0017_auto_20160224_1306.py | query/migrations/0017_auto_20160224_1306.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from query.operations import engine_specific
class Migration(migrations.Migration):
dependencies = [
('query', '0016_auto_20160203_1324'),
]
operations = [
engine_specific(('mysql',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from query.operations import engine_specific
class Migration(migrations.Migration):
dependencies = [
('query', '0016_auto_20160203_1324'),
]
operations = [
engine_specific(('mysql',... | Use named arguments for RunSQL | Use named arguments for RunSQL
| Python | apache-2.0 | UUDigitalHumanitieslab/texcavator,UUDigitalHumanitieslab/texcavator,UUDigitalHumanitieslab/texcavator |
fb2f66adf5ba60d2cda934ef27125ce84057367e | PCbuild/rmpyc.py | PCbuild/rmpyc.py | # Remove all the .pyc and .pyo files under ../Lib.
def deltree(root):
import os
def rm(path):
os.unlink(path)
npyc = npyo = 0
dirs = [root]
while dirs:
dir = dirs.pop()
for short in os.listdir(dir):
full = os.path.join(dir, short)
if os.path.isdir(ful... | # Remove all the .pyc and .pyo files under ../Lib.
def deltree(root):
import os
from os.path import join
npyc = npyo = 0
for root, dirs, files in os.walk(root):
for name in files:
delete = False
if name.endswith('.pyc'):
delete = True
np... | Use os.walk() to find files to delete. | Use os.walk() to find files to delete.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
d301cbeb4e6f248ed137a9d1a6b6f39558231cc3 | tests/functional/test_vcs_mercurial.py | tests/functional/test_vcs_mercurial.py | from pip._internal.vcs.mercurial import Mercurial
from tests.lib import _create_test_package
def test_get_repository_root(script):
version_pkg_path = _create_test_package(script, vcs="hg")
tests_path = version_pkg_path.joinpath("tests")
tests_path.mkdir()
root1 = Mercurial.get_repository_root(version... | from pip._internal.vcs.mercurial import Mercurial
from tests.lib import _create_test_package, need_mercurial
@need_mercurial
def test_get_repository_root(script):
version_pkg_path = _create_test_package(script, vcs="hg")
tests_path = version_pkg_path.joinpath("tests")
tests_path.mkdir()
root1 = Mercu... | Add marker to Mercurial test | Add marker to Mercurial test
| Python | mit | pradyunsg/pip,pfmoore/pip,pradyunsg/pip,pypa/pip,pfmoore/pip,pypa/pip,sbidoul/pip,sbidoul/pip |
7c1886cf8751281e1b41e80341a045b46c2c38f5 | querylist/betterdict.py | querylist/betterdict.py | # Attribute prefix for allowing dotlookups when keys conflict with dict
# attributes.
PREFIX = '_bd_'
class BetterDict(dict):
def __init__(self, *args, **kwargs):
# Prefix that will be appended to keys for dot lookups that would
# otherwise conflict with dict attributes.
self.__prefix = PR... | # Attribute prefix for allowing dotlookups when keys conflict with dict
# attributes.
PREFIX = '_bd_'
class BetterDict(dict):
def __init__(self, *args, **kwargs):
# Prefix that will be appended to keys for dot lookups that would
# otherwise conflict with dict attributes.
self.__prefix = PR... | Remove unnecessary check for dict attr conflicts. | Remove unnecessary check for dict attr conflicts.
| Python | mit | thomasw/querylist,zoidbergwill/querylist |
fc036a2cc7bd3200d98ed833343e116f4ce32bf1 | kitchen/text/exceptions.py | kitchen/text/exceptions.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010 Red Hat, Inc
#
# kitchen 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.
#
# k... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010 Red Hat, Inc
#
# kitchen 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.
#
# k... | Add ControlCharError for process_control_chars function | Add ControlCharError for process_control_chars function
| Python | lgpl-2.1 | fedora-infra/kitchen,fedora-infra/kitchen |
e0c19574995224fe56fad411ce6f0796b71f8af5 | l10n_br_zip/__openerp__.py | l10n_br_zip/__openerp__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
... | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '9.0.1.0.0',
'depends': [
... | Change the version of module. | [MIG] Change the version of module.
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil |
a06607c9fa5a248000edeba6a392a3ecdd531507 | src/tempel/models.py | src/tempel/models.py | from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now=True, auto_now_ad... | from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now=True, auto_now_ad... | Add functions to EntryModel to get language, mimetype, filename, and extension | Add functions to EntryModel to get language, mimetype, filename, and extension
| Python | agpl-3.0 | fajran/tempel |
ee32b2e48acd47f1f1ff96482abf20f3d1818fc4 | tests/__init__.py | tests/__init__.py | # -*- coding: utf-8 -*-
"""
Unit test.
Each file in tests/ is for each main package.
"""
import sys
import unittest
sys.path.append("../pythainlp")
loader = unittest.TestLoader()
testSuite = loader.discover("tests")
testRunner = unittest.TextTestRunner(verbosity=1)
testRunner.run(testSuite)
| # -*- coding: utf-8 -*-
"""
Unit test.
Each file in tests/ is for each main package.
"""
import sys
import unittest
import nltk
sys.path.append("../pythainlp")
nltk.download('omw-1.4') # load wordnet
loader = unittest.TestLoader()
testSuite = loader.discover("tests")
testRunner = unittest.TextTestRunner(verbosity=... | Add load wordnet to tests | Add load wordnet to tests
| Python | apache-2.0 | PyThaiNLP/pythainlp |
dd248a14a40dea03458985640571bccf9b38b030 | conftest.py | conftest.py | import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if "robots" in str(pat... | import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if str(path).endswith(... | Remove robots from pytest path ignore, as requested by @gonzalocasas. | Remove robots from pytest path ignore, as requested by @gonzalocasas.
| Python | mit | compas-dev/compas |
27ab3ad3d1ce869baec85264b840da49ff43f82f | scripts/sync_exceeded_traffic_limits.py | scripts/sync_exceeded_traffic_limits.py | #!/usr/bin/env python3
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import os
from flask import _request_ctx_stack, g, request
from sqlalchemy import creat... | #!/usr/bin/env python3
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import os
from flask import _request_ctx_stack, g, request
from sqlalchemy import creat... | Add schema version check to sync script | Add schema version check to sync script
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft |
a82067a5484133233ccf7037e5c277eaaa5318fa | aioes/__init__.py | aioes/__init__.py | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_v... | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
from .exception import (ConnectionError, NotFountError, ConflictError,
RequestError, TransportError)
__all__ = ('Elasticsearch', 'ConnectionError', 'NotFountError',
'ConflictError', 'RequestErr... | Add aioes exceptions to top-level imports | Add aioes exceptions to top-level imports
| Python | apache-2.0 | aio-libs/aioes |
7669a43b1dcf097434942bea64e05a29c32f9717 | django_dowser/urls.py | django_dowser/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('django_dowser.views',
url(r'^trace/(?P<typename>[\.\-\w]+)(/(?P<objid>\d+))?$', 'trace'),
url(r'^tree/(?P<typename>[\.\-\w]+)/(?P<objid>\d+)$', 'tree'),
url(r'^$', 'index'),
)
| try:
from django.conf.urls import *
except ImportError:
from django.conf.urls.defaults import *
urlpatterns = patterns('django_dowser.views',
url(r'^trace/(?P<typename>[\.\-\w]+)(/(?P<objid>\d+))?$', 'trace'),
url(r'^tree/(?P<typename>[\.\-\w]+)/(?P<objid>\d+)$', 'tree'),
url(r'^$', 'index'),
)
| Fix compatibility with Django 1.6 | Fix compatibility with Django 1.6
| Python | mit | munhitsu/django-dowser,munhitsu/django-dowser |
4a4dbfd142e2f8fca3e82d7790ace4ed88bb0b3f | djangocms_spa/urls.py | djangocms_spa/urls.py | from django.conf.urls import url
from .views import SpaCmsPageDetailApiView
urlpatterns = [
url(r'^(?P<language_code>[\w-]+)/pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'),
url(r'^(?P<language_code>[\w-]+)/pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_deta... | from django.conf.urls import url
from .views import SpaCmsPageDetailApiView
urlpatterns = [
url(r'^pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'),
url(r'^pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'),
]
| Remove language code from path | Remove language code from path
We no longer need the language detection in the URL. The locale
middleware already handles the language properly and we can consume
it from the request.
| Python | mit | dreipol/djangocms-spa,dreipol/djangocms-spa |
cff0f979abc4bf9bfb24b9cd70c447a2bc838501 | syncplay/__init__.py | syncplay/__init__.py | version = '1.7.0'
revision = ' development'
milestone = 'Yoitsu'
release_number = '101'
projectURL = 'https://syncplay.pl/'
| version = '1.7.0'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '102'
projectURL = 'https://syncplay.pl/'
| Mark as 1.7.0 beta 1 | Mark as 1.7.0 beta 1 | Python | apache-2.0 | Syncplay/syncplay,Syncplay/syncplay |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.