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 |
|---|---|---|---|---|---|---|---|---|---|
729cea9ae07f7264b765813cac00e869f66069ff | tools/allBuild.py | tools/allBuild.py | import os
import buildFirefox
import buildChrome
os.chdir(os.path.dirname(os.path.abspath(__file__)))
buildFirefox.run()
buildChrome.run() | import os
import buildFirefox
import buildChrome
os.chdir(os.path.dirname(os.path.abspath(__file__)))
filenames = ['header.js', 'guild_page.js', 'core.js']
with open('tgarmory.js', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
buildFirefox.r... | Prepare for file concat build system | Prepare for file concat build system
| Python | mit | ZergRael/tgarmory |
b53ebee86c36dfe52e8a11fb8c4f3cec99878fc9 | gitlabform/gitlab/merge_requests.py | gitlabform/gitlab/merge_requests.py | from gitlabform.gitlab.core import GitLabCore
class GitLabMergeRequests(GitLabCore):
def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None):
pid = self._get_project_id(project_and_group_name)
data = {
"id": pid,
"source_branch": ... | from gitlabform.gitlab.core import GitLabCore
class GitLabMergeRequests(GitLabCore):
def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None):
pid = self._get_project_id(project_and_group_name)
data = {
"id": pid,
"source_branch": ... | Add update MR method (for internal use for now) | Add update MR method (for internal use for now)
| Python | mit | egnyte/gitlabform,egnyte/gitlabform |
badc84447ad6a596317c93e7c393e6021da8a18f | park_api/security.py | park_api/security.py | def file_is_allowed(file):
t = file.endswith(".py")
t &= "__Init__" not in file.title()
t &= "Sample_City" not in file.title()
return t
| def file_is_allowed(file):
t = file.endswith(".py")
t &= "__Init__" not in file.title()
t &= "Sample_City" not in file.title()
t &= "Frankfurt" not in file.title() # See offenesdresden/ParkAPI#153
return t
| Disable Frankfurt until requests is fixed | Disable Frankfurt until requests is fixed
ref #153
| Python | mit | offenesdresden/ParkAPI,offenesdresden/ParkAPI |
7cf37b966049cfc47ef200ad8ae69763d98185c5 | collector/description/normal/L2.py | collector/description/normal/L2.py | from __future__ import absolute_import
import math, utilities.operator
from ...weight import WeightDict, normalize_exp
from .L1 import phase_description
# Normalised distances and L2-normalised (Euclidean norm) collector sets
collector_weights = \
WeightDict(normalize_exp, (utilities.operator.square, math.sqrt),
... | from __future__ import absolute_import
import math, utilities.operator
from ...weight import WeightDict, normalize_exp
from .L1 import descriptions
# Normalised distances and L2-normalised (Euclidean norm) collector sets
weights = \
WeightDict(normalize_exp, (utilities.operator.square, math.sqrt),
tags=('normal... | Update secondary collector description module | Update secondary collector description module
| Python | mit | davidfoerster/schema-matching |
eb57469f1b14dfd5c2e74f2bbb774513e0662a6c | installer/installer_config/forms.py | installer/installer_config/forms.py | from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.... | from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
choices = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.o... | Remove steps from Env Prof form | Remove steps from Env Prof form
| Python | mit | alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy |
4e94cef9f6617827341af443ac428b9ccc190535 | lib/recommend-by-url.py | lib/recommend-by-url.py | # -*- coding: utf-8 -*-
from newspaper import Article
from goose import Goose
import json
import sys
article = Article(sys.argv[1])
article.download()
article.parse()
article.nlp()
published = ''
if article.publish_date:
published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S")
# Get body with goose
g = Goos... | # -*- coding: utf-8 -*-
from newspaper import Article
from goose import Goose
import requests
import json
import sys
article = Article(sys.argv[1])
article.download()
if not article.html:
r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' })
article.set_html(r.text)
article.parse()... | Improve reliablity of python article fetcher | Improve reliablity of python article fetcher
| Python | mit | lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder |
c6de39b01b8eac10edbb6f95d86285075bf8a9ab | conanfile.py | conanfile.py | from conans import ConanFile
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfile/*", "... | from conans import ConanFile, CMake
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfil... | Add build step into Conan recipe. | Add build step into Conan recipe.
| Python | mit | igormironchik/cfgfile |
222e2a70f9c2d4ce7cb4a26d717c6bcce1e3f344 | tests/utils.py | tests/utils.py | import os
import pytest
from tests.consts import examples_path
from valohai_yaml import parse
def _load_config(filename, roundtrip):
with open(os.path.join(examples_path, filename), 'r') as infp:
config = parse(infp)
if roundtrip:
config = parse(config.serialize())
return config
def co... | import os
import pytest
from tests.consts import examples_path
from valohai_yaml import parse
def _load_config(filename, roundtrip):
with open(os.path.join(examples_path, filename), 'r') as infp:
config = parse(infp)
if roundtrip:
config = parse(config.serialize())
return config
def co... | Add nicer ids for tests | Add nicer ids for tests
| Python | mit | valohai/valohai-yaml |
fa9e488c3fa008fa2c9b08a787ea9c2655bd3d02 | tests/test_discuss.py | tests/test_discuss.py | import pytest
from web_test_base import *
class TestIATIDiscuss(WebTestBase):
requests_to_load = {
'IATI Discuss': {
'url': 'http://discuss.iatistandard.org/'
}
}
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the define... | import pytest
from web_test_base import *
class TestIATIDiscuss(WebTestBase):
requests_to_load = {
'IATI Discuss': {
'url': 'http://discuss.iatistandard.org/'
}
, 'IATI Discuss Welcome Thread': {
'url': 'http://discuss.iatistandard.org/t/welcome-to-iati-discuss/6'
... | Add test for Discuss Welcome | Add test for Discuss Welcome
This ensures the welcome post is sufficiently welcoming.
The XPaths are based on the page with Javascript disabled. As such,
they will not correctly match if Javascript is enabled.
| Python | mit | IATI/IATI-Website-Tests |
9ae8283e06b0b72213fc8084909ae9c2c2b3e553 | build/android/pylib/gtest/gtest_config.py | build/android/pylib/gtest/gtest_config.py | # 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.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | # 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.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | Move component_unittest to android main waterfall and cq | Move component_unittest to android main waterfall and cq
These are existing tests that moved to the component_unittest
target. They have been running on the FYI bots for a few days
without issue.
BUG=
Android bot script change. Ran through android trybots.
NOTRY=true
Review URL: https://chromiumcodereview.appspot.co... | Python | bsd-3-clause | jaruba/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,jaruba/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,anirudhSK/chromium,dednal/chromium.... |
f74636d6944b45753d274f6a993678863a368961 | tests/test_testapp.py | tests/test_testapp.py |
import json
import ckanapi
import unittest
import paste.fixture
def wsgi_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'application/json')]
path = environ['PATH_INFO']
if path == '/api/action/hello_world':
response = {'success': True, 'result': 'how are you?'}
... |
import json
import ckanapi
import unittest
import paste.fixture
def wsgi_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'application/json')]
path = environ['PATH_INFO']
if path == '/api/action/hello_world':
response = {'success': True, 'result': 'how are you?'}
... | Fix a couple of tests | Fix a couple of tests
Fix a couple of tests that were broken by commit 7e068a3.
| Python | mit | LaurentGoderre/ckanapi,perceptron-XYZ/ckanapi,xingyz/ckanapi,metaodi/ckanapi,wardi/ckanapi,eawag-rdm/ckanapi |
8ae4594d4f4157568db0dc5cad4d07b8f1142218 | src/common/utils.py | src/common/utils.py | from passlib.hash import pbkdf2_sha512
class Utils:
@staticmethod
def hash_password(password):
"""
Hashes a password using sha512 -> pbkdf2_sha512 encrypted password
"""
return pbkdf2_sha512.encrypt(password)
@staticmethod
def check_hashed_password(password, hashed_password):
"""
Checks the password ... | import re
from passlib.hash import pbkdf2_sha512
class Utils:
@staticmethod
def email_is_valid(email):
email_address_matcher = re.compile('^[\w-]+@([\w-]+\.)+[\w]+$')
return True if email_address_matcher.match(email) else False
@staticmethod
def hash_password(password):
"""
Hashes a password using sha512... | Add static method for email address | Add static method for email address
| Python | apache-2.0 | asimonia/pricing-alerts,asimonia/pricing-alerts |
f4d9e55cf3dbed0cf21661c33a6efbc98093d1f8 | paypal.py | paypal.py | #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first li... | #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first li... | Tweak PayPal output to use Payee and Memo fields | Tweak PayPal output to use Payee and Memo fields
| Python | mit | pwaring/csv2qif |
439cbfbfa6b16fdd0d24f91adb55eb510802ab8c | inbox/ignition.py | inbox/ignition.py | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | Set pool_recycle to deal with MySQL closing idle connections. | Set pool_recycle to deal with MySQL closing idle connections.
See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
| Python | agpl-3.0 | PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,closeio/nylas,Eagles2F/sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-e... |
71324420df350bba5423006a444927e33c1a5ae2 | dddp/apps.py | dddp/apps.py | """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from django.db import DatabaseError
from django.db.models import signals
from dddp import autodiscover
from dddp.models import Connection
class DjangoDDPConfig... | """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from dddp import autodiscover
class DjangoDDPConfig(AppConfig):
"""Django app config for django-ddp."""
api = None
name = 'dddp'
verbose_name... | Remove unused imports from AppConfig module. | Remove unused imports from AppConfig module.
| Python | mit | commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp |
0f0d404f36115d6410b3ba5eed9e9f9f2fb2461f | carnetdumaker/context_processors.py | carnetdumaker/context_processors.py | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... | Add missing facebook and google verif codes | Add missing facebook and google verif codes
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker |
b8f9b2664f8782a028ce27a361f2a7a28eb925aa | cloudenvy/commands/envy_snapshot.py | cloudenvy/commands/envy_snapshot.py | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | Remove out-of-date comment about snapshot UX | Remove out-of-date comment about snapshot UX
| Python | apache-2.0 | cloudenvy/cloudenvy |
b0fef4ed92cde72305a2d85f3e96adde93f82547 | tests/test_py35/test_resp.py | tests/test_py35/test_resp.py | import pytest
import aiohttp
from aiohttp import web
@pytest.mark.run_loop
async def test_await(create_server, loop):
async def handler(request):
return web.HTTPOk()
app, url = await create_server()
app.router.add_route('GET', '/', handler)
resp = await aiohttp.get(url+'/', loop=loop)
a... | import pytest
import aiohttp
from aiohttp import web
@pytest.mark.run_loop
async def test_await(create_server, loop):
async def handler(request):
return web.HTTPOk()
app, url = await create_server()
app.router.add_route('GET', '/', handler)
resp = await aiohttp.get(url+'/', loop=loop)
a... | Add test for context manager | Add test for context manager
| Python | apache-2.0 | juliatem/aiohttp,playpauseandstop/aiohttp,juliatem/aiohttp,Eyepea/aiohttp,mind1master/aiohttp,z2v/aiohttp,decentfox/aiohttp,jashandeep-sohi/aiohttp,pfreixes/aiohttp,vaskalas/aiohttp,hellysmile/aiohttp,AraHaanOrg/aiohttp,moden-py/aiohttp,rutsky/aiohttp,z2v/aiohttp,vaskalas/aiohttp,elastic-coders/aiohttp,singulared/aioht... |
e1e7189bbe859d6dfa6f883d2ff46ff1faed4842 | scrape.py | scrape.py | import scholarly
import requests
_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def search(query, start_year, end_year):
"""Search by scholar query and return a generator of Publication objects"""
soup = scholarly._get_soup(
_SEARCH.format(requests.utils.quote(query),
str(star... | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query... | Make year range arguments optional in search | Make year range arguments optional in search
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker |
667a3d2803529c5b14fd17c6877961646615f2fd | python2/raygun4py/middleware/wsgi.py | python2/raygun4py/middleware/wsgi.py | import logging
from raygun4py import raygunprovider
log = logging.getLogger(__name__)
class Provider(object):
def __init__(self, app, apiKey):
self.app = app
self.sender = raygunprovider.RaygunSender(apiKey)
def __call__(self, environ, start_response):
if not self.sender:
... | import logging
from raygun4py import raygunprovider
log = logging.getLogger(__name__)
class Provider(object):
def __init__(self, app, apiKey):
self.app = app
self.sender = raygunprovider.RaygunSender(apiKey)
def __call__(self, environ, start_response):
if not self.sender:
... | Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly | Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
| Python | mit | MindscapeHQ/raygun4py |
95bb764e78e623310dff1ae48eabf4271b452406 | penchy/jobs/__init__.py | penchy/jobs/__init__.py | from penchy.jobs import jvms, tools, filters, workloads
from penchy.jobs.job import Job, SystemComposition, NodeSetting
from penchy.jobs.dependency import Edge
JVM = jvms.JVM
# all job elements that are interesting for the user have to be enumerated here
__all__ = [
# job
'Job',
'NodeSetting',
'System... | from penchy.jobs import jvms, tools, filters, workloads
from penchy.jobs.job import Job, SystemComposition, NodeSetting
JVM = jvms.JVM
# all job elements that are interesting for the user have to be enumerated here
__all__ = [
# job
'Job',
'NodeSetting',
'SystemComposition',
# jvms
'JVM',
... | Remove Edge from jobs package. | jobs: Remove Edge from jobs package.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy |
dbc16598a87403f52324bca3d50132fc9303ee90 | reviewboard/hostingsvcs/gitorious.py | reviewboard/hostingsvcs/gitorious.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name... | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name... | Fix the raw paths for Gitorious | Fix the raw paths for Gitorious
Gitorious have changed the raw orl paths, making impossible to use a Gitorious
repository.
This patch has been tested in production at
http://reviewboard.chakra-project.org/r/27/diff/#index_header
Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header
| Python | mit | KnowNo/reviewboard,brennie/reviewboard,1tush/reviewboard,chipx86/reviewboard,davidt/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,beol/reviewboard,1tush/reviewboard,brennie/reviewboard,custode/reviewboard,sgallagher/reviewboard,1tush/reviewbo... |
ae55577e4cea64a0052eb0c219641435c9c0210c | samples/model-builder/init_sample.py | samples/model-builder/init_sample.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Update init sample to import inside of function. | chore: Update init sample to import inside of function.
PiperOrigin-RevId: 485079470
| Python | apache-2.0 | googleapis/python-aiplatform,googleapis/python-aiplatform |
cba8ec4754ed3516ba3f873b0879c8379e8f93ab | data_structures/bitorrent/server/udp.py | data_structures/bitorrent/server/udp.py | #!/usr/bin/env python
import struct
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
class Announce(DatagramProtocol):
def parse_connection(self, data):
connection, action, transaction_id = struct.unpack("!qii", data)
message = struct.pack('!iiq', action, transac... | #!/usr/bin/env python
import struct
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from announce.torrent import Torrent
class Announce(DatagramProtocol):
def parse_connection(self, data):
connection, action, transaction_id = struct.unpack("!qii", data)
message... | Send back announce response to client | Send back announce response to client
| Python | apache-2.0 | vtemian/university_projects,vtemian/university_projects,vtemian/university_projects |
2ef0ccfbf337d0ef1870c5a1191b2bcdcffd1f9e | dbaas/backup/admin/log_configuration.py | dbaas/backup/admin/log_configuration.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "rete... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "rete... | Add new fields on LogConfiguration model | Add new fields on LogConfiguration model
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
446923b12942f351f2f40d035f0c1e6f9dcb8813 | __init__.py | __init__.py | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
# Add the third_party/ dir to our search path so that we can find the
# modules in there automatically. This isn't normal, so d... | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
# Add the third_party/ dir to our search path so that we can find the
# modules in there automatically. This isn't normal, so d... | Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts. | Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts.
If chromite is living inside the Chrome checkout under
<chrome_root>/src/third_party/chromite, its dependencies will be
checked out to <chrome_root>/src/third_party instead of the normal
chromite/third_party location due to git-submodule limitations ... | Python | bsd-3-clause | coreos/chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,zhang0137/chromite,chadversary/chromiumos.chromite,coreos/chromite,zhang0137/chromite,coreos/chromite,zhang0137/chromite,chadversary/chromiumos.chromite |
16cd3b501755c6d45b39b46ca8179cc0dc015125 | main/admin/lan.py | main/admin/lan.py | from django.contrib import admin
from django.forms import model_to_dict
from django.utils.timezone import now
from main.models import Lan, Event
class EventInline(admin.TabularInline):
model = Event
show_change_link = True
fields = ('name', 'url', 'start', 'end')
@admin.register(Lan)
class LanAdmin(ad... | from django.contrib import admin
from django.forms import model_to_dict
from django.utils.timezone import now
from main.models import Lan, Event
class EventInline(admin.TabularInline):
model = Event
show_change_link = True
fields = ('name', 'url', 'start', 'end')
@admin.register(Lan)
class LanAdmin(ad... | Remove schedule from admin too | Remove schedule from admin too
| Python | mit | bomjacob/htxaarhuslan,bomjacob/htxaarhuslan,bomjacob/htxaarhuslan |
f497259869ba0f920d8a7eaac45bd320566c4808 | examples/Interactivity/circlepainter.py | examples/Interactivity/circlepainter.py | size(800, 800)
import time
colormode(RGB)
speed(60)
def setup():
# ovallist is the list of ovals we created by moving the mouse.
global ovallist
stroke(0)
strokewidth(1)
ovallist = []
class Blob:
def __init__(self, x, y, c, r):
self.x, self.y = x, y
self.color = c
self... | size(800, 800)
import time
colormode(RGB)
speed(60)
def setup():
# ovallist is the list of ovals we created by moving the mouse.
global ovallist
stroke(0)
strokewidth(1)
ovallist = []
class Blob:
def __init__(self, x, y, c, r):
self.x, self.y = x, y
self.color = c
self... | Use of circle() instead of oval() | Use of circle() instead of oval()
| Python | mit | karstenw/nodebox-pyobjc,karstenw/nodebox-pyobjc |
1eb9830485ec82713d3e8d4d1e13ea1fdc1733c6 | airtable.py | airtable.py | import requests, json
import pandas as pd
class AT:
def __init__(self, base, api):
self.base = base
self.api = api
self.headers = {"Authorization": "Bearer "+self.api}
def getTable(self,table):
r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers)
j = r.json()
df = ... | import requests, json
import pandas as pd
class AT:
def __init__(self, base, api):
self.base = base
self.api = api
self.headers = {"Authorization": "Bearer "+self.api}
def getTable(self,table):
r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers)
j = r.json()
df = ... | Add quick error messaging for easier debugging | Add quick error messaging for easier debugging
| Python | mit | MeetMangrove/location-bot |
378b5679f9ca3b814eb0a2a89e9f8045ae4bc4c1 | FunctionHandler.py | FunctionHandler.py | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... | Clean up module loading printing | Clean up module loading printing
| Python | mit | HubbeKing/Hubbot_Twisted |
47d69320261a3126637229c9deaf02ba425998af | members/models.py | members/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.protocols.all()
| from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.meetings_attend.all()
def absent_m... | Add attended_meetings and absent_meetings methos to User class | Add attended_meetings and absent_meetings methos to User class
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
b261eb0b2180ebc07ace6c1abad4ec68d6c17840 | app/__init__.py | app/__init__.py | from __future__ import absolute_import
from __future__ import unicode_literals
# Import flask and template operators
from flask import Flask, request, render_template
# Define the WSGI application object
app = Flask(__name__)
# Configurations
app.config.from_object('config.default')
# Configure webhooks
from .webho... | from __future__ import absolute_import
from __future__ import unicode_literals
# Import flask and template operators
from flask import Flask, request, render_template
# Define the WSGI application object
app = Flask(__name__)
# Configurations
app.config.from_object('config.default')
# Configure webhooks
from .webho... | Configure slacker on app initialization | Configure slacker on app initialization
| Python | apache-2.0 | pipex/gitbot,pipex/gitbot,pipex/gitbot |
2917e089734ace4fd212ef9a16e8adf71d671312 | test/partial_double_test.py | test/partial_double_test.py | from doubles import allow, teardown
class User(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
class TestPartialDouble(object):
def test_stubs_real_object(self):
user = User('Alice')
allow(user).to_receive('get_name').and_return(... | from doubles import allow, teardown
class User(object):
def __init__(self, name, age):
self.name = name
self._age = age
@property
def age(self):
return self._age
def get_name(self):
return self.name
class TestPartialDouble(object):
def test_stubs_real_object(sel... | Test that only stubbed methods are altered on partial doubles. | Test that only stubbed methods are altered on partial doubles.
| Python | mit | uber/doubles |
b37eb87e73f049b87dcd0bf3cd3ff9be1ffaff4b | scripts/run_tests.py | scripts/run_tests.py | #!/usr/bin/env python
import optparse
import sys
from os import path
from os.path import expanduser
import unittest
import argparse
# Simple stand-alone test runner
# - Runs independently of appengine runner
# - So we need to find the GAE library
# - Looks for tests as ./tests/test*.py
# - Use --skipbasics to skip th... | #!/usr/bin/env python
import argparse
import optparse
from os import getenv, path
from os.path import expanduser
import sys
import unittest
# Simple stand-alone test runner
# - Runs independently of appengine runner
# - So we need to find the GAE library
# - Looks for tests as ./tests/test*.py
# - Use --skipbasics to... | Check APP_ENGINE env var before using hard-coded path to Google AppEngine SDK. | Check APP_ENGINE env var before using hard-coded path to Google AppEngine SDK.
| Python | apache-2.0 | hschema/schemaorg,schemaorg/schemaorg,pwz3n0/schemaorg,gkellogg/schemaorg,vholland/schemaorg,URXtech/schemaorg,schemaorg/schemaorg,cesarmarinhorj/schemaorg,sdo-sport/schemaorg,hschema/schemaorg,tfrancart/schemaorg,ya7lelkom/schemaorg,ynh/schemaorg,sdo-sport/schemaorg,twamarc/schemaorg,haonature/schemaorg,schemaorg/sche... |
1a61ba3655e575cbf4d20190182654cb677bce9c | app/grandchallenge/serving/tasks.py | app/grandchallenge/serving/tasks.py | from celery import shared_task
from django.db.models import F
from grandchallenge.serving.models import Download
@shared_task
def create_download(*_, **kwargs):
try:
d = Download.objects.get(**kwargs)
d.count = F("count") + 1
d.save()
except Download.DoesNotExist:
Download.obj... | from celery import shared_task
from django.db.models import F
from grandchallenge.serving.models import Download
@shared_task
def create_download(*_, **kwargs):
d, created = Download.objects.get_or_create(**kwargs)
if not created:
d.count = F("count") + 1
d.save()
| Fix race condition in create_download | Fix race condition in create_download
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
8c10f7a3112ecece857ee9c3d20076377f7196a0 | upload.py | upload.py | import os
import re
import datetime
from trovebox import Trovebox
def main():
try:
client = Trovebox()
client.configure(api_version=2)
except IOError, e:
print
print '!! Could not initialize Trovebox connection.'
print '!! Check that ~/.config/trovebox/default exists a... | import os
import re
import datetime
from trovebox import Trovebox
from trovebox.errors import TroveboxError
def main():
try:
client = Trovebox()
client.configure(api_version=2)
except IOError, e:
print
print '!! Could not initialize Trovebox connection.'
print '!! Chec... | Use full path as album name fallback. Support all Trovebox file types. | Use full path as album name fallback. Support all Trovebox file types.
| Python | mit | nip3o/trovebox-uploader |
b13c8b5cd0dde5d329a14b99c672307567992434 | workshop_drf/todo/serializers.py | workshop_drf/todo/serializers.py | from rest_framework import serializers
from . import models
class Category(serializers.ModelSerializer):
class Meta:
model = models.Category
class Task(serializers.ModelSerializer):
class Meta:
model = models.Task
| from rest_framework import serializers
from django.contrib.auth import get_user_model
from . import models
class Category(serializers.ModelSerializer):
class Meta:
model = models.Category
fields = ('id', 'name')
class Task(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(
... | Add human readable owner & categories. | Add human readable owner & categories.
| Python | mit | arnlaugsson/workshop_drf,xordoquy/workshop_drf_djangoconeu2015,pombredanne/workshop_drf_djangoconeu2015 |
8ddfcf45b4da91a02e12ebff2304e7ecf8a04378 | IPython/utils/importstring.py | IPython/utils/importstring.py | # encoding: utf-8
"""
A simple utility to import something by its string name.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is... | # encoding: utf-8
"""
A simple utility to import something by its string name.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is... | Restructure code to avoid unnecessary list slicing by using rsplit. | Restructure code to avoid unnecessary list slicing by using rsplit.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
531974ce5d621b903608aa226110277f77918167 | tools/reset_gids.py | tools/reset_gids.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import types
from sfa.storage.model import *
from sfa.storage.alchemy import *
from sfa.trust.gid import create_uuid
from sfa.trust.hierarchy import Hierarchy
from sfa.util.xrn import Xrn
from sfa.trust.certificate import Certificate, Keypair, convert_public_key
def fix_u... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import types
from sfa.storage.model import *
from sfa.storage.alchemy import *
from sfa.trust.gid import create_uuid
from sfa.trust.hierarchy import Hierarchy
from sfa.util.xrn import Xrn
from sfa.trust.certificate import Certificate, Keypair, convert_public_key
def fix_u... | Reset GIDs works even if user has no pub_key | Fix: Reset GIDs works even if user has no pub_key
| Python | mit | yippeecw/sfa,onelab-eu/sfa,onelab-eu/sfa,yippeecw/sfa,onelab-eu/sfa,yippeecw/sfa |
1a069e7a8565dcd72b362d6b4c0cc3b1b981e5a6 | Streamer/iterMapper.py | Streamer/iterMapper.py | #!/usr/bin/env python
from utils import read_input
from constants import EURISTIC_FACTOR
from collections import Counter
import sys
def choose_nodes(nodes, neighbours_iterable):
neighbours_count = len(neighbours_iterable)
unpacked_list = []
for t in neighbours_iterable:
unpacked_list += t[1:]
... | #!/usr/bin/env python
from utils import read_input
from constants import EURISTIC_FACTOR
from collections import Counter
import sys
def choose_nodes(nodes, neighbours_iterable):
neighbours_count = len(neighbours_iterable)
unpacked_list = []
for t in neighbours_iterable:
unpacked_list += t[1:]
... | Improve choose_nodes method (set problem) | Improve choose_nodes method (set problem)
| Python | mit | AldurD392/SubgraphExplorer,AldurD392/SubgraphExplorer,AldurD392/SubgraphExplorer |
1d1a64c8a98d98a243307dd58ec3874f0369ce8f | tests/ex12_tests.py | tests/ex12_tests.py | from nose.tools import *
from exercises import ex12
def test_histogram():
'''
Test our histogram output is correct
'''
test_histogram = ex12.histogram([1, 2, 3])
print(test_histogram)
assert_equal(test_histogram, '*\n**\n***\n')
| from nose.tools import *
from exercises import ex12
def test_histogram():
'''
Test our histogram output is correct
'''
test_histogram = ex12.histogram([1, 2, 3])
# assert_equal(test_histogram, '*\n**\n***\n')
| Drop ex12 tests for now. | Drop ex12 tests for now.
| Python | mit | gravyboat/python-exercises |
13da665f07be45f5c5b9308d0219250b368810d5 | tests/test_utils.py | tests/test_utils.py | import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all... | import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url, get_redirect_target
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
... | Add unit test for get_redirect_target utility function | Add unit test for get_redirect_target utility function
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary |
23e984fe24428241b873b93a4ca541b69d3345d2 | nipy/labs/viz_tools/test/test_cm.py | nipy/labs/viz_tools/test/test_cm.py | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
impo... | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
impo... | Fix tests on old MPL | BUG: Fix tests on old MPL
Old MPL do not have function-defined colormaps, so the corresponding
code path cannot be tested.
| Python | bsd-3-clause | alexis-roche/nipy,nipy/nipy-labs,arokem/nipy,arokem/nipy,alexis-roche/nipy,alexis-roche/nireg,alexis-roche/register,alexis-roche/niseg,alexis-roche/nipy,bthirion/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/register,arokem/nipy,nipy/nireg,nipy/nireg,bthirion/nipy,alexis-roche/nireg,alexis-roche/niseg,arokem/nipy,a... |
d348c4f7c60b599e713eeeda7ed6806c5b1baae0 | tests/explorers_tests/test_additive_ou.py | tests/explorers_tests/test_additive_ou.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
class ... | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
from chainer import testing
import numpy as np
from chainerrl.explorers.additive_o... | Add tests of non-scalar sigma for AddtiveOU | Add tests of non-scalar sigma for AddtiveOU
| Python | mit | toslunar/chainerrl,toslunar/chainerrl |
7baac2883aa6abc0f1f458882025ba1d0e9baab2 | app/migrations/versions/4ef20b76cab1_.py | app/migrations/versions/4ef20b76cab1_.py | """Enable PostGIS
Revision ID: 4ef20b76cab1
Revises: 55004b0f00d6
Create Date: 2015-02-11 20:49:42.303864
"""
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION postgis;")
... | """Enable PostGIS
Revision ID: 4ef20b76cab1
Revises: 55004b0f00d6
Create Date: 2015-02-11 20:49:42.303864
"""
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION IF NOT EXIS... | Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist. | Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist.
| Python | mit | openchattanooga/cpd-zones-old,openchattanooga/cpd-zones-old |
e697743b89f262a179881e2c58e2422a146248d0 | db_cleanup.py | db_cleanup.py | #!/usr/bin/env python
#
# Periodic cleanup job for blog comments.
# This will remove any abandoned comments that
# may have been posted by bots and did not get
# past the captcha.
#
# Use PYTHONPATH=<StackSmash dir to manage.py> ./db_cleanup.py
#
import os, datetime
def clean_up():
# Set Django settings module.
os.... | #!/usr/bin/env python
#
# Periodic cleanup job for blog comments.
# This will remove any abandoned comments that
# may have been posted by bots and did not get
# past the captcha.
#
# Use PYTHONPATH=<StackSmash dir to manage.py> ./db_cleanup.py
#
# Cronjob to run on the 12th hour of every day:
# * 12 * * * PYTHONPATH=/... | Add cron information, clean up old cruft that isnt needed. | Add cron information, clean up old cruft that isnt needed.
| Python | bsd-2-clause | Justasic/StackSmash,Justasic/StackSmash |
6e6aaac438a18220db20ad480a8a82af49c44caa | pages/serializers.py | pages/serializers.py | from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regio... | from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regio... | Add 'view_name' to url extra kwargs | Add 'view_name' to url extra kwargs
| Python | bsd-2-clause | incuna/feincms-pages-api |
fb7b9618d5e54e8500efb0904913b4febf80222c | catsnap/batch/image_batch.py | catsnap/batch/image_batch.py | from __future__ import unicode_literals
from catsnap import Client, HASH_KEY
from boto.dynamodb.batch import BatchList
import json
MAX_ITEMS_TO_REQUEST = 99
def get_images(filenames):
if not filenames:
raise StopIteration
filenames = list(filenames)
unprocessed_keys = filenames[MAX_ITEMS_TO_REQUE... | from __future__ import unicode_literals
from catsnap import Client, HASH_KEY
from boto.dynamodb.batch import BatchList
import json
MAX_ITEMS_TO_REQUEST = 99
def get_image_items(filenames):
if not filenames:
raise StopIteration
filenames = list(filenames)
unprocessed_keys = filenames[MAX_ITEMS_TO_... | Break get_images up to match get_tags | Break get_images up to match get_tags
| Python | mit | ErinCall/catsnap,ErinCall/catsnap,ErinCall/catsnap |
39d370f314431e44e7eb978865be4f7696625eec | scraper/models.py | scraper/models.py | from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.... | from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.... | Order entries in table by year, then title | Order entries in table by year, then title
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker |
9c3c5ede82b6672f23b5aec90cdbadb57ca8b92c | construi/cli.py | construi/cli.py | from .config import parse
from .target import Target
from .__version__ import __version__
from argparse import ArgumentParser
import logging
import os
import sys
def main():
setup_logging()
parser = ArgumentParser(prog='construi', description='Run construi')
parser.add_argument('target', metavar='TARG... | from .config import parse
from .target import Target
from .__version__ import __version__
from argparse import ArgumentParser
import logging
import os
import sys
def main():
setup_logging()
parser = ArgumentParser(prog='construi', description='Run construi')
parser.add_argument('target', metavar='TARG... | Add -T option to list available targets | Add -T option to list available targets
| Python | apache-2.0 | lstephen/construi |
a754323facdb05b18d19a1a0365ad12e8c25ed06 | ocradmin/core/tests/test_core.py | ocradmin/core/tests/test_core.py | """
Core tests. Test general environment.
"""
import subprocess as sp
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.conf import settings
class CoreTest(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
... | """
Core tests. Test general environment.
"""
import subprocess as sp
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.conf import settings
class CoreTest(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
... | Test the presence of various tools | Test the presence of various tools
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
9c5c2f916f8f8fceb38848212d7c4d8883fd2aef | polling_stations/apps/api/mixins.py | polling_stations/apps/api/mixins.py | from rest_framework.decorators import list_route
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
class LargeResultsSetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 1000
class PollingEntityMixin():
pagination_class = LargeResu... | from rest_framework.decorators import list_route
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
class LargeResultsSetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 1000
class PollingEntityMixin():
pagination_class = LargeResu... | Return object not array when requesting single district/station | Return object not array when requesting single district/station
If we are requesting a single polling station or district
return an object instead of an array with length 1
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
dcd39f2955cd80e3888458954a58203ae74dab71 | cyder/base/eav/forms.py | cyder/base/eav/forms.py | from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.constants import ATTRIBUTE_TYPES
from cyder.base.eav.models import Attribute
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'inst... | from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.constants import ATTRIBUTE_TYPES
from cyder.base.eav.models import Attribute
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'inst... | Set EAV form class name to match EAV model name | Set EAV form class name to match EAV model name
(for easier debugging, at least in theory)
| Python | bsd-3-clause | murrown/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,akeym/cyder,murrown/cyder,murrown/cyder,murrown/cyder,zeeman/cyder,zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder |
43e43e9f342d69bd2b0652d833e204916517efe2 | module_auto_update/migrations/10.0.2.0.0/pre-migrate.py | module_auto_update/migrations/10.0.2.0.0/pre-migrate.py | # -*- coding: utf-8 -*-
# Copyright 2018 Tecnativa - Jairo Llopis
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import logging
from psycopg2 import IntegrityError
from odoo.addons.module_auto_update.models.module_deprecated import \
PARAM_DEPRECATED
_logger = logging.getLogger(__name__)
def mi... | # -*- coding: utf-8 -*-
# Copyright 2018 Tecnativa - Jairo Llopis
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import logging
from psycopg2 import IntegrityError
from odoo.addons.module_auto_update.models.module_deprecated import \
PARAM_DEPRECATED
_logger = logging.getLogger(__name__)
def mi... | Rollback cursor if param exists | [FIX] module_auto_update: Rollback cursor if param exists
Without this patch, when upgrading after you have stored the deprecated features parameter, the cursor became broken and no more migrations could happen. You got this error:
Traceback (most recent call last):
File "/usr/local/bin/odoo", line 6, in <mod... | Python | agpl-3.0 | Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools |
82c31412190e42f98ce65d5ad1a6a9b8faad2cb6 | lcd_ticker.py | lcd_ticker.py | #!/usr/bin/env python
"""Display stock quotes on LCD"""
import ystockquote as y
from lcd import lcd_string, tn
symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK', 'DIS', 'GM', 'GE',
'BAC', 'IBM', 'C', 'AMZN', 'AET', 'DOW', 'INTC', 'PFE', 'MRK',
'RTN']
def compact_quote(symbol):
symbo... | #!/usr/bin/env python
"""Display stock quotes on LCD"""
import ystockquote as y
from lcd import lcd_string, tn
symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK', 'DIS', 'GM', 'GE',
'BAC', 'IBM', 'C', 'AMZN', 'AET', 'DOW', 'INTC', 'PFE', 'MRK',
'RTN']
def compact_quote(symbol):
a = y... | Handle when N/A comes thru the quote. | Handle when N/A comes thru the quote.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie |
b9dde5e9fc56feaea581cecca3f919f4e053044d | brumecli/config.py | brumecli/config.py | import os
import yaml
from subprocess import check_output, CalledProcessError
from colors import red
from jinja2 import Template
class Config():
@staticmethod
def load(config_file='brume.yml'):
"""Return the YAML configuration for a project based on the `config_file` template."""
template_fu... | import os
import yaml
from subprocess import check_output, CalledProcessError
from colors import red
from jinja2 import Template
class Config():
@staticmethod
def env(key):
"""Return the value of the `key` environment variable."""
try:
return os.environ[key]
except KeyErr... | Move template functions out of `Config.load()` | Move template functions out of `Config.load()`
| Python | mit | flou/brume,geronimo-iia/brume |
fe42da2e9c642c7e4f8b480012e9455ffcb294a0 | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | # -*- coding: utf-8 -*-
from openerp import fields, models
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to iden... | # -*- coding: utf-8 -*-
from openerp import api, fields, models
'''
This module create model of Course
'''
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | deivislaya/openacademy-project |
b27a09e67d737310ec419eb76a39e667316184f0 | userprofile/forms.py | userprofile/forms.py | from datetime import datetime
from django import forms
from news.forms import MaterialFileWidget
from .models import Profile
class ProfileSearchForm(forms.Form):
name = forms.CharField(max_length=200)
class ProfileForm(forms.ModelForm):
image = forms.FileField(required=False, widget=MaterialFileWidget)
... | from datetime import datetime, timedelta
from django import forms
from news.forms import MaterialFileWidget
from .models import Profile
class ProfileSearchForm(forms.Form):
name = forms.CharField(max_length=200)
class ProfileForm(forms.ModelForm):
image = forms.FileField(required=False, widget=MaterialFi... | Add 24 hour waiting time for removing phone number after reservation | Add 24 hour waiting time for removing phone number after reservation
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website |
b8a1e049024289a0665c5bff3ecdf60cf3e63825 | typhon/spareice/__init__.py | typhon/spareice/__init__.py | # -*- coding: utf-8 -*-
"""All SPARE-ICE related modules."""
from typhon.spareice.collocations import * # noqa
from typhon.spareice.common import * # noqa
from typhon.spareice.datasets import * # noqa
__all__ = [s for s in dir() if not s.startswith('_')]
| # -*- coding: utf-8 -*-
"""All SPARE-ICE related modules."""
from typhon.spareice.array import *
from typhon.spareice.collocations import * # noqa
from typhon.spareice.common import * # noqa
from typhon.spareice.datasets import * # noqa
__all__ = [s for s in dir() if not s.startswith('_')]
| Add array submodule to standard import | Add array submodule to standard import
| Python | mit | atmtools/typhon,atmtools/typhon |
12b46a902f1596c0559e6e7d3faf6ea7b812a800 | api/radar_api/tests/conftest.py | api/radar_api/tests/conftest.py | import string
import random
import pytest
from radar_api.app import create_app
from radar.database import db
@pytest.fixture(scope='session')
def app():
return create_app({
'TESTING': True,
'SQLALCHEMY_DATABASE_URI': 'postgres://postgres@localhost/radar_test',
'SECRET_KEY': ''.join(rando... | import string
import random
import pytest
from radar_api.app import create_app
from radar.database import db
@pytest.fixture(scope='session')
def app():
return create_app({
'TESTING': True,
'SQLALCHEMY_DATABASE_URI': 'postgres://postgres@localhost/radar_test',
'SECRET_KEY': ''.join(rando... | Add UKRDC_PATIENT_SEARCH_URL to test app config | Add UKRDC_PATIENT_SEARCH_URL to test app config
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar |
73caeecd963326f4789eb3dc484e59ffb475e12f | blankspot_stats.py | blankspot_stats.py | #! /usr/bin/env python
import MapGardening
import optparse
usage = "usage: %prog [options]"
p = optparse.OptionParser(usage)
p.add_option('--place', '-p',
default="all"
)
options, arguments = p.parse_args()
possible_tables = [
'hist_point',
'hist_poin... | #! /usr/bin/env python
"""
Calculate statistics for each study area, and prints results to stdout.
All it prints is the number of blankspots, the number of v1 nodes,
and the number of total nodes. Since I am no longer storing the blankspot
information in the hist_point table itself, these stats are no longer very inf... | Add docstring, change tables searched | Add docstring, change tables searched
| Python | mit | almccon/mapgardening,almccon/mapgardening,almccon/mapgardening,almccon/mapgardening |
b97842ecf1c8fa22b599353c1c7fe75fcf482702 | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import (split_translated_fieldname,
transform_translatable_fields)
from modeltrans.utils import build_localized_fieldname
from tests.app.models import Blog
class U... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (build_localized_fieldname,
split_translated_fieldname)
from tests.app.models import Blog
class Uti... | Use proper import from utils | Use proper import from utils
| Python | bsd-3-clause | zostera/django-modeltrans,zostera/django-modeltrans |
a9d4fab047249fbf5db26385779902d0f7483057 | qsimcirq/__init__.py | qsimcirq/__init__.py | from .qsim_circuit import *
from .qsim_simulator import *
from .qsimh_simulator import *
| from .qsim_circuit import add_op_to_opstring, add_op_to_circuit, QSimCircuit
from .qsim_simulator import QSimSimulatorState, QSimSimulatorTrialResult, QSimSimulator
from .qsimh_simulator import QSimhSimulator
| Replace star imports to fix mypy issue. | Replace star imports to fix mypy issue.
| Python | apache-2.0 | quantumlib/qsim,quantumlib/qsim,quantumlib/qsim,quantumlib/qsim |
f5592efd0cf780c6e97483a16820f98478be8e3d | devil/devil/android/sdk/version_codes.py | devil/devil/android/sdk/version_codes.py | # Copyright 2015 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.
"""Android SDK version codes.
http://developer.android.com/reference/android/os/Build.VERSION_CODES.html
"""
JELLY_BEAN = 16
JELLY_BEAN_MR1 = 17
JELLY_BEAN... | # Copyright 2015 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.
"""Android SDK version codes.
http://developer.android.com/reference/android/os/Build.VERSION_CODES.html
"""
JELLY_BEAN = 16
JELLY_BEAN_MR1 = 17
JELLY_BEAN... | Add NOUGAT version code constant. | Add NOUGAT version code constant.
Review-Url: https://codereview.chromium.org/2386453002
| Python | bsd-3-clause | sahiljain/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,sahiljain/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,benschmaus/catapult,sahiljain/catap... |
70863101a882eee0811460cf9bf0f8442d9b0775 | djproxy/urls.py | djproxy/urls.py | from django.conf.urls import patterns
from djproxy.views import HttpProxy
def generate_routes(config):
routes = []
for service_name, proxy_config in config.items():
ProxyClass = type(
'ProxyClass',
(HttpProxy, ),
{'base_url': proxy_config['base_url']}
)
... | import re
from django.conf.urls import patterns, url
from djproxy.views import HttpProxy
def generate_routes(config):
routes = ()
for service_name, proxy_config in config.items():
base_url = proxy_config['base_url']
prefix = proxy_config['prefix']
ProxyClass = type('ProxyClass', (Ht... | Return a `patterns` rather than a list of tuples | Return a `patterns` rather than a list of tuples
| Python | mit | thomasw/djproxy |
48ef416352870ae5c695ada006f1855d03d893df | dlexperiment.py | dlexperiment.py | class Experiment(object):
def __init__(self, epochs=1):
self.epochs = epochs
def get_epochs(self):
return self.epochs
def train(self):
raise NotImplementedError
def test(self):
raise NotImplementedError
def set_loss(self):
raise NotImplementedError
de... | class Experiment(object):
def __init__(self, model, optimizer, train_data, test_data, epochs=1):
self.model = model
self.optimizer = optimizer
self.train_data = train_data
self.test_data = test_data
self.epochs = epochs
self.loss = 0
self.current_epoch = 0
... | Add necessary params to Experiment. | Add necessary params to Experiment.
| Python | apache-2.0 | sagelywizard/dlex |
05e8170326c5aa2be48eee5f90ab5a3919775e01 | io_EDM/__init__.py | io_EDM/__init__.py |
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,0,1),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_oper... |
bl_info = {
'name': "Import: .EDM model files",
'description': "Importing of .EDM model files",
'author': "Nicholas Devenish",
'version': (0,0,1),
'blender': (2, 78, 0),
'location': "File > Import/Export > .EDM Files",
'category': 'Import-Export',
}
try:
import bpy
def register():
from .io_oper... | Remove potential duplicate registration code | Remove potential duplicate registration code
Was sometimes causing an error when importing the project
| Python | mit | ndevenish/Blender_ioEDM,ndevenish/Blender_ioEDM |
f8fe7041d209bb83e8483180824ffa73ceaa5f52 | ckanny/__init__.py | ckanny/__init__.py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, divisi... | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, divisi... | Move version num to own line | Move version num to own line | Python | mit | reubano/ckanny,reubano/ckanny |
899cf1aa2bc274602a7f9b2ef315ed67239f955a | examples/inprocess/embedded_qtconsole.py | examples/inprocess/embedded_qtconsole.py | import os
from IPython.qt.console.qtconsoleapp import IPythonQtConsoleApp
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
from IPython.lib import guisupport
from IPython.utils import path
def print_process_id():
print 'Process ID is:'... | import os
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
from IPython.lib import guisupport
def print_process_id():
print 'Process ID is:', os.getpid()
def main():
# Print the ID of the main process
print_process_id()
... | Revert config-loading change in embedding example. | Revert config-loading change in embedding example.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
ae324434fb00a46eae45d8218954950947bd636c | test_board_pytest.py | test_board_pytest.py | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board... | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board... | Add test checking board can't get overfilled. | Add test checking board can't get overfilled.
| Python | mit | isaacarvestad/four-in-a-row |
9437b7fa2ef7f581968d6628561940dcb1e3f4ad | test_tws/__init__.py | test_tws/__init__.py | '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__... | '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__... | Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params. | Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params. | Python | bsd-3-clause | kbluck/pytws,kbluck/pytws |
87c6a222c7e979c2e44ecf152158bfcbe3b61d2a | calaccess_processed/managers.py | calaccess_processed/managers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for working with CAL-ACCESS processed data models.
"""
from __future__ import unicode_literals
import os
from django.db import models, connection
class ProcessedDataManager(models.Manager):
"""
Utilities for loading raw CAL-ACCESS data into proc... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for working with CAL-ACCESS processed data models.
"""
from __future__ import unicode_literals
import os
from django.db import models, connection
class ProcessedDataManager(models.Manager):
"""
Utilities for loading raw CAL-ACCESS data into proc... | Fix path to .sql files | Fix path to .sql files
| Python | mit | california-civic-data-coalition/django-calaccess-processed-data,california-civic-data-coalition/django-calaccess-processed-data |
334b3e1bbda58439020131fe178db1e72cbf662a | 2/Solution.py | 2/Solution.py | from ListNode import *
class Solution():
def addTwoNumbers(self, l1, l2):
current_node = ListNode(None)
head_node = current_node
carry = 0
p = l1
q = l2
while p or q or carry:
x = y = 0
if p is not None:
x = p.val
... | from ListNode import *
class Solution():
def addTwoNumbers(self, l1, l2):
head_node = current_node = ListNode(None)
carry = 0
p = l1
q = l2
while p or q or carry:
x = y = 0
if p is not None:
x = p.val
p = p.next
... | Refactor build and print method | Refactor build and print method
| Python | mit | xliiauo/leetcode,xiao0720/leetcode,xiao0720/leetcode,xliiauo/leetcode,xliiauo/leetcode |
edb10e7ae1f428dade04a9976c3b3f985065d458 | settings/__init__.py | settings/__init__.py | # -*- coding: utf-8 -*-
from __future__ import print_function
# Standard Library
import sys
if "test" in sys.argv:
print("\033[1;91mNo django tests.\033[0m")
print("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
from .common import * # noqa
try:
from .dev import * # noqa
from .prod import * # no... | # -*- coding: utf-8 -*-
from __future__ import print_function
# Standard Library
import sys
if "test" in sys.argv:
print("\033[1;91mNo django tests.\033[0m")
print("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
from .common import * # noqa
try:
from .dev import * # noqa
except ImportError:
pass
... | Make sure prod.py is read in settings | Make sure prod.py is read in settings
| Python | mit | hTrap/junction,farhaanbukhsh/junction,ChillarAnand/junction,farhaanbukhsh/junction,akshayaurora/junction,NabeelValapra/junction,pythonindia/junction,shashisp/junction,hTrap/junction,ChillarAnand/junction,shashisp/junction,nava45/junction,NabeelValapra/junction,shashisp/junction,farhaanbukhsh/junction,akshayaurora/junct... |
b7db1d067c8efe86a6ab39a15fef0ab878656249 | uber/__init__.py | uber/__init__.py | import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber... | import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber... | Revert "Don't make dirs on startup" | Revert "Don't make dirs on startup"
This reverts commit 17243b31fc6c8d8f4bb0dc7e11e2601800e80bb0.
| Python | agpl-3.0 | magfest/ubersystem,magfest/ubersystem,magfest/ubersystem,magfest/ubersystem |
84bb5fbef5c98bdee344ac9d9739f035bd9a8f7b | tooz/drivers/zake.py | tooz/drivers/zake.py | # Copyright (c) 2013-2014 Mirantis Inc. 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 applica... | # Copyright (c) 2013-2014 Mirantis Inc. 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 applica... | Change inline docs about class fake storage variable | Change inline docs about class fake storage variable
Adjust the docs to better describe why a fake storage
class attribute exists and how it is used and what it
represents compared to a real zookeeper setup.
Change-Id: I255ccd83c8033266e9cee09a343468ae4e0f2bfd
| Python | apache-2.0 | citrix-openstack-build/tooz,openstack/tooz,citrix-openstack-build/tooz,openstack/tooz |
40493966b989e73a07f6a33bd9e9497ae9ad9f3f | user/admin.py | user/admin.py | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'get_name',
'email',
'get_date_joined',
'is_staff',
'is_superuser')
list_display_links = ('get_name', 'email')
list_f... | from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# list view
list_display = (
'get_name',
'email',
'get_date_joined',
'is_staff',
'is_superuser')
list_display_links = ('get_name', 'email')
list_f... | Remove password from UserAdmin fieldsets. | Ch23: Remove password from UserAdmin fieldsets.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
01b15e2df498706a342009e300c77168032c7824 | fbmsgbot/bot.py | fbmsgbot/bot.py | from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completio... | from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message):
response, error = self.cli... | Refactor send_message to remove completion block | Refactor send_message to remove completion block
| Python | mit | ben-cunningham/python-messenger-bot,ben-cunningham/pybot |
bf53b5a1e6562162ba9c3f89568ebfeb0124249d | athenet/layers/pool.py | athenet/layers/pool.py | """Pooling layer."""
from theano.tensor.signal import downsample
from athenet.layers import Layer
class MaxPool(Layer):
"""Max-pooling layer."""
def __init__(self, poolsize, stride=None):
"""Create max-pooling layer.
:poolsize: Pooling factor in the format (height, width).
:stride: ... | """Pooling layer."""
from theano.tensor.signal import downsample
from athenet.layers import Layer
class MaxPool(Layer):
"""Max-pooling layer."""
def __init__(self, poolsize, stride=None):
"""Create max-pooling layer.
:poolsize: Pooling factor in the format (height, width).
:stride: ... | Change stride semantic in MaxPool | Change stride semantic in MaxPool
| Python | bsd-2-clause | heurezjusz/Athenet,heurezjusz/Athena |
f56ed1c14b87e4d28e8e853cf64d91cf756576d1 | dashboard/tasks.py | dashboard/tasks.py | import json
import requests
from bitcoinmonitor.celeryconfig import app
from channels import Group
app.conf.beat_schedule = {
'add-every-30-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 6.0,
'args': ("dale",)
},
}
@app.task
def get_bitcoin_price(arg):
last... | import json
from bitcoinmonitor.celeryconfig import app
from channels import Group
from .helpers import get_coin_price
app.conf.beat_schedule = {
'get-bitcoin-price-every-five-seconds': {
'task': 'dashboard.tasks.get_bitcoin_price',
'schedule': 5.0,
},
'get-litecoin-price-every-five-secon... | Create another task to get the litecoin price | Create another task to get the litecoin price
| Python | mit | alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor |
8d53a7478a139770d9ffb241ec2985123c403845 | bookmarks/bookmarks/models.py | bookmarks/bookmarks/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=T... | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings
from taggit.managers import TaggableManager
import requests
class Bookmark(models.Model):
title = models.CharField(max_length=200, blank=T... | Remove attachment and use slack link unfurling | Remove attachment and use slack link unfurling
| Python | mit | tom-henderson/bookmarks,tom-henderson/bookmarks,tom-henderson/bookmarks |
abe9be5cc9789b7b1c091f08b23655f903d71fb2 | apps/impala/src/impala/tests.py | apps/impala/src/impala/tests.py | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | Fix test looking for Impala icon | [impala] Fix test looking for Impala icon
Use regexp in tests for matching white spaces and new lines
| Python | apache-2.0 | xiangel/hue,xiangel/hue,GitHublong/hue,kawamon/hue,kawamon/hue,rahul67/hue,cloudera/hue,lumig242/Hue-Integration-with-CDAP,dulems/hue,xq262144/hue,sanjeevtripurari/hue,epssy/hue,rahul67/hue,pwong-mapr/private-hue,x303597316/hue,ahmed-mahran/hue,epssy/hue,ChenJunor/hue,sanjeevtripurari/hue,abhishek-ch/hue,epssy/hue,xian... |
5841590444d202e6fb1fe8d7d937807ff9805677 | astropy/table/tests/test_row.py | astropy/table/tests/test_row.py | import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
table = Table([self.a, self.b]... | import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
self.t = Table([self.a, self.b])
def test_subclass(self):
"""Row is subclass of ndarray and Row"... | Add a (skipped) test for row slice assignment. | Add a (skipped) test for row slice assignment.
E. Bray requested the ability to assign to a table via a row with
slice assignment, e.g.
row = table[2]
row[2:5] = [2, 3, 4]
row[:] = 3
This does not currently work because np.void (which is what numpy
returns for structured array row access) does not support slice
assi... | Python | bsd-3-clause | bsipocz/astropy,lpsinger/astropy,MSeifert04/astropy,larrybradley/astropy,bsipocz/astropy,astropy/astropy,kelle/astropy,DougBurke/astropy,stargaser/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,dhomeier/astropy,DougBurke/astropy,lpsinger/astropy,astropy/astropy,tbabej/astropy,joergdietrich/astropy,funbaker/ast... |
7faeebea3186443055cd8dd5e02137339c048ac9 | src/ggrc_basic_permissions/roles/ProgramOwner.py | src/ggrc_basic_permissions/roles/ProgramOwner.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a ... | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a ... | Add support for creating snapshots for program owner | Add support for creating snapshots for program owner
| Python | apache-2.0 | AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core |
ce95fbb56d7b331c0d1f55f6f6f8fc32b1e0f135 | datastories/admin.py | datastories/admin.py | from models import Story, Page, StoryPage
from django.contrib import admin
admin.site.register(Story)
admin.site.register(Page)
admin.site.register(StoryPage)
| from models import Story, Page, StoryPage
from django.contrib import admin
class StoryAdmin(admin.ModelAdmin):
list_display = ('title', 'slug')
prepopulated_fields = dict(slug=['title'])
exclude = ('owner',)
# Uncomment the stuff below to automate keeping creator as owner
# and restricting editing to own... | Add a StoryAdmin to hide owner. | Add a StoryAdmin to hide owner.
Also has comment out code for automating owner and restrincting
editing of a story to its owner and superuser. We can decide
whether we want it later (untested).
| Python | bsd-3-clause | MAPC/masshealth,MAPC/masshealth |
c0f37084b587e142aaadfa2c803d40bb9c4e55fe | website/project/metadata/authorizers/__init__.py | website/project/metadata/authorizers/__init__.py | import json
import os
import logging
logger = logging.getLogger(__name__)
HERE = os.path.dirname(os.path.realpath(__file__))
groups = json.load(
open(
os.path.join(HERE, 'defaults.json')
)
)
fp = None
try:
fp = open('{0}/local.json'.format(HERE))
except IOError:
logger.info('No local.json fou... | import json
import os
import logging
logger = logging.getLogger(__name__)
HERE = os.path.dirname(os.path.realpath(__file__))
groups = None
with open(os.path.join(HERE, 'defaults.json')) as defaults:
groups = json.load(defaults)
fp = None
try:
fp = open('{0}/local.json'.format(HERE))
except IOError:
logg... | Use context manager for filepointer management | Use context manager for filepointer management
| Python | apache-2.0 | kch8qx/osf.io,wearpants/osf.io,pattisdr/osf.io,cwisecarver/osf.io,billyhunt/osf.io,crcresearch/osf.io,baylee-d/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,sloria/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,samanehsan/osf.io,asanfilippo7/osf.io,felliott/osf.io,jnayak1/osf.io,brandon... |
dbd92c4fd50f81ee23387636fddff827da8fb7f3 | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):... | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):... | Fix in output to help command. | Fix in output to help command.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli |
b4d9fb47e040b199f88cffb4a0b761c443f390b4 | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
... | # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):... | Update in output to terminal. | Update in output to terminal.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli |
44e50483a4ba9a4c47ee092d8d807930340c4e8e | testClient.py | testClient.py | #!/usr/bin/env python
"""
Binary memcached test client.
Copyright (c) 2007 Dustin Sallings <dustin@spy.net>
"""
import sys
import socket
import random
import struct
from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET
if __name__ == '__main__':
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... | #!/usr/bin/env python
"""
Binary memcached test client.
Copyright (c) 2007 Dustin Sallings <dustin@spy.net>
"""
import sys
import socket
import random
import struct
from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET, EXTRA_HDR_FMTS
from testServer import CMD_SET, CMD_ADD, CMD_REPLACE
if __name__ == '_... | Allow mutation commands from the test client. | Allow mutation commands from the test client.
| Python | mit | dustin/memcached-test |
a0db97549a64595cb30554ccb583f928f4ad430d | api/models.py | api/models.py | import json
from django.db import models
import requests
from Suchary.settings import GCM_API_KEY
class Device(models.Model):
registration_id = models.TextField()
android_id = models.TextField(unique=True)
alias = models.TextField(blank=True)
version = models.CharField(max_length=20)
model = mod... | import json
from django.db import models
import requests
from Suchary.settings import GCM_API_KEY
class Device(models.Model):
registration_id = models.TextField()
android_id = models.TextField(unique=True)
alias = models.TextField(blank=True)
version = models.CharField(max_length=20)
model = mod... | Fix Device model, not needed to set last_seen on creation | Fix Device model, not needed to set last_seen on creation
| Python | mit | jchmura/suchary-django,jchmura/suchary-django,jchmura/suchary-django |
83c5cc34539f68360cbab585af9465e95f3ec592 | tensorbayes/__init__.py | tensorbayes/__init__.py | from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function
| import sys
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function
if 'ipykernel' in sys.argv[0]:
from . import nbutils
| Add nbutils import to base import | Add nbutils import to base import
| Python | mit | RuiShu/tensorbayes |
e5812200c68a720345310e9a14ffa2a1a8f849e0 | arg-reader.py | arg-reader.py | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, p... | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text
import argparse
from arg... | Format description to multiple lines using RawTextHelpFormatter. | Format description to multiple lines using RawTextHelpFormatter.
Reference:
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text
| Python | mit | beepscore/argparse |
39c4d50b08f92a5d76ac5864e13a3427e7dfd86a | app/accounts/tests/test_models.py | app/accounts/tests/test_models.py | from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from app.accounts.models import UserProfile
class UserProfileTest(TestCase):
"""Test UserProfile model"""
def setUp(self):
self.user = User.objects.create(username='frank', password='sec... | from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCase
from app.accounts.models import UserProfile
class UserProfileTest(TestCase):
"""Test UserProfile model"""
def setUp(self):
self.user = User.objects.create(username='frank', password='sec... | Add test for creating profile on user creation | Add test for creating profile on user creation
| Python | mit | teamtaverna/core |
4007508e10d730068e7f0a2ded0a7403525051a4 | checklisthq/checklisthq/urls.py | checklisthq/checklisthq/urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^users/new$', 'main.views.new_user', name="new_user"),
url(r'^... | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^users/new$', 'main.views.new_user', name="new_user"),
url(r'^... | Reorder URLs, catchall at the end | Reorder URLs, catchall at the end
| Python | agpl-3.0 | checklisthq/checklisthq.com,checklisthq/checklisthq.com |
265f36fb7fac426d662fbdebf29e8aad01e257d2 | flask_oauthlib/utils.py | flask_oauthlib/utils.py | # coding: utf-8
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.headers)
if 'wsgi.input' in headers:
del headers['... | # coding: utf-8
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
def extract_params():
"""Extract request params."""
uri = request.url
http_method = request.method
headers = dict(request.headers)
if 'wsgi.input' in headers:
del headers['... | Fix to_bytes when text is None | Fix to_bytes when text is None
| Python | bsd-3-clause | tonyseek/flask-oauthlib,auerj/flask-oauthlib,icook/flask-oauthlib,RealGeeks/flask-oauthlib,Fleurer/flask-oauthlib,CoreyHyllested/flask-oauthlib,huxuan/flask-oauthlib,landler/flask-oauthlib,lepture/flask-oauthlib,lepture/flask-oauthlib,tonyseek/flask-oauthlib,CommonsCloud/CommonsCloud-FlaskOAuthlib,brightforme/flask-oau... |
c480ed20fd5b7c5d53b4f0112feed801cd99ef9c | tests/test_data_prep.py | tests/test_data_prep.py | import os
import pandas as pd
import numpy.testing as npt
from gypsy import DATA_DIR
from gypsy.data_prep import prep_standtable
def test_prep_standtable():
data_file_name = 'raw_standtable.csv'
plot_data = pd.read_csv(os.path.join(DATA_DIR, data_file_name))
expected_data_path = os.path.join(
DAT... | import os
import pandas as pd
import numpy.testing as npt
from gypsy import DATA_DIR
from gypsy.data_prep import prep_standtable
def test_prep_standtable():
data_file_name = 'raw_standtable.csv'
plot_data = pd.read_csv(os.path.join(DATA_DIR, data_file_name))
expected_data_path = os.path.join(
DAT... | Use allclose for dataprep test | Use allclose for dataprep test
| Python | mit | tesera/pygypsy,tesera/pygypsy |
07455e5821d21c988c7c5fcda9345e99355eb4e7 | redash/__init__.py | redash/__init__.py | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=sett... | Use database number from redis url if available. | Use database number from redis url if available.
| Python | bsd-2-clause | chriszs/redash,imsally/redash,44px/redash,guaguadev/redash,denisov-vlad/redash,rockwotj/redash,44px/redash,rockwotj/redash,getredash/redash,ninneko/redash,akariv/redash,amino-data/redash,akariv/redash,imsally/redash,EverlyWell/redash,getredash/redash,easytaxibr/redash,M32Media/redash,vishesh92/redash,ninneko/redash,get... |
4139dafb967c61ac8d10b3b9fa8d64c8c079bfa2 | scripts/png2raw.py | scripts/png2raw.py | #!/usr/bin/env python
import Image
import logging
import sys
def main(argv):
pngFileName = sys.argv[1]
baseFileName, _ = pngFileName.rsplit('.')
rawFileName = '%s.raw' % baseFileName
palFileName = '%s.pal' % baseFileName
image = Image.open(pngFileName)
with open(palFileName, 'w') as palFile:
pal = ... | #!/usr/bin/env python
import Image
import argparse
import os
def main():
parser = argparse.ArgumentParser(
description='Converts input image to raw image and palette data.')
parser.add_argument('-f', '--force', action='store_true',
help='If output files exist, the tool will overwrite them.')
parser.... | Add cmdline options parser and a sanity check. | Add cmdline options parser and a sanity check.
| Python | artistic-2.0 | cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene,cahirwpz/demoscene |
3c4f7906f98e6dfb9afe6993bee993ed05b969f3 | apps/splash/views.py | apps/splash/views.py | import datetime
from django.shortcuts import render
from apps.splash.models import SplashEvent, SplashYear
def index(request):
# I'm really sorry ...
splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180)))
return render(request, 'splash/base.html', {'splas... | import datetime
from django.shortcuts import render
from apps.splash.models import SplashEvent, SplashYear
def index(request):
# I'm really sorry ...
splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180)))
return render(request, 'splash/base.html', {'splas... | Add method for merging duplicated events | Add method for merging duplicated events
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
7b108ec9392c70113a5f5bf04e104de1fe123815 | autosort/wrapping.py | autosort/wrapping.py | def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = 0, limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if i == j or score < best and psum >= 0:
best ... | def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = float('inf'), limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if score < best and (psum >= 0 or i == j):
... | Make it clearer that exactly one item allows psum < 0 | Make it clearer that exactly one item allows psum < 0
| Python | mit | fbergroth/autosort |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.