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 |
|---|---|---|---|---|---|---|---|---|---|
0b8cf8f8942c59432ead113dd7c0e55360946c16 | masters/master.chromium.linux/master_site_config.py | masters/master.chromium.linux/master_site_config.py | # Copyright (c) 2012 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
... | # Copyright (c) 2012 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
... | Switch chromium.linux slaves to buildbot 0.8. | Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
3035521c5a8e04b8eeb6874d8769dd5859747d53 | devpi_builder/cli.py | devpi_builder/cli.py | # coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('require... | # coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project vers... | Use a logger instead of printing to stdout | Use a logger instead of printing to stdout
| Python | bsd-3-clause | tylerdave/devpi-builder |
f11e56076e10d2c7e1db529751c53c1c5dc2074f | cihai/_compat.py | cihai/_compat.py | # -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
... | # -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
... | Revert "Port with_metaclass from flask" | Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.
| Python | mit | cihai/cihai,cihai/cihai-python,cihai/cihai |
7ccc4567071edfa9bc35c38105061ef5a02c7875 | vagrant/fabfile/hadoop.py | vagrant/fabfile/hadoop.py | from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def form... | from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def form... | Add safeguard against namenode formatting | [vagrant] Add safeguard against namenode formatting | Python | mit | terrai/rastercube,terrai/rastercube,terrai/rastercube |
1d739dea9cbd91605319412637b32730a250014e | entropy/backends/base.py | entropy/backends/base.py | # Copyright (C) 2013 Yahoo! 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 applicable law or a... | # Copyright (C) 2013 Yahoo! 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 applicable law or a... | Add some abstract methods to backend | Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160
| Python | apache-2.0 | stackforge/entropy,stackforge/entropy,stackforge/entropy |
3136b2525ad0716c6b6f7fa60f78f5f6d776ee55 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | Remove vue from selectors and just use embedded html | Remove vue from selectors and just use embedded html | Python | mit | jackbrewer/SublimeLinter-contrib-stylint |
0c71164f6c9a2229b8e99eb2dd38981407d8dfe7 | measurement/migrations/0003_auto_20141013_1137.py | measurement/migrations/0003_auto_20141013_1137.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
... | Patch a migration to work with postgres | Patch a migration to work with postgres
| Python | mit | sigurdsa/angelika-api |
6e0d583e0c3eea7ca9e7a37567cfc7535d8f406b | django_prices_openexchangerates/tasks.py | django_prices_openexchangerates/tasks.py | from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + ... | from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + ... | Make rates parsing more readable | Make rates parsing more readable
| Python | bsd-3-clause | artursmet/django-prices-openexchangerates,mirumee/django-prices-openexchangerates |
60087afcf8f0130fb9cd6e154a9fb7290c0fde2e | tools/test.py | tools/test.py | #!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. 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 string
import subprocess
import sys
import utils
def Main():
a... | #!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. 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 string
import subprocess
import sys
import utils
def Main():
a... | Add third_party/android_tools/sdk/platform-tools to PATH if available | Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .
| Python | bsd-3-clause | dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-ar... |
6687d8bbfbda55110145d5398a07672e71735f7b | ecal_users.py | ecal_users.py | from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible result... | from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results.... | Use 8 characters for email address rather than 10. | Use 8 characters for email address rather than 10.
| Python | mit | eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot |
e466da4f26d8cbac45476e8c00e009e004cd4baa | fluent_blogs/templatetags/fluent_blogs_comments_tags.py | fluent_blogs/templatetags/fluent_blogs_comments_tags.py | """
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expo... | """
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from dj... | Support django-contrib-comments instead of django.contrib.comments for Django 1.8 | Support django-contrib-comments instead of django.contrib.comments for Django 1.8
| Python | apache-2.0 | edoburu/django-fluent-blogs,edoburu/django-fluent-blogs |
ecb1550f2cd02568e81b92ca360c0783df0e5bd7 | zbzapp/extras/ocr/vars.py | zbzapp/extras/ocr/vars.py | #!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
... | #!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
... | Support currently removed for gifs because of bugs | Support currently removed for gifs because of bugs
| Python | apache-2.0 | bhavyanshu/zBzQuiz,bhavyanshu/zBzQuiz,bhavyanshu/zBzQuiz |
ae3d8fd826647c8d853247b069726a26f4ae462d | exterminal.py | exterminal.py | import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
she... | import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
she... | Fix dangling default in kwargs 'shell_cmd' | Fix dangling default in kwargs 'shell_cmd'
| Python | mit | jemc/SublimeExterminal,jemc/SublimeExterminal |
beb9528c4a1a8cba1b432c285135b7d1d18453dc | heltour/tournament/templatetags/tournament_extras.py | heltour/tournament/templatetags/tournament_extras.py | from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args... | from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args... | Add comment to resultclass tag | Add comment to resultclass tag | Python | mit | cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour |
8748854969f8cab9f416a05b4565734b2632df77 | statscache_plugins/releng/plugins/cloud_images_upload_base.py | statscache_plugins/releng/plugins/cloud_images_upload_base.py | import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messa... | import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod... | Move fedmsg topics listened to by a plugin to a class variable. | Move fedmsg topics listened to by a plugin to a class variable.
| Python | lgpl-2.1 | yazman/statscache_plugins |
6b603840b8abd0b63e13c8ccbffa40e8abc453b5 | movies.py | movies.py | import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', h... | import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::',... | Read and print all data files. | Read and print all data files.
| Python | mit | m1key/data-science-sandbox |
f3c04e95bc40d5a85fe2f560df68315384ef763e | picoCTF-web/daemons/cache_stats.py | picoCTF-web/daemons/cache_stats.py | #!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registrati... | #!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app... | Update stats daemon to update ZSets and memoization as necessary | Update stats daemon to update ZSets and memoization as necessary
| Python | mit | royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF |
981b5f27bc819056a9bc888c29f21b4fd9a0bded | server/app.py | server/app.py | #!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.... | #!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(t... | Add command line args to App | Add command line args to App
| Python | mit | CaminsTECH/owncloud-test |
15519437a0197582c4b321b9e55544320a759c28 | src/lib/sd2/workspace.py | src/lib/sd2/workspace.py | #!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
... | #!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
... | Add containers in hosts so we can rsync into containers | Add containers in hosts so we can rsync into containers | Python | apache-2.0 | gae123/sd2,gae123/sd2 |
accca78e7d9dab841d4850f74795099d63854707 | masters/master.client.v8.ports/master_site_config.py | masters/master.client.v8.ports/master_site_config.py | # Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_s... | # Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_s... | Add buildbucket integration to v8.ports | V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
85220f2830d355245803965ee57886e5c1268833 | tests/unit/test_twitter.py | tests/unit/test_twitter.py | from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='h... | from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/109... | Update Twitter test to be more robust | Update Twitter test to be more robust
| Python | apache-2.0 | obsidianforensics/unfurl,obsidianforensics/unfurl |
2baab2e945af8c797d8b8804139fc56f366ea83d | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
ce703cbe3040770ee105fb0d953f85eebb92bdc9 | us_ignite/sections/templatetags/sections_tags.py | us_ignite/sections/templatetags/sections_tags.py | from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
... | from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
... | Make sure the ``context`` is not overriden. | Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
f952a963dee28759e9ed4846eec5966d401c71e7 | goodreads/scraper.py | goodreads/scraper.py | import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'cl... | import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'c... | Allow user to get popular or new quotes | Allow user to get popular or new quotes
| Python | mit | chankeypathak/goodreads-quotes |
238427e684e6cb6f8c8cc6c80c8d24a51e908e24 | bika/lims/upgrade/to3031.py | bika/lims/upgrade/to3031.py | from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal... | from Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('S... | Include catalog setup in 3031 upgrade | Include catalog setup in 3031 upgrade
| Python | agpl-3.0 | veroc/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS |
2e1516ee89fb0af69733bab259cbb38a3f8a614c | latexbuild/latex_parse.py | latexbuild/latex_parse.py | """Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\... | """Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one l... | Update latex parser to better-handle edge cases | Update latex parser to better-handle edge cases
| Python | mit | pappasam/latexbuild |
f4b92c2212ce2533860764fccdb5ff05df8b8059 | die_bag.py | die_bag.py | import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
... | import random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in ... | Remove test functions and, clean code in preperation for posting a pull request | Remove test functions and, clean code in preperation for posting a pull request
| Python | mit | Eanilsen/RPGHelper |
7c690e65fd1fe0a139eaca8df7799acf0f696ea5 | mqtt/tests/test_client.py | mqtt/tests/test_client.py | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... | Add more time to mqtt.test.client | Add more time to mqtt.test.client
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient |
3c60a46d9cb89dbf1e2e4a05766d91d837173089 | encryptit/tests/openpgp_message/test_packet_location.py | encryptit/tests/openpgp_message/test_packet_location.py | import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PA... | import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PA... | Test for incorrect serialisation of PacketLocation | Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.
| Python | agpl-3.0 | paulfurley/encryptit,paulfurley/encryptit |
f165cb38e57315fcbe4049128a436c4ef743ef4b | lib/bx/misc/bgzf_tests.py | lib/bx/misc/bgzf_tests.py | import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf() | import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 " | Make BGZF test a real unittest | Make BGZF test a real unittest
| Python | mit | bxlab/bx-python,bxlab/bx-python,bxlab/bx-python |
46fad55c9a707caeb28663d7560d93d5e4563b72 | keteparaha/__init__.py | keteparaha/__init__.py | # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certa... | # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certa... | Add more detail to module docstring | Add more detail to module docstring
| Python | mit | aychedee/keteparaha,tomdottom/keteparaha |
c705fcf1771466ac2445a8058334c27cd1040e81 | docs/examples/compute/azure_arm/instantiate.py | docs/examples/compute/azure_arm/instantiate.py | from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
| from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
| Fix lint in example script | Fix lint in example script
| Python | apache-2.0 | Scalr/libcloud,illfelder/libcloud,pquentin/libcloud,apache/libcloud,pquentin/libcloud,andrewsomething/libcloud,samuelchong/libcloud,vongazman/libcloud,illfelder/libcloud,erjohnso/libcloud,SecurityCompass/libcloud,watermelo/libcloud,ByteInternet/libcloud,illfelder/libcloud,apache/libcloud,vongazman/libcloud,erjohnso/lib... |
cfb9838349a076e8fa3afe9a69db74581b13d296 | labsys/auth/decorators.py | labsys/auth/decorators.py | from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) ... | from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):... | Remove test condition for permissions | :bug: Remove test condition for permissions
Otherwise I would not be able to test them properly
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys |
e120aafad13138abb5d98bbad12c0d8bdc532b30 | lglass/web/application.py | lglass/web/application.py | # coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abo... | # coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File ... | Replace static_file by open call | Replace static_file by open call
| Python | mit | fritz0705/lglass |
2b21871f3a06d296066b8409741212537b458fa3 | tests/offline/__init__.py | tests/offline/__init__.py | # coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.pa... | # coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename... | Use context manager for the offline tests | Use context manager for the offline tests
| Python | mit | alexandriagroup/fnapy,alexandriagroup/fnapy |
d64492c85182a992597729999f1e4483977b87d6 | cisco_olt_client/command.py | cisco_olt_client/command.py | import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:par... | import shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 m... | Add function for parsing cli arguments | Add function for parsing cli arguments
| Python | mit | Vnet-as/cisco-olt-client |
8d3e79d268ae16e9774c60332c47b11038407050 | vagrant/roles/db/molecule/default/tests/test_default.py | vagrant/roles/db/molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_runnin... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert ... | Add 'testinfra' test method 'test_mongo_host_port' | Add 'testinfra' test method 'test_mongo_host_port'
| Python | mit | DmitriySh/infra,DmitriySh/infra,DmitriySh/infra |
8c1f303d4cc04c95170dea268ab836a23d626064 | thezombies/management/commands/crawl_agency_datasets.py | thezombies/management/commands/crawl_agency_datasets.py | from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def hand... | from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
a... | Add message for when command is not supplied any arguments. | Add message for when command is not supplied any arguments.
| Python | bsd-3-clause | sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies |
22ef8a836a765b98fbc05bda5254ee9e5b6bf11b | udata/core/jobs/models.py | udata/core/jobs/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringF... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week... | Fix periodic tasks model display | Fix periodic tasks model display
| Python | agpl-3.0 | opendatateam/udata,davidbgk/udata,etalab/udata,opendatateam/udata,opendatateam/udata,etalab/udata,davidbgk/udata,etalab/udata,davidbgk/udata |
20699a38f8ab28fa605abbe110d0bfdb2b571662 | workers/exec/examples/dummy_worker.py | workers/exec/examples/dummy_worker.py | #!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT... | #!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT... | Add flush for dummy exec worker | Add flush for dummy exec worker
| Python | bsd-3-clause | timofey-barmin/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench |
2ec5f71d04ae17a1c0a457fba1b82f8c8e8891ab | sc2reader/listeners/utils.py | sc2reader/listeners/utils.py | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass | Add a default ListenerBase.setup implementation. | Add a default ListenerBase.setup implementation.
| Python | mit | StoicLoofah/sc2reader,vlaufer/sc2reader,vlaufer/sc2reader,GraylinKim/sc2reader,ggtracker/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,StoicLoofah/sc2reader |
90c2141ccdcb566149a0f11e8cc1e3f67b2dc113 | mnp/commands.py | mnp/commands.py | import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["-i", index_url] + additional_args)
def upload(repository, additional_args = None):
additional_args = [] ... | import subprocess
def download(packages, index_url, additional_args = None):
additional_args = [] if additional_args is None else additional_args
subprocess.check_call(["pip", "install"] + packages + ["--extra-index-url", index_url] + additional_args)
def upload(repository, additional_args = None):
additi... | Change to use --extra-index-url instead | Change to use --extra-index-url instead
| Python | mit | heryandi/mnp |
446d36cbbf79083b9d41ea5b152c5a845560eb4b | whats_fresh/whats_fresh_api/tests/views/test_stories.py | whats_fresh/whats_fresh_api/tests/views/test_stories.py | from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def s... | from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def s... | Add error field to expected JSON | Add error field to expected JSON
| Python | apache-2.0 | iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api |
ab57bcc9f4219af63e99d82a844986213ade4c01 | script/commit_message.py | script/commit_message.py | #!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc7... | #!/usr/bin/env python
import re
import sys
import subprocess
examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc7... | Fix script up to search branches | Fix script up to search branches
| Python | mit | pact-foundation/pact-python,pact-foundation/pact-python |
03aae3ef6488168730d35e36f416e1b8eb058431 | script/daytime_client.py | script/daytime_client.py | # A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | Use python script to send json | Use python script to send json
| Python | bsd-3-clause | crapp/netfortune,crapp/netfortune |
a63481c0198791b41cf377e4bc8247afaed90364 | email_extras/__init__.py | email_extras/__init__.py |
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
|
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
... | Fix to allow version number to be imported without dependencies being installed. | Fix to allow version number to be imported without dependencies being installed.
| Python | bsd-2-clause | blag/django-email-extras,stephenmcd/django-email-extras,blag/django-email-extras,dreipol/django-email-extras,dreipol/django-email-extras,stephenmcd/django-email-extras |
ca9f3c005b2412c1b9ff0247afc6708b0172d183 | web/impact/impact/v1/views/base_history_view.py | web/impact/impact/v1/views/base_history_view.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
me... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
me... | Improve history sorting and remove dead comments | [AC-4875] Improve history sorting and remove dead comments
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api |
112ce320f351399a28e4d85ed88e1b71df4e7aef | magpie/config/__init__.py | magpie/config/__init__.py | from os import path
class ConfigPath(object):
def __getattr__(self, key):
return_path = path.join(path.dirname(__file__), key + '.cfg')
if not path.exists(return_path): return None
return return_path
config_path = ConfigPath()
| from os import path
class ConfigPath(object):
def __init__(self):
self.config_paths = [path.join(path.expanduser('~'), '.magpie'), path.dirname(__file__)]
def __getattr__(self, key):
for path in self.config_paths:
return_path = path.join(path, key + '.cfg')
if path.exist... | Enable configuration from home directory | Enable configuration from home directory
This adds the possibility of defining multiple locations for the config-files. The given example first searches in ~/.magpie and if it doesn't find any config-files there, it searches in the default path. This enables configuration for each individual user and fixes the problem... | Python | mit | damoeb/magpie,akarca/magpie,charlesthomas/magpie,jcda/magpie,akarca/magpie,damoeb/magpie,damoeb/magpie,beni55/magpie,jcda/magpie,beni55/magpie,jcda/magpie,beni55/magpie,charlesthomas/magpie,akarca/magpie,charlesthomas/magpie |
6f992bda1747d8dd23dd03f1ae3679c00f2fc977 | marketpulse/geo/lookup.py | marketpulse/geo/lookup.py | from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
... | from urlparse import urljoin
from django.conf import settings
from django_countries import countries
import requests
COUNTRY_CODES = {key: value for (value, key) in list(countries)}
def reverse_geocode(lat, lng):
"""Query Mapbox API to get data for lat, lng"""
query = '{0},{1}.json'.format(lng, lat)
... | Handle errors in case of a country mismatch. | Handle errors in case of a country mismatch.
| Python | mpl-2.0 | mozilla/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,mozilla/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse |
ef7910d259f3a7d025e95ad69345da457a777b90 | myvoice/urls.py | myvoice/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broa... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('bro... | Use Django 1.7 syntax for URLs | Use Django 1.7 syntax for URLs
| Python | bsd-2-clause | myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice |
e252962f9a6cc1ed6cd2ccdd72c4151708be7233 | tests/cases/resources/tests/preview.py | tests/cases/resources/tests/preview.py | import json
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'app... | import json
from django.contrib.auth.models import User
from django.test import TestCase
class PreviewResourceTestCase(TestCase):
def test_get(self):
response = self.client.get('/api/data/preview/',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
sel... | Add test to recreate error in this bug | Add test to recreate error in this bug
| Python | bsd-2-clause | rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano,chop-dbhi/serrano |
64732e7dd32f23b9431bd69fecd757af1772053e | local_test_settings.py | local_test_settings.py | from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.con... | from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.con... | Remove UNICORE_DISTRIBUTE_API from test settings | Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo |
c460fd7d257b25723fc19557ad4404519904e0a9 | simplecoin/tests/__init__.py | simplecoin/tests/__init__.py | import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra ... | import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
... | Fix tests to allow use of random, but not change each time | Fix tests to allow use of random, but not change each time
| Python | mit | nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi |
66eadda6a2a26cfef2f38449736183b8b5175022 | pytest_django/__init__.py | pytest_django/__init__.py | from .plugin import *
from .funcargs import *
from .marks import *
| from pytest_django.plugin import *
from pytest_django.funcargs import *
from pytest_django.marks import *
# When Python 2.5 support is dropped, these imports can be used instead:
# from .plugin import *
# from .funcargs import *
# from .marks import *
| Make module imports 2.5 compatible | Make module imports 2.5 compatible
| Python | bsd-3-clause | bforchhammer/pytest-django,thedrow/pytest-django,reincubate/pytest-django,aptivate/pytest-django,felixonmars/pytest-django,pelme/pytest-django,ojake/pytest-django,hoh/pytest-django,RonnyPfannschmidt/pytest_django,ktosiek/pytest-django,davidszotten/pytest-django,pombredanne/pytest_django,tomviner/pytest-django |
d4f63bb099db886f50b6e54838ec9200dbc3ca1f | echo_client.py | echo_client.py | #!/usr/bin/env python
import socket
import sys
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message... | #!/usr/bin/env python
import socket
import sys
import echo_server
from threading import Thread
def main():
message = sys.argv[1]
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((a... | Add threading to allow for client and server to be run from a single script | Add threading to allow for client and server to be run from a single script
| Python | mit | charlieRode/network_tools |
fddd632e73a7540bc6be4f02022dcc663b35b3d4 | echo_server.py | echo_server.py | import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
address = ('127.0.0.1', 50000)
server_socket.bind(address)
server_socket.listen(1)
connection, client_address = server... | import socket
try:
while True:
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
connection, client_address = server_socket.accept()
# ... | Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt | Fix bug in server, connection closes after returning message, socket closes on KeyboardInterupt
| Python | mit | jwarren116/network-tools,jwarren116/network-tools |
0611f0ca617c3463a69e5bd627e821ae55c822ec | logintokens/tests/util.py | logintokens/tests/util.py | from time import time
class MockTime:
time_passed = 0.0
def time(self):
return time() + self.time_passed
def sleep(self, seconds):
self.time_passed += seconds
mock_time = MockTime()
| """utility functions for testing logintokens app
"""
from time import time
class MockTime:
"""Provide mocked time and sleep methods to simulate the passage of time.
"""
time_passed = 0.0
def time(self):
"""Return current time with a consistent offset.
"""
return time() + se... | Add docstrings to mocked time methods | Add docstrings to mocked time methods
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
07617ec8b1cb57c795d9875691d7f3c67e633b6a | repour/auth/oauth2_jwt.py | repour/auth/oauth2_jwt.py | import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token: ' + str(token))
OPTIONS = {
'verify_signature': True,... | import asyncio
import logging
from jose import jwt, JWTError
from repour.config import config
logger = logging.getLogger(__name__)
@asyncio.coroutine
def verify_token(token):
c = yield from config.get_configuration()
logger.info('Got token!')
OPTIONS = {
'verify_signature': True,
'veri... | Remove user token from logs | [NCL-3741] Remove user token from logs
| Python | apache-2.0 | project-ncl/repour,project-ncl/repour |
9f557a7632a1cd3b16dd6db79c7bb6a61ff79791 | v0/tig.py | v0/tig.py | #!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
... | #!/usr/bin/env python
"""
Usage:
tig init
tig commit <msg>
tig checkout <start-point> [-b <branch-name>]
tig diff
tig log
tig branch
tig merge <branch>
Options:
-b <branch-name> Branch name to checkout.
"""
import docopt
def init():
pass
def branch():
pass
def commit(msg):
pass
... | Print parsed args, useful for demo. | Print parsed args, useful for demo.
| Python | mit | bravegnu/tiny-git,jamesmortensen/tiny-git,jamesmortensen/tiny-git,bravegnu/tiny-git |
fd09e0ef4ea9a0dede74e5a87ad108a75d5e5ce7 | comrade/core/decorators.py | comrade/core/decorators.py | from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
inst... | from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
... | Add decorator for loading instance of a model in a view. | Add decorator for loading instance of a model in a view.
| Python | mit | bueda/django-comrade |
5a2c794bebc4b6594eacdaef4409825c135b62d7 | test/test_integ_rules.py | test/test_integ_rules.py | """ Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_existsCaptureP_capture... | """ Integration tests for the rules module """
import unittest
# pylint: disable=import-error
from res import types
from src import coordinate
from src import gamenode
from src import rules
class TestIntegRules(unittest.TestCase):
""" Integration tests for the rules module """
def test_isACaptureP_direction_... | Add integration test for isACaptureP() | Add integration test for isACaptureP()
| Python | mit | blairck/jaeger |
cc0a971bad5f4b2eb81881b8c570eddb2bd144f3 | django_vend/stores/forms.py | django_vend/stores/forms.py | from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
... | from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
... | Make form update existing instance if uid matches | Make form update existing instance if uid matches
| Python | bsd-3-clause | remarkablerocket/django-vend,remarkablerocket/django-vend |
5d5a4e6fb6a646ddf189100d87160d36f09862bf | games/admin.py | games/admin.py | from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
pass
class AssetAdmin(admin.Mode... | from django.contrib import admin
from .models import Game, Framework, Release, Asset
class GameAdmin(admin.ModelAdmin):
list_display = ['name', 'uuid', 'owner', 'framework', 'public']
class FrameworkAdmin(admin.ModelAdmin):
pass
class ReleaseAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'ga... | Add more fields to the release display | Add more fields to the release display
| Python | mit | stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb |
89ae5637fe57afbd777f0a491a6ab0d674a5e351 | agsadmin/sharing_admin/content/users/UserItem.py | agsadmin/sharing_admin/content/users/UserItem.py | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_re... | from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
super, zip)
from ...._endpoint_base import EndpointBase
from ...._utils import send_session_re... | Add move operation to user item | Add move operation to user item
| Python | bsd-3-clause | DavidWhittingham/agsadmin |
afbe8ddff1791084aa1bcad775f1b01481b72c2b | larvae/person.py | larvae/person.py | from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras... | from larvae.base import LarvaeBase
class Person(LarvaeBase):
"""
Details for a Person in Popolo format.
"""
_schema_name = "person"
__slots__ = ('name', '_id', 'gender', 'birth_date',
'death_date', 'image', 'summary', 'biography', 'links',
'other_names', 'extras... | Move default value assignments before kwargs | Move default value assignments before kwargs
| Python | bsd-3-clause | AGarrow/larvae |
2d4382ae1cec44875e7bec2f16b8406879a0bac9 | opentreemap/api/models.py | opentreemap/api/models.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharFie... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import uuid
import base64
import os
from django.contrib.gis.db import models
from treemap.models import User
class APIAccessCredential(models.Model):
access_key = models.CharFie... | Print debug-friendly repr of APIAccessCredential | Print debug-friendly repr of APIAccessCredential
| Python | agpl-3.0 | maurizi/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,RickMohr/otm-core,... |
25a37ea86e26a731608e4c2a810610c842d37d19 | grano/service/indexer.py | grano/service/indexer.py | import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Ent... | import logging
from pprint import pprint
import elasticsearch
from grano.core import es, es_index
from grano.model import Entity
from grano.logic import entities
log = logging.getLogger(__name__)
def index_entities():
""" Re-build an index for all enitites from scratch. """
for i, entity in enumerate(Ent... | Remove use of yield_per which clashes with 'joined' load. | Remove use of yield_per which clashes with 'joined' load. | Python | mit | 4bic/grano,granoproject/grano,4bic-attic/grano,CodeForAfrica/grano |
62d93afd3f59f4096ef22a056881faf725d09531 | oweb/tests/__init__.py | oweb/tests/__init__.py | # Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
| # Django imports
from django.test import TestCase
class OWebViewTests(TestCase):
"""Provides view related tests"""
fixtures = ['oweb_testdata_01.json']
def setup(self):
"""Prepare general testing settings"""
# urls must be specified this way, because the class-attribute can not
# ... | Add test specific url configuration | Add test specific url configuration
| Python | mit | Mischback/django-oweb,Mischback/django-oweb |
7f23dfe16904fdf73b353338a8881928c5211989 | hoomd/filter/__init__.py | hoomd/filter/__init__.py | """Particle filters."""
from hoomd.filter.filter_ import ParticleFilter # noqa
from hoomd.filter.all_ import All # noqa
from hoomd.filter.set_ import Intersection, SetDifference, Union # noqa
from hoomd.filter.tags import Tags # noqa
from hoomd.filter.type_ import Type # noqa
| """Particle filters.
Particle filters describe criteria to select subsets of the particle in the
system for use by various operations throughout HOOMD. To maintain high
performance, filters are **not** re-evaluated on every use. Instead, each unique
particular filter (defined by the class name and hash) is mapped to a... | Add particle filter overview information. | Add particle filter overview information.
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue |
bb5b84cd71ff95bd2539afce75491139fbc6f066 | pi_control_client/gpio.py | pi_control_client/gpio.py | from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url, device_key):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service',
device_key=device_key)
def on(self, pin_number):
return self._call({'pin'... | from rpc import RPCClient
class GPIOClient(RPCClient):
def __init__(self, rabbit_url):
super(GPIOClient, self).__init__(
rabbit_url=rabbit_url,
queue_name='gpio_service')
def on(self, device_key, pin_number):
return self._call(device_key, {'pin': pin_number, 'action':... | Add device_key on every call in GPIO client | Add device_key on every call in GPIO client
| Python | mit | HydAu/Projectweekends_Pi-Control-Client,projectweekend/Pi-Control-Client |
266027514c740c30c0efae5fcd1e2932f1be9933 | perfrunner/tests/ycsb2.py | perfrunner/tests/ycsb2.py | from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clon... | from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clon... | Check the number of items a little bit later | Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
| Python | apache-2.0 | couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner |
0445c8a8e82d3ed5c05537b43616a3b94dcf786f | wye/workshops/templatetags/workshop_action_button.py | wye/workshops/templatetags/workshop_action_button.py | from django import template
from datetime import datetime
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
WorkshopSt... | from datetime import datetime
from django import template
from wye.base.constants import WorkshopStatus
register = template.Library()
def show_draft_button(workshop, user):
if (workshop.status in [WorkshopStatus.REQUESTED,
WorkshopStatus.ACCEPTED,
Workshop... | Add filter to show button only if selected role tutor | Add filter to show button only if selected role tutor
| Python | mit | shankisg/wye,pythonindia/wye,harisibrahimkv/wye,DESHRAJ/wye,harisibrahimkv/wye,harisibrahimkv/wye,shankisg/wye,DESHRAJ/wye,pythonindia/wye,shankisg/wye,DESHRAJ/wye,shankig/wye,pythonindia/wye,DESHRAJ/wye,pythonindia/wye,harisibrahimkv/wye,shankig/wye,shankisg/wye,shankig/wye,shankig/wye |
65cd9eff50a95d53b75d9bd6a02e56e7a6b6262e | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocke... | Migrate from Folly Format to fmt | Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
| Python | apache-2.0 | facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly |
3c1e52ccd329c255649b0ca4e3727f60996f8e34 | src/apps/console/views.py | src/apps/console/views.py | from django.shortcuts import render_to_response
from account.auth import *
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@dh_login_required
def index(request):
return render_to_response("console.html", {
'login': get_login(request)}) | from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
'''
@author: Anant Bhardwaj
@date: Mar 21, 2013
Datahub Console
'''
@login_required
def index(request):
return render_to_response("console.html", {
'login': request.user.username})
| Make the console app work with the new user model. | Make the console app work with the new user model.
| Python | mit | anantb/datahub,anantb/datahub,anantb/datahub,datahuborg/datahub,anantb/datahub,anantb/datahub,anantb/datahub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datah... |
8b9454fdf9e54059edcc951f188c05cb0f34c0a4 | lookup_isbn.py | lookup_isbn.py | #!/usr/bin/env python
import yaml
from amazon.api import AmazonAPI
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_key_id'],
self.config['aws_secret_key'],
self.config['amazon_associate_tag']
... | #!/usr/bin/env python
import yaml
import sys
import os
from amazon.api import AmazonAPI
# Change to script directory
os.chdir(os.path.dirname(sys.argv[0]))
class Books:
def __init__(self, config_file):
self.config = yaml.load(open(config_file, 'r'))
self.amazon = AmazonAPI(
self.config['aws_access_ke... | Read commandline args as isbns | Read commandline args as isbns
| Python | mit | sortelli/book_pivot,sortelli/book_pivot |
326c249e41e431112ae213c20bf948a7ae351a31 | visualisation_display.py | visualisation_display.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vec... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n,... | Add vmin, vmax and possible labels to display of images | Add vmin, vmax and possible labels to display of images
| Python | mit | ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer |
bb0b72333b715956740373c3ba80a8193b99a8cc | app/services/updater_service.py | app/services/updater_service.py | from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self.... | from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self.... | Add message before running ansible. | Add message before running ansible.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer |
d30355ace2c84cad198fd4bfcc3d6a211275fb76 | src/ggrc_basic_permissions/roles/AuditorReader.py | src/ggrc_basic_permissions/roles/AuditorReader.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
requir... | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "System Implied"
description = """
A user with Auditor role for a program audit will also have this role in the
default object context so that the auditor will have access to the objects
requir... | Add support for reading snapshots for auditor reader | Add support for reading snapshots for auditor reader
| Python | apache-2.0 | AleksNeStu/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core |
114eae527cce97423ec5cc5896a4728dc0764d2c | chunsabot/modules/images.py | chunsabot/modules/images.py | import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=stri... | import os
import json
import shutil
import subprocess
import string
import random
from chunsabot.database import Database
from chunsabot.botlogic import brain
RNN_PATH = Database.load_config('rnn_library_path')
MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7")
def id_generator(size=12, chars=stri... | Fix some confusion of creating folders | Fix some confusion of creating folders
| Python | mit | susemeee/Chunsabot-framework |
1f4349e20a98e622124c1e5bc121053e4775152f | login/signals.py | login/signals.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, ... | from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from django.contrib.auth.models import User, Group
from login.permissions import cache_clear
from .models import UserProfile, GroupProfile
# Add signal to automatically extend user profile
@receiver(post_save, sender=Us... | Add signal to invalidate cache when groups change. | Add signal to invalidate cache when groups change.
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient |
48455d0d1b8632d6b512e257d6dd914defd7ae84 | px/px_process_test.py | px/px_process_test.py | import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
test_me = px_process.Px... | import getpass
import os
import px_process
def test_create_process():
process_builder = px_process.PxProcessBuilder()
process_builder.pid = 7
process_builder.username = "usernamex"
process_builder.cpu_time = 1.3
process_builder.memory_percent = 42.7
process_builder.cmdline = "hej kontinent"
... | Add (failing) test for getting all processes | Add (failing) test for getting all processes
| Python | mit | walles/px,walles/px |
7352a257a08ad4d41261dd0c1076cde966d2a5c2 | sharer/multi.py | sharer/multi.py | from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def ... | from .base import AbstractSharer
class MultiSharer(AbstractSharer):
def __init__(self, **kw):
super(MultiSharer, self).__init__()
self.sharers = {}
self.add_sharers(**kw)
def add_sharers(self, **kw):
for key, val in kw.iteritems():
self.sharers[key] = val
def ... | Add _services keyword argument to MultiSharer's send. | Add _services keyword argument to MultiSharer's send.
| Python | mit | FelixLoether/python-sharer |
7209e44f913d2f28f94bb4d67ba875ff635261d2 | myhdl/_compat.py | myhdl/_compat.py | import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def... | from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_typ... | Revert "Remove the __future__ flags" | Revert "Remove the __future__ flags"
This reverts commit 24b3332ca0c0005483d5f310604cca984efd1ce9.
| Python | lgpl-2.1 | jmgc/myhdl-numeric,jmgc/myhdl-numeric,jmgc/myhdl-numeric |
c769b66c546ad3fd9d04c0607506a49e9d3bff4a | fortdepend/preprocessor.py | fortdepend/preprocessor.py | import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super().__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
re... | import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f... | Fix super() call for py2.7 | Fix super() call for py2.7
| Python | mit | ZedThree/fort_depend.py,ZedThree/fort_depend.py |
83c52f6a294b69e48d455f9037be088420d4cfa8 | selectable/__init__.py | selectable/__init__.py | """
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version_info__ = {
'major': 0,
'minor': 5,
'micro': 2,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
... | """
django-selectable is a collection of tools and widgets for using/creating auto-complete selection widgets using Django and jQuery UI.
"""
__version__ = '0.6.0dev'
| Simplify version string and update to reflect current status. | Simplify version string and update to reflect current status.
| Python | bsd-2-clause | mlavin/django-selectable,affan2/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable |
394e3ffd4221a749bcc8df7d11da2f3bc3ace5f9 | getalltext.py | getalltext.py | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... | #!/usr/bin/env python3
"""
A program to extract raw text from Telegram chat log
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract all raw text from a specific Telegram chat")
parser.add_argument('filepath', help='the json chatlog file to ... | Add option to remove newlines; remove bug on messages sent by someone without a username | Add option to remove newlines; remove bug on messages sent by someone without a username
| Python | mit | expectocode/telegram-analysis,expectocode/telegramAnalysis |
eea1ba0273b8e5362f6b27854e29e6053555fb2a | gittip/cli.py | gittip/cli.py | """This is installed as `payday`.
"""
from gittip import wireup
def payday():
db = wireup.db()
wireup.billing()
wireup.nanswers()
# Lazily import the billing module.
# =================================
# This dodges a problem where db in billing is None if we import it from
# gittip befo... | """This is installed as `payday`.
"""
import os
from gittip import wireup
def payday():
# Wire things up.
# ===============
# Manually override max db connections so that we only have one connection.
# Our db access is serialized right now anyway, and with only one
# connection it's easier to tru... | Configure payday for no db timeout | Configure payday for no db timeout
| Python | mit | mccolgst/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/... |
191e62a2547c4d3d013cb4c68fed60f1619fe82c | pyheufybot/modules/say.py | pyheufybot/modules/say.py | from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say"
self.moduleType = ModuleType.COMMAND
self.modulePriotity = ModulePriority.NORMAL
sel... | from pyheufybot.module_interface import Module, ModulePriority, ModuleType
class ModuleSpawner(Module):
def __init__(self, bot):
self.bot = bot
self.name = "Say"
self.trigger = "say|sayremote"
self.moduleType = ModuleType.COMMAND
self.modulePriority = ModulePriority.NORMAL
... | Add a remote option to Say | Add a remote option to Say
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
f80cbe4b962fc9dd6341e9a59848238f5d7dee5e | src/sas/qtgui/MainWindow/UnitTesting/WelcomePanelTest.py | src/sas/qtgui/MainWindow/UnitTesting/WelcomePanelTest.py | import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePane... | import sys
import pytest
from PyQt5 import QtGui, QtWidgets
# Local
from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel
class WelcomePanelTest:
'''Test the WelcomePanel'''
@pytest.fixture(autouse=True)
def widget(self, qapp):
'''Create/Destroy the WelcomePanel'''
w = WelcomePane... | Fix test for change in panel text | Fix test for change in panel text
| Python | bsd-3-clause | SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview |
78032531e9fe1ab99f6c0e021250754fe5375ab9 | src/zeit/content/article/edit/browser/tests/test_sync.py | src/zeit/content/article/edit/browser/tests/test_sync.py | import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
... | import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def s... | Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded. | Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article |
ee1aea5ab2002f14fbf0191e3e1a94988fcb7e08 | guetzli_img_compression.py | guetzli_img_compression.py | # -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
filename = os.path.split(img_file)[1]
url_out = os.path.join(source, '-'+filename)
subprocess.call(['guetzli', '--quality', '84', '--verbose', img_file, url_out])
#####... | # -*- coding:utf-8 -*-
import os
import subprocess
import sys
source = sys.argv[1]
TYPES = ('.jpeg', '.png', '.jpg')
def convert_a_img(img_file):
file = os.path.split(img_file)[1]
filename = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
url_out = os.path.join(source, filename + '_mini' + suffi... | Update the output file name | Update the output file name
| Python | mit | JonyFang/guetzli-img-compression |
8c88da640f2fab19254e96a144461f2c65aff720 | wagtailstartproject/project_template/tests/middleware.py | wagtailstartproject/project_template/tests/middleware.py | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | Reset Content-Length after changing the length of the response | Reset Content-Length after changing the length of the response
| Python | mit | leukeleu/wagtail-startproject,leukeleu/wagtail-startproject |
a10c7ed55151533a647332c6b910b3724d5b3af1 | il2fb/ds/airbridge/json.py | il2fb/ds/airbridge/json.py | # -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_primitive'):
cls = obj.__class__
result = obj.to... | # -*- coding: utf-8 -*-
import json as _json
from functools import partial
from il2fb.commons.events import Event
from il2fb.ds.airbridge.structures import TimestampedData
__all__ = ('dumps', 'loads', )
class JSONEncoder(_json.JSONEncoder):
def default(self, obj):
cls = type(obj)
if issubc... | Update custom JSONEncoder to treat TimestampedData as dict | Update custom JSONEncoder to treat TimestampedData as dict
| Python | mit | IL2HorusTeam/il2fb-ds-airbridge |
2b1dadb57cce89f12e825dc24a2136fe27a8d0db | cattr/function_dispatch.py | cattr/function_dispatch.py | import attr
@attr.s(slots=True)
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be i... | from ._compat import lru_cache
class FunctionDispatch(object):
"""
FunctionDispatch is similar to functools.singledispatch, but
instead dispatches based on functions that take the type of the
first argument in the method, and return True or False.
objects that help determine dispatch should be in... | Use lru_cache instead of a dict cache in FunctionDispatch | Use lru_cache instead of a dict cache in FunctionDispatch
This has no affect on the microbenchmark, but seems appropriate for
consistency with the previous commit.
| Python | mit | python-attrs/cattrs,Tinche/cattrs |
99360f7b128c2691763c283406f3758db69d8bca | serrano/formatters.py | serrano/formatters.py | from django.template import defaultfilters as filters
from avocado.formatters import Formatter, registry
class HTMLFormatter(Formatter):
def to_html(self, values, fields=None, **context):
toks = []
for value in values.values():
if value is None:
continue
if ... | from django.template import defaultfilters as filters
from avocado.formatters import Formatter
class HTMLFormatter(Formatter):
delimiter = u' '
html_map = {
None: '<em>n/a</em>'
}
def to_html(self, values, **context):
toks = []
for value in values.values():
# Chec... | Add `delimiter` and `html_map` to HTML formatter and do not register it by default | Add `delimiter` and `html_map` to HTML formatter and do not register it by default | Python | bsd-2-clause | rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano |
561060423d0979e51b92a7209482e76680734d51 | dallinger/dev_server/app.py | dallinger/dev_server/app.py | import codecs
import os
import gevent.monkey
from dallinger.experiment_server.experiment_server import app
gevent.monkey.patch_all()
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex").decode("ascii")
| import codecs
import os
import gevent.monkey
gevent.monkey.patch_all() # Patch before importing app and all its dependencies
from dallinger.experiment_server.experiment_server import app # noqa: E402
app.config["EXPLAIN_TEMPLATE_LOADING"] = True
os.environ["FLASK_SECRET_KEY"] = codecs.encode(os.urandom(16), "hex"... | Apply gevent patch earlier based on output of `flask run` | Apply gevent patch earlier based on output of `flask run`
| Python | mit | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger |
4dca51fe6cd976c0312156ab32f787cecbb765a2 | task_router/tests/test_views.py | task_router/tests/test_views.py | from django.test import TestCase, Client
class HomePageTest(TestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is a class-based view, so we can mostly rely on Django's own
# tests... | from xmlunittest import XmlTestCase
from django.test import TestCase, Client
from unittest import skip
class HomePageTest(TestCase, XmlTestCase):
def setUp(self):
self.client = Client()
def test_home_page(self):
# Act
response = self.client.get('/')
# Assert
# This is... | Add test for test incoming call | Add test for test incoming call
| Python | mit | TwilioDevEd/task-router-django,TwilioDevEd/task-router-django,TwilioDevEd/task-router-django |
67b681697ebd3c1ea1ebda335c098e628da60b58 | cinder/tests/test_test_utils.py | cinder/tests/test_test_utils.py | #
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #
# Copyright 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Verify the full interface of the context object | Verify the full interface of the context object
Improved testcase for get_test_admin_context method
Change-Id: I8c99401150ed41cbf66b32cd00c7f8353ec4e267
| Python | apache-2.0 | Nexenta/cinder,nikesh-mahalka/cinder,eharney/cinder,NetApp/cinder,abusse/cinder,CloudServer/cinder,saeki-masaki/cinder,phenoxim/cinder,Accelerite/cinder,dims/cinder,takeshineshiro/cinder,NetApp/cinder,manojhirway/ExistingImagesOnNFS,Akrog/cinder,Hybrid-Cloud/cinder,scottdangelo/RemoveVolumeMangerLocks,mahak/cinder,mano... |
05acf13b46a3515d5a1362515984b42115b01ca3 | clone_everything/github.py | clone_everything/github.py | import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
... | import re
import requests
URL_REGEX = re.compile(r'https?://(?:www.)?github.com/(?P<account>[^\s]+)')
def matches_url(url):
"""Check with a URL matches a GitHub account URL."""
return bool(URL_REGEX.match(url))
def get_repos(url):
"""Get a list of repo clone URLs."""
match = URL_REGEX.match(url)
... | Add user agent to GitHub cloning | Add user agent to GitHub cloning
| Python | mit | tomleese/clone-everything,thomasleese/clone-everything |
65731fff94cd18a0d196c463b5e2aee444027d77 | salt/utils/pycrypto.py | salt/utils/pycrypto.py |
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
def secure_password(length=20):
'''
Generate a secure... |
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
try:
import Crypto.Random # pylint: disable=E0611
HAS_RANDOM = True
except ImportError:
HAS_RANDOM = False
import crypt
import re
import salt.exceptions
def secure_password(length=20):
''... | Add algorithm argument to get_hash | Add algorithm argument to get_hash
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.