commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
ec7791663ed866d240edbaf5e0dd766e9418e1ff | cla_backend/apps/status/tests/smoketests.py | cla_backend/apps/status/tests/smoketests.py | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
cursor = connection.cursor()
cursor.execute('SELECT 1')
row = cursor.fetchone(... | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | Add docstrings so that hubot can say what went wrong | Add docstrings so that hubot can say what went wrong
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | Add docstrings so that hubot can say what went wrong
import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
cursor = connection.cursor()
cur... |
75131bdf806c56970f3160de3e6d476d9ecbc3a7 | python/deleteNodeInALinkedList.py | python/deleteNodeInALinkedList.py | # https://leetcode.com/problems/delete-node-in-a-linked-list/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: v... | Add problem delete note in a linked list | Add problem delete note in a linked list
| Python | mit | guozengxin/myleetcode,guozengxin/myleetcode | # https://leetcode.com/problems/delete-node-in-a-linked-list/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: v... | Add problem delete note in a linked list
| |
48857638694ceca08c64d7b9c6825e2178c53279 | pylearn2/utils/doc.py | pylearn2/utils/doc.py | """
Documentation-related helper classes/functions
"""
class soft_wraps:
"""
A Python decorator which concatenates two functions' docstrings: one
function is defined at initialization and the other one is defined when
soft_wraps is called.
This helps reduce the ammount of documentation to write: ... | Add function decorator to improve functools.wraps | Add function decorator to improve functools.wraps
| Python | bsd-3-clause | goodfeli/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,fulmicoton/pylearn2,pkainz/pylearn2,Refefer/pylearn2,woozzu/pylearn2,kastnerkyle/pylearn2,CIFASIS/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,aalmah/pylearn2,bartvm/pylearn2,JesseLivezey/pylearn2,nouiz/pylearn2,lamblin/pylearn2,CIFASIS/pylearn2,junbo... | """
Documentation-related helper classes/functions
"""
class soft_wraps:
"""
A Python decorator which concatenates two functions' docstrings: one
function is defined at initialization and the other one is defined when
soft_wraps is called.
This helps reduce the ammount of documentation to write: ... | Add function decorator to improve functools.wraps
| |
403f23ae486c14066e0a93c7deca91c5fbc15b87 | plugins/brian.py | plugins/brian.py | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
attribution = [
"salad master",
"esquire",
"the one and only",
"startup enthusiast",
"boba king",
"not-dictator",
"normal citizen",
"ping-pong expert"
]
with ... | Use bigrams in Markov chain generator | Use bigrams in Markov chain generator
| Python | mit | kvchen/keffbot,kvchen/keffbot-py | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
attribution = [
"salad master",
"esquire",
"the one and only",
"startup enthusiast",
"boba king",
"not-dictator",
"normal citizen",
"ping-pong expert"
]
with ... | Use bigrams in Markov chain generator
"""Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
... |
c395da80c02b6c39514fcc46a7b951c71ae2c12b | usingnamespace/api/views/v1/root.py | usingnamespace/api/views/v1/root.py | from pyramid.view import view_config
from ....views.finalisecontext import FinaliseContext
class APIV1(FinaliseContext):
@view_config(context='...traversal.v1.Root', route_name='api', renderer='json')
def main(self):
sites = []
for site in self.context.sites:
sites.append(
... | Add view for API v1 Root | Add view for API v1 Root
This sends back a JSON response contain sites with ID's as well as
title/tagline.
| Python | isc | usingnamespace/usingnamespace | from pyramid.view import view_config
from ....views.finalisecontext import FinaliseContext
class APIV1(FinaliseContext):
@view_config(context='...traversal.v1.Root', route_name='api', renderer='json')
def main(self):
sites = []
for site in self.context.sites:
sites.append(
... | Add view for API v1 Root
This sends back a JSON response contain sites with ID's as well as
title/tagline.
| |
4ed64168541993e2ea85e7ea47139550d1daa206 | backdrop/write/config/development_environment_sample.py | backdrop/write/config/development_environment_sample.py | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | Add buckets for collecting pingdom data | Add buckets for collecting pingdom data
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | Add buckets for collecting pingdom data
# Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'lic... |
9f64d5e2f9447233df8d3b841c519196c3213e05 | pyflation/analysis/tests/test_deltaprel.py | pyflation/analysis/tests/test_deltaprel.py | ''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import nose
class TestSoundSpeeds... | ''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import nose
class TestSoundSpeeds... | Add test for scalar values. | Add test for scalar values.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation | ''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import nose
class TestSoundSpeeds... | Add test for scalar values.
''' test_deltaprel - Test functions for deltaprel module
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
import numpy as np
from numpy.testing import assert_, assert_raises
from pyflation.analysis import deltaprel
import n... |
55c183ad234ec53e2c7ba82e9e19793564373200 | comics/comics/dieselsweetiesweb.py | comics/comics/dieselsweetiesweb.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Stevens'
class Crawler(CrawlerBase):
his... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Stevens'
class Crawler(CrawlerBase):
his... | Check if field exists, not if it's empty | Check if field exists, not if it's empty
| Python | agpl-3.0 | jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Stevens'
class Crawler(CrawlerBase):
his... | Check if field exists, not if it's empty
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'Diesel Sweeties (web)'
language = 'en'
url = 'http://www.dieselsweeties.com/'
start_date = '2000-01-01'
rights = 'Richard Ste... |
65d5f4f3947b115421f273b7edb22420035c3ca3 | obfsproxy/common/modexp.py | obfsproxy/common/modexp.py | import gmpy
def powMod( x, y, mod ):
"""
Efficiently calculate and return `x' to the power of `y' mod `mod'.
Before the modular exponentiation, the three numbers are converted to
GMPY's bignum representation which speeds up exponentiation.
"""
x = gmpy.mpz(x)
y = gmpy.mpz(y)
mod = gmp... | Add function for fast modular exponentiation. | Add function for fast modular exponentiation.
The function uses GMPY's bignum arithmetic which speeds up the calculation.
| Python | bsd-3-clause | qdzheng/obfsproxy,infinity0/obfsproxy,catinred2/obfsproxy,NullHypothesis/obfsproxy,isislovecruft/obfsproxy,Yawning/obfsproxy,masterkorp/obfsproxy,Yawning/obfsproxy-wfpadtools,sunsong/obfsproxy,david415/obfsproxy | import gmpy
def powMod( x, y, mod ):
"""
Efficiently calculate and return `x' to the power of `y' mod `mod'.
Before the modular exponentiation, the three numbers are converted to
GMPY's bignum representation which speeds up exponentiation.
"""
x = gmpy.mpz(x)
y = gmpy.mpz(y)
mod = gmp... | Add function for fast modular exponentiation.
The function uses GMPY's bignum arithmetic which speeds up the calculation.
| |
603c36aec2a4704bb4cf41c224194a5f83f9babe | sale_payment_method_automatic_workflow/__openerp__.py | sale_payment_method_automatic_workflow/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | Set the module as auto_install | Set the module as auto_install
So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them
| Python | agpl-3.0 | BT-ojossen/e-commerce,Antiun/e-commerce,raycarnes/e-commerce,jt-xx/e-commerce,gurneyalex/e-commerce,BT-ojossen/e-commerce,Endika/e-commerce,damdam-s/e-commerce,vauxoo-dev/e-commerce,charbeljc/e-commerce,brain-tec/e-commerce,BT-jmichaud/e-commerce,Endika/e-commerce,brain-tec/e-commerce,JayVora-SerpentCS/e-commerce,fevxi... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | Set the module as auto_install
So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Ca... |
5e53f1e86fc7c4f1c7b42479684ac393c997ce52 | client/test/test-unrealcv.py | client/test/test-unrealcv.py | # TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realist... | # TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realist... | Fix exit code of unittest. | Fix exit code of unittest.
| Python | mit | qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv | # TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realist... | Fix exit code of unittest.
# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import Te... |
706dbcc5208cdebe616e387b280aa7411d4bdc42 | setup.py | setup.py | # coding: utf-8
from setuptools import setup, find_packages
setup(
name = 'thumbor_aws',
version = "1",
description = 'Thumbor AWS extensions',
author = 'William King',
author_email = 'willtrking@gmail.com',
zip_safe = False,
include_package_data = True,
packages=find_packages(),
install_requires=['py-dateut... | # coding: utf-8
from setuptools import setup, find_packages
setup(
name = 'thumbor_aws',
version = "1",
description = 'Thumbor AWS extensions',
author = 'William King',
author_email = 'willtrking@gmail.com',
zip_safe = False,
include_package_data = True,
packages=find_packages(),
install_requires=['python-da... | Use python-dateutil instead of py-dateutil | Use python-dateutil instead of py-dateutil
| Python | mit | voxmedia/aws,bob3000/thumbor_aws,pgr0ss/aws,andrew-a-dev/aws,aoqfonseca/aws,tsauzeau/aws,thumbor-community/aws,guilhermef/aws,ScrunchEnterprises/thumbor_aws,abaldwin1/tc_aws | # coding: utf-8
from setuptools import setup, find_packages
setup(
name = 'thumbor_aws',
version = "1",
description = 'Thumbor AWS extensions',
author = 'William King',
author_email = 'willtrking@gmail.com',
zip_safe = False,
include_package_data = True,
packages=find_packages(),
install_requires=['python-da... | Use python-dateutil instead of py-dateutil
# coding: utf-8
from setuptools import setup, find_packages
setup(
name = 'thumbor_aws',
version = "1",
description = 'Thumbor AWS extensions',
author = 'William King',
author_email = 'willtrking@gmail.com',
zip_safe = False,
include_package_data = True,
packages=fi... |
6f148fb1bb047b4977c8fcd1d898c231bed3fc9d | indra/tests/test_dart_client.py | indra/tests/test_dart_client.py | import json
from indra.literature.dart_client import jsonify_query_data
def test_timestamp():
# Should ignore "after"
assert jsonify_query_data(timestamp={'on': '2020-01-01',
'after': '2020-01-02'}) == \
json.dumps({"timestamp": {"on": "2020-01-01"}})
asser... | Add two tests for dart client | Add two tests for dart client
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra | import json
from indra.literature.dart_client import jsonify_query_data
def test_timestamp():
# Should ignore "after"
assert jsonify_query_data(timestamp={'on': '2020-01-01',
'after': '2020-01-02'}) == \
json.dumps({"timestamp": {"on": "2020-01-01"}})
asser... | Add two tests for dart client
| |
e2fa4b150546be4b4f0ae59f18ef6ba2b6180d1a | accounts/serializers.py | accounts/serializers.py | """Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and field definitions"""
model = User
... | """Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and field definitions"""
model = User
... | Change avatar to avatar_url in the user API | Change avatar to avatar_url in the user API
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,lutris/website | """Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and field definitions"""
model = User
... | Change avatar to avatar_url in the user API
"""Serializers for account models"""
# pylint: disable=too-few-public-methods
from rest_framework import serializers
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer for Users"""
class Meta:
"""Model and fie... |
d791b593dbf3d6505bf9eac8766aaf0b7f22c721 | launch_instance.py | launch_instance.py | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(sec... | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=False):
'''
'''
if not isinstance(se... | Disable the extra check by default | Disable the extra check by default
| Python | mit | Astroua/aws_controller,Astroua/aws_controller | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=False):
'''
'''
if not isinstance(se... | Disable the extra check by default
# License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
''... |
d08b0a11176225302b01657e9d396066923ae7ce | polyfilter.py | polyfilter.py | #!/usr/bin/python
# Polyfilter - filters polygon files for very small polygons
import sys
f = open(sys.argv[1])
def PolygonArea(corners):
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corn... | Add filter program to remove small polygons | Add filter program to remove small polygons
| Python | mit | jmacarthur/ld34,jmacarthur/ld34,jmacarthur/ld34 | #!/usr/bin/python
# Polyfilter - filters polygon files for very small polygons
import sys
f = open(sys.argv[1])
def PolygonArea(corners):
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corn... | Add filter program to remove small polygons
| |
5631276591cf2c4e3c83920da32857e47286d9c9 | wanikani/django.py | wanikani/django.py | from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFI... |
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key... | Switch to getting the API key from the URL instead of a config file. | Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want. | Python | mit | kfdm/wanikani,kfdm/wanikani |
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key... | Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want.
from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
fr... |
849a4e5daf2eb845213ea76179d7a8143148f39a | lib/mixins.py | lib/mixins.py | class Countable(object):
@classmethod
def count(cls, options={}):
return int(cls.get("count", **options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_id=self.id)
def add_metafield(self, metafield):
if self.is_n... | class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_... | Allow count method to be used the same way as find. | Allow count method to be used the same way as find.
| Python | mit | varesa/shopify_python_api,metric-collective/shopify_python_api,gavinballard/shopify_python_api,asiviero/shopify_python_api,ifnull/shopify_python_api,Shopify/shopify_python_api,SmileyJames/shopify_python_api | class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_... | Allow count method to be used the same way as find.
class Countable(object):
@classmethod
def count(cls, options={}):
return int(cls.get("count", **options))
class Metafields(object):
def metafields(self):
return Metafield.find(resource=self.__class__.plural, resource_id=self.id)
def... |
4c2c80e0004a758787beb555fbbe789cce5e82fc | nova/tests/test_vmwareapi_vm_util.py | nova/tests/test_vmwareapi_vm_util.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Canonical Corp.
# 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.or... | Fix variable referenced before assginment in vmwareapi code. | Fix variable referenced before assginment in vmwareapi code.
Add unitests for VMwareapi vm_util.
fix bug #1177689
Change-Id: If16109ee626c197227affba122c2e4986d92d2df
| Python | apache-2.0 | n0ano/gantt,n0ano/gantt | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Canonical Corp.
# 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.or... | Fix variable referenced before assginment in vmwareapi code.
Add unitests for VMwareapi vm_util.
fix bug #1177689
Change-Id: If16109ee626c197227affba122c2e4986d92d2df
| |
ad4ecad2e5785ddeb7bbd595e59dc12345c4b256 | xbob/blitz/__init__.py | xbob/blitz/__init__.py | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_v... | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_v... | Add API number in get_config() | Add API number in get_config()
| Python | bsd-3-clause | tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_v... | Add API number in get_config()
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
fro... |
fd50ce4b22b4f3d948a64ed400340c0fc744de49 | src/waldur_core/core/migrations/0008_changeemailrequest_uuid.py | src/waldur_core/core/migrations/0008_changeemailrequest_uuid.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_changeemailrequest'),
]
operations = [
migrations.AddField(
model_name='changeemailrequest', name='uuid', field=models.UUIDField(),
),
]
| from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_changeemailrequest'),
]
operations = [
migrations.AddField(
model_name='changeemailrequest',
name='uuid',
field=models.UUIDField(null=True),... | Allow null values in UUID field. | Allow null values in UUID field.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_changeemailrequest'),
]
operations = [
migrations.AddField(
model_name='changeemailrequest',
name='uuid',
field=models.UUIDField(null=True),... | Allow null values in UUID field.
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_changeemailrequest'),
]
operations = [
migrations.AddField(
model_name='changeemailrequest', name='uuid', field=models.UUIDField()... |
7bf86f0ef0572e86370726ff25479d051b3fbd3e | scripts/check_dataset_integrity.py | scripts/check_dataset_integrity.py | import os
from collections import defaultdict
import click
import dtoolcore
@click.command()
@click.argument('dataset_path')
def main(dataset_path):
uri = "disk:{}".format(dataset_path)
proto_dataset = dtoolcore.ProtoDataSet.from_uri(uri)
overlays = defaultdict(dict)
for handle in proto_dataset.... | Add script to check dataset integrity | Add script to check dataset integrity
| Python | mit | JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field,JIC-Image-Analysis/senescence-in-field | import os
from collections import defaultdict
import click
import dtoolcore
@click.command()
@click.argument('dataset_path')
def main(dataset_path):
uri = "disk:{}".format(dataset_path)
proto_dataset = dtoolcore.ProtoDataSet.from_uri(uri)
overlays = defaultdict(dict)
for handle in proto_dataset.... | Add script to check dataset integrity
| |
f381214b4d05fb0c809888ea6362a4125ae3b779 | test/Configure/VariantDir2.py | test/Configure/VariantDir2.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | Add test case for configure failure. | Add test case for configure failure.
TryRun fails to find the executable when VariantDir is set up from
SConscript/SConstruct.
git-svn-id: 7892167f69f80ee5d3024affce49f20c74bcb41d@4363 fdb21ef1-2011-0410-befe-b5e4ea1792b1
| Python | mit | azverkan/scons,azverkan/scons,azverkan/scons,azverkan/scons,azverkan/scons | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | Add test case for configure failure.
TryRun fails to find the executable when VariantDir is set up from
SConscript/SConstruct.
git-svn-id: 7892167f69f80ee5d3024affce49f20c74bcb41d@4363 fdb21ef1-2011-0410-befe-b5e4ea1792b1
| |
7dced29bcf8b2b5f5220f5dbfeaf631d9d5fc409 | examples/backtest.py | examples/backtest.py | import time
import logging
from pythonjsonlogger import jsonlogger
from flumine import FlumineBacktest, clients
from strategies.lowestlayer import LowestLayer
logger = logging.getLogger()
custom_format = "%(asctime) %(levelname) %(message)"
log_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(c... | import time
import logging
from pythonjsonlogger import jsonlogger
from flumine import FlumineBacktest, clients
from strategies.lowestlayer import LowestLayer
logger = logging.getLogger()
custom_format = "%(asctime) %(levelname) %(message)"
log_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(c... | Comment to say using logging.CRITICAL is faster | Comment to say using logging.CRITICAL is faster
| Python | mit | liampauling/flumine | import time
import logging
from pythonjsonlogger import jsonlogger
from flumine import FlumineBacktest, clients
from strategies.lowestlayer import LowestLayer
logger = logging.getLogger()
custom_format = "%(asctime) %(levelname) %(message)"
log_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(c... | Comment to say using logging.CRITICAL is faster
import time
import logging
from pythonjsonlogger import jsonlogger
from flumine import FlumineBacktest, clients
from strategies.lowestlayer import LowestLayer
logger = logging.getLogger()
custom_format = "%(asctime) %(levelname) %(message)"
log_handler = logging.Strea... |
024b862bdd4ae3bf4c3058ef32b6016b280a4cf6 | tests/web/test_request.py | tests/web/test_request.py | import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.url = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
self.assertEqual('post', Request.POST)
... | import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.host = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
self.assertEqual('post', Request.POST)
... | Remove tests for response_time, update variable names | Remove tests for response_time, update variable names
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.host = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Request.GET)
self.assertEqual('post', Request.POST)
... | Remove tests for response_time, update variable names
import unittest
from performance.web import Request, RequestTypeError, RequestTimeError
class RequestTestCase(unittest.TestCase):
def setUp(self):
self.url = 'http://www.google.com'
def test_constants(self):
self.assertEqual('get', Reques... |
5f416dadecf21accbaccd69740c5398967ec4a7c | doubles/nose.py | doubles/nose.py | from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
def beforeTest(self, test):
setup()
d... | from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
def beforeTest(self, test):
setup()
d... | Remove verification skipping in Nose plugin for now. | Remove verification skipping in Nose plugin for now.
| Python | mit | uber/doubles | from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
def beforeTest(self, test):
setup()
d... | Remove verification skipping in Nose plugin for now.
from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
... |
5c61d7f125078cb6b3bd0c5700ae9219baab0078 | webapp/tests/test_dashboard.py | webapp/tests/test_dashboard.py | from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('graphite.dashboard.views.dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
| from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
| Update reverse call to use named URL | Update reverse call to use named URL
| Python | apache-2.0 | redice/graphite-web,dbn/graphite-web,Skyscanner/graphite-web,penpen/graphite-web,lyft/graphite-web,esnet/graphite-web,bpaquet/graphite-web,atnak/graphite-web,section-io/graphite-web,kkdk5535/graphite-web,cosm0s/graphite-web,cgvarela/graphite-web,gwaldo/graphite-web,redice/graphite-web,edwardmlyte/graphite-web,atnak/gra... | from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
| Update reverse call to use named URL
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('graphite.dashboard.views.dashboard')
response = self.client.get(url)
self.assertEqual(response.status_... |
517e8f16dbc24af3371a287e69c4d1361c1744f6 | python_scripts/azure_sense.py | python_scripts/azure_sense.py | #!/usr/bin/env python
"""
sends temperature, humidity and pressure
gathered from Sense Hat on Raspberry Pi2 to Azure Table Storage
only python works with Azure , not python3,
sudo pip install azure-storage
invoke (no sudo required): python azure_sense.py
"""
import time
from sense_hat import SenseHat
from datet... | Add script for sending sense info to azure table storage | Add script for sending sense info to azure table storage
| Python | mit | mirontoli/tolle-rasp,mirontoli/tolle-rasp,mirontoli/tolle-rasp,mirontoli/tolle-rasp,mirontoli/tolle-rasp | #!/usr/bin/env python
"""
sends temperature, humidity and pressure
gathered from Sense Hat on Raspberry Pi2 to Azure Table Storage
only python works with Azure , not python3,
sudo pip install azure-storage
invoke (no sudo required): python azure_sense.py
"""
import time
from sense_hat import SenseHat
from datet... | Add script for sending sense info to azure table storage
| |
f2ab04ec2eb870e661223fd397d7c5a23935a233 | src/apps/employees/schema/types.py | src/apps/employees/schema/types.py | import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class Meta:
model = models.Employee
filte... | import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class Meta:
model = models.Employee
filte... | Remove Node interfaces (use origin id for objects) | Remove Node interfaces (use origin id for objects)
| Python | mit | wis-software/office-manager | import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class Meta:
model = models.Employee
filte... | Remove Node interfaces (use origin id for objects)
import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class ... |
a0342631d6888f4748af9011839020ee0843a721 | crypto_enigma/_version.py | crypto_enigma/_version.py | #!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release__ = '0.2.1' # N(.N)*
__pre_release__ =... | #!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release__ = '0.2.1' # N(.N)*
__pre_release__ =... | Update test version after test release | Update test version after test release
| Python | bsd-3-clause | orome/crypto-enigma-py | #!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release__ = '0.2.1' # N(.N)*
__pre_release__ =... | Update test version after test release
#!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release... |
fd99ef86dfca50dbd36b2c1a022cf30a0720dbea | scrapy/squeues.py | scrapy/squeues.py | """
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).p... | """
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).p... | Test for AttributeError when pickling objects (Python>=3.5) | Test for AttributeError when pickling objects (Python>=3.5)
Same "fix" as in e.g. https://github.com/joblib/joblib/pull/246
| Python | bsd-3-clause | YeelerG/scrapy,wenyu1001/scrapy,GregoryVigoTorres/scrapy,crasker/scrapy,jdemaeyer/scrapy,Parlin-Galanodel/scrapy,arush0311/scrapy,Digenis/scrapy,pablohoffman/scrapy,ArturGaspar/scrapy,kmike/scrapy,crasker/scrapy,eLRuLL/scrapy,wujuguang/scrapy,carlosp420/scrapy,darkrho/scrapy-scrapy,redapple/scrapy,carlosp420/scrapy,bar... | """
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class SerializableQueue(queue_class):
def push(self, obj):
s = serialize(obj)
super(SerializableQueue, self).p... | Test for AttributeError when pickling objects (Python>=3.5)
Same "fix" as in e.g. https://github.com/joblib/joblib/pull/246
"""
Scheduler queues
"""
import marshal
from six.moves import cPickle as pickle
from queuelib import queue
def _serializable_queue(queue_class, serialize, deserialize):
class Serializabl... |
4cf8ae2ab95e9c7ed1a091532f12a4211f7580b7 | textingtree.py | textingtree.py | import os
import requests
import tinycss2
from tinycss2 import color3
from flask import Flask, Response, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def merry_christmas():
return 'Merry Christmas!'
@app.route('/sms', methods=['POST'])
def sms():
body = request.values.get('Body', None)
... | Add application code with SMS route to accept SMS and route to Spark Core via their API | Add application code with SMS route to accept SMS and route to Spark Core via their API
| Python | mit | willdages/The-Texting-Tree | import os
import requests
import tinycss2
from tinycss2 import color3
from flask import Flask, Response, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def merry_christmas():
return 'Merry Christmas!'
@app.route('/sms', methods=['POST'])
def sms():
body = request.values.get('Body', None)
... | Add application code with SMS route to accept SMS and route to Spark Core via their API
| |
380331a54ae09a54e458b30a0fb6a459faa76f37 | emission/analysis/point_features.py | emission/analysis/point_features.py | # Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calDistance(point1, point2):
return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])
def calHeading(point1, point2):
re... | # Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calDistance(point1, point2):
return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])
def calHeading(point1, point2):
re... | Change the feature calculation to match the new unified format | Change the feature calculation to match the new unified format
- the timestamps are now in seconds, so no need to divide them
- the field is called ts, not mTime
| Python | bsd-3-clause | e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,joshzarrabi/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission... | # Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calDistance(point1, point2):
return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])
def calHeading(point1, point2):
re... | Change the feature calculation to match the new unified format
- the timestamps are now in seconds, so no need to divide them
- the field is called ts, not mTime
# Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calD... |
2bd5887a62d0f6bfd6f9290604effad322e8ab1e | myElsClient.py | myElsClient.py | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... | Add basic HTTP error handling. | Add basic HTTP error handling.
| Python | bsd-3-clause | ElsevierDev/elsapy | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
... | Add basic HTTP error handling.
import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "https://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
... |
f408346e69f643e603f279c2581fad8c99962b11 | service_registry_cli/commands/configuration/remove.py | service_registry_cli/commands/configuration/remove.py | # Copyright 2012 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the... | Add a command for removing a configuration value. | Add a command for removing a configuration value.
| Python | apache-2.0 | racker/python-service-registry-cli,racker/python-service-registry-cli | # Copyright 2012 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the... | Add a command for removing a configuration value.
| |
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 | 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
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 da... |
e45f394c61620db13bae579a29043dfdd6ae2d0f | SLA_bot/alertfeed.py | SLA_bot/alertfeed.py | import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDeco... | import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDeco... | Remove text coloring in AlertFeed if it seems like scheduled text | Remove text coloring in AlertFeed if it seems like scheduled text
| Python | mit | EsqWiggles/SLA-bot,EsqWiggles/SLA-bot | import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
return await response.json()
except json.decoder.JSONDeco... | Remove text coloring in AlertFeed if it seems like scheduled text
import asyncio
import json
import aiohttp
import SLA_bot.config as cf
class AlertFeed:
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def download(url):
try:
async with aiohttp.get(url) as response:
... |
bf17a86bccf25ead90d11dd15a900cb784d9cb9f | raco/myrial/myrial_test.py | raco/myrial/myrial_test.py |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parse... |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor ... | Revert "Add compile_to_json invocation in Myrial test fixture" | Revert "Add compile_to_json invocation in Myrial test fixture"
This reverts commit ceb848021d5323b5bad8518ac7ed850a51fc89ca.
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor ... | Revert "Add compile_to_json invocation in Myrial test fixture"
This reverts commit ceb848021d5323b5bad8518ac7ed850a51fc89ca.
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json
... |
038b56134017b6b3e4ea44d1b7197bc5168868d3 | safeopt/__init__.py | safeopt/__init__.py | """
The `safeopt` package provides...
Main classes
============
.. autosummary::
SafeOpt
SafeOptSwarm
Utilities
=========
.. autosummary::
sample_gp_function
linearly_spaced_combinations
plot_2d_gp
plot_3d_gp
plot_contour_gp
"""
from __future__ import absolute_import
from .utilities import *
fr... | """
The `safeopt` package provides...
Main classes
============
These classes provide the main functionality for Safe Bayesian optimization.
.. autosummary::
SafeOpt
SafeOptSwarm
Utilities
=========
The following are utilities to make testing and working with the library more pleasant.
.. autosummary::
s... | Add short comment to docs | Add short comment to docs
| Python | mit | befelix/SafeOpt,befelix/SafeOpt | """
The `safeopt` package provides...
Main classes
============
These classes provide the main functionality for Safe Bayesian optimization.
.. autosummary::
SafeOpt
SafeOptSwarm
Utilities
=========
The following are utilities to make testing and working with the library more pleasant.
.. autosummary::
s... | Add short comment to docs
"""
The `safeopt` package provides...
Main classes
============
.. autosummary::
SafeOpt
SafeOptSwarm
Utilities
=========
.. autosummary::
sample_gp_function
linearly_spaced_combinations
plot_2d_gp
plot_3d_gp
plot_contour_gp
"""
from __future__ import absolute_import
... |
a3bc13ed4943dae80928da4e09765002bb0db60c | nbsetuptools/tests/test_nbsetuptools.py | nbsetuptools/tests/test_nbsetuptools.py | import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup
class NBSetupTestCase(unittest.TestCase):
def setUp(self):
self.prefix = tempfile.mkdtemp()
self.params = {
'prefix': self.prefix,
'static': os.pat... | import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup
class NBSetupTestCase(unittest.TestCase):
def setUp(self):
self.prefix = tempfile.mkdtemp()
self.params = {
'prefix': self.prefix,
'static': os.pat... | Comment out test that doesn't pass on Windows | Comment out test that doesn't pass on Windows
It appears to be assuming unix paths, so I'm going on the assumption
that it's not a valid test case on Windows.
| Python | bsd-3-clause | Anaconda-Server/nbsetuptools,Anaconda-Server/nbsetuptools,Anaconda-Server/nbsetuptools | import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup
class NBSetupTestCase(unittest.TestCase):
def setUp(self):
self.prefix = tempfile.mkdtemp()
self.params = {
'prefix': self.prefix,
'static': os.pat... | Comment out test that doesn't pass on Windows
It appears to be assuming unix paths, so I'm going on the assumption
that it's not a valid test case on Windows.
import os
import tempfile
import unittest
from jupyter_core.paths import jupyter_config_dir
from ..nbsetuptools import NBSetup
class NBSetupTestCase(unittest... |
8a0fc8a9241a7d090f801101cd5324d15e7ae990 | heutagogy/views.py | heutagogy/views.py | from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
r = re... | from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
r = re... | Fix reading json from client (ignore mimetype). | Fix reading json from client (ignore mimetype).
• http://stackoverflow.com/a/14112400/2517622
| Python | agpl-3.0 | heutagogy/heutagogy-backend,heutagogy/heutagogy-backend | from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
r = re... | Fix reading json from client (ignore mimetype).
• http://stackoverflow.com/a/14112400/2517622
from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'He... |
cf748e2bc4f28a11c79555f2e6c3d1f89d027709 | tests/test_memory_leak.py | tests/test_memory_leak.py | import resource
import pytest
from .models import TestModel as DirtyMixinModel
pytestmark = pytest.mark.django_db
def test_rss_usage():
DirtyMixinModel()
rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
for _ in range(1000):
DirtyMixinModel()
rss_2 = resource.getrusage(resource.RU... | import gc
import resource
import pytest
from .models import TestModel as DirtyMixinModel
pytestmark = pytest.mark.django_db
def test_rss_usage():
DirtyMixinModel()
gc.collect()
rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
for _ in range(1000):
DirtyMixinModel()
gc.collect(... | Call gc.collect() before measuring memory usage. | Call gc.collect() before measuring memory usage.
| Python | bsd-3-clause | romgar/django-dirtyfields,smn/django-dirtyfields | import gc
import resource
import pytest
from .models import TestModel as DirtyMixinModel
pytestmark = pytest.mark.django_db
def test_rss_usage():
DirtyMixinModel()
gc.collect()
rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
for _ in range(1000):
DirtyMixinModel()
gc.collect(... | Call gc.collect() before measuring memory usage.
import resource
import pytest
from .models import TestModel as DirtyMixinModel
pytestmark = pytest.mark.django_db
def test_rss_usage():
DirtyMixinModel()
rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
for _ in range(1000):
DirtyMixin... |
b698f6925b4629d7473fbe42806f54068d98428a | tests/component/test_component_identidock.py | tests/component/test_component_identidock.py | import sys
print(sys.path)
| import pytest
import requests
from time import sleep
COMPONENT_INDEX_URL = "http://identidock:5000"
COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'
def test_get_mainpage():
print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
sleep(1)
page =... | Add component test functions using pytest | Add component test functions using pytest
| Python | mit | anirbanroydas/ci-testing-python,anirbanroydas/ci-testing-python,anirbanroydas/ci-testing-python | import pytest
import requests
from time import sleep
COMPONENT_INDEX_URL = "http://identidock:5000"
COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster'
def test_get_mainpage():
print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server')
sleep(1)
page =... | Add component test functions using pytest
import sys
print(sys.path)
|
2c141722aa8478b7e6a078d02206a26db3772a95 | setup.py | setup.py | import os
from setuptools import setup
def getPackages(base):
packages = []
def visit(arg, directory, files):
if '__init__.py' in files:
packages.append(directory.replace('/', '.'))
os.path.walk(base, visit, None)
return packages
setup(
name='tryfer',
version='0.1',
... | import os
from setuptools import setup
def getPackages(base):
packages = []
def visit(arg, directory, files):
if '__init__.py' in files:
packages.append(directory.replace('/', '.'))
os.path.walk(base, visit, None)
return packages
setup(
name='tryfer',
version='0.1',
... | Add maintainer and long description. | Add maintainer and long description.
| Python | apache-2.0 | tryfer/tryfer | import os
from setuptools import setup
def getPackages(base):
packages = []
def visit(arg, directory, files):
if '__init__.py' in files:
packages.append(directory.replace('/', '.'))
os.path.walk(base, visit, None)
return packages
setup(
name='tryfer',
version='0.1',
... | Add maintainer and long description.
import os
from setuptools import setup
def getPackages(base):
packages = []
def visit(arg, directory, files):
if '__init__.py' in files:
packages.append(directory.replace('/', '.'))
os.path.walk(base, visit, None)
return packages
setup(
... |
0e593183ccf9fe719d8dc6ced05a9967698f5c7d | api/app.py | api/app.py | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = m... | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = m... | Remove GET options in url | Remove GET options in url
| Python | mit | joaojunior/y_text_recommender_system | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = m... | Remove GET options in url
from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(sel... |
6bc1f6e466fa09dd0bc6a076f9081e1aa03efdc7 | examples/translations/dutch_test_1.py | examples/translations/dutch_test_1.py | # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikiped... | # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikiped... | Update the Dutch example test | Update the Dutch example test
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | # Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.controleren_tekst("Welkom op Wikiped... | Update the Dutch example test
# Dutch Language Test
from seleniumbase.translate.dutch import Testgeval
class MijnTestklasse(Testgeval):
def test_voorbeeld_1(self):
self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina")
self.controleren_element('a[title*="hoofdpagina gaan"]')
self.contr... |
5a6a96435b7cf45cbbc5f2b81a7be84cd986b456 | haas/__main__.py | haas/__main__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
import sys # pragma: no cover
from .main import main # pragma: no cover
if __name__ == '__main... | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
import sys # pragma: no cover
from haas.main import main # pragma: no cover
if __name__ == '__... | Use absolute import for main entry point. | Use absolute import for main entry point.
| Python | bsd-3-clause | itziakos/haas,sjagoe/haas,scalative/haas,sjagoe/haas,itziakos/haas,scalative/haas | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
import sys # pragma: no cover
from haas.main import main # pragma: no cover
if __name__ == '__... | Use absolute import for main entry point.
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
import sys # pragma: no cover
from .main import main ... |
ffff9d10862391289e4fba8ac120983ac6368200 | setup.py | setup.py | from setuptools import setup
setup(
name='cmsplugin-biography',
version='0.0.1',
packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
install_requires=[
'django-cms',
'djangocms-text-ckeditor==1.0.9',
'easy-thumbnails==1.2',
],
author='Kevin Richardson'... | from setuptools import setup
setup(
name='cmsplugin-biography',
version='0.0.1',
packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
install_requires=[
'django-cms',
'djangocms-text-ckeditor==1.0.9',
'easy-thumbnails==1.2',
],
author='Kevin Richardson'... | Mark package as not zip_safe | Mark package as not zip_safe
This package needs access to its templates to function. Thus, the
zip_safe flag has been set to False to tell setuptools to not
install the package's egg as a zip file.
See http://pythonhosted.org/distribute/setuptools.html#setting-the-zip-safe-flag
for further information.
| Python | mit | kfr2/cmsplugin-biography | from setuptools import setup
setup(
name='cmsplugin-biography',
version='0.0.1',
packages=['cmsplugin_biography', 'cmsplugin_biography.migrations', ],
install_requires=[
'django-cms',
'djangocms-text-ckeditor==1.0.9',
'easy-thumbnails==1.2',
],
author='Kevin Richardson'... | Mark package as not zip_safe
This package needs access to its templates to function. Thus, the
zip_safe flag has been set to False to tell setuptools to not
install the package's egg as a zip file.
See http://pythonhosted.org/distribute/setuptools.html#setting-the-zip-safe-flag
for further information.
from setuptoo... |
3c9a062ebb7745fbdefcf836165ef5cd85825417 | setup.py | setup.py | from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hierarchies'
]
packages = ['pyaccess']... | from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hierarchies'
]
packages = ['pyaccess']... | Use pyaccess as the package name. | Use pyaccess as the package name.
| Python | agpl-3.0 | UDST/pandana,SANDAG/pandana,UDST/pandana,rafapereirabr/pandana,SANDAG/pandana,UDST/pandana,waddell/pandana,waddell/pandana,waddell/pandana,synthicity/pandana,rafapereirabr/pandana,osPlanning/pandana,waddell/pandana,osPlanning/pandana,osPlanning/pandana,osPlanning/pandana,rafapereirabr/pandana,synthicity/pandana,rafaper... | from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hierarchies'
]
packages = ['pyaccess']... | Use pyaccess as the package name.
from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hie... |
e91b691ba2e9a83d8cc94f42bdc41c9a7350c790 | setup.py | setup.py | #!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | #!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | Add trove classifiers specifying Python 3 support. | Add trove classifiers specifying Python 3 support.
| Python | mit | testing-cabal/extras | #!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | Add trove classifiers specifying Python 3 support.
#!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
ver... |
04337a036429e98edab7c2e5f17086a3ccfe263b | jsonsempai.py | jsonsempai.py | import sys
class SempaiLoader(object):
def __init__(self, *args):
print args
def find_module(self, fullname, path=None):
print 'finding', fullname, path
if fullname == 'simple':
return self
return None
sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple'... | Add very simple module finder | Add very simple module finder
| Python | mit | kragniz/json-sempai | import sys
class SempaiLoader(object):
def __init__(self, *args):
print args
def find_module(self, fullname, path=None):
print 'finding', fullname, path
if fullname == 'simple':
return self
return None
sys.path_hooks.append(SempaiLoader)
sys.path.insert(0, 'simple'... | Add very simple module finder
| |
b6bf01a5c95da0de1e6831a3cf41243e69297854 | setup.py | setup.py | # Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | # Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | Remove workaround for issue with older python versions. | Remove workaround for issue with older python versions.
| Python | apache-2.0 | osrg/ryu,osrg/ryu,osrg/ryu,osrg/ryu,osrg/ryu | # Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | Remove workaround for issue with older python versions.
# Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
f89398d49b53b3ec43b196c22a5735696f2de021 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
... | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
... | Update pins to match horton dictionary/api | chore(pins): Update pins to match horton dictionary/api
- Update pins to match horton dictionary/api
| Python | apache-2.0 | NCI-GDC/gdcdatamodel,NCI-GDC/gdcdatamodel | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
... | chore(pins): Update pins to match horton dictionary/api
- Update pins to match horton dictionary/api
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
... |
1261777b6aaaea6947a32477e340ef1597045866 | nested_admin/urls.py | nested_admin/urls.py | try:
from django.conf.urls.defaults import patterns, url
except ImportError:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
| Fix DeprecationWarning in Django 1.5 | Fix DeprecationWarning in Django 1.5
| Python | bsd-2-clause | sbussetti/django-nested-admin,sbussetti/django-nested-admin,olivierdalang/django-nested-admin,sbussetti/django-nested-admin,olivierdalang/django-nested-admin,olivierdalang/django-nested-admin | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
| Fix DeprecationWarning in Django 1.5
try:
from django.conf.urls.defaults import patterns, url
except ImportError:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
|
c2506fdc71f1dcff2e3455c668e78ad6b7d5d94b | scripts/fenix/fenix_download.py | scripts/fenix/fenix_download.py | # python fenix_download login_file <url> -e <file_extension> (DEFAULT = pdf) -d <download_directory>
#
#
from fenix import Fenix
import argparse
if __name__ == '__main__':
# TODO: argparse
parser = argparse.ArgumentParser(description='Download files from Fenix Edu pages')
parser.add_argument('login', type... | Add inital structure for fenix downloader | Add inital structure for fenix downloader
| Python | mit | iluxonchik/python-general-repo | # python fenix_download login_file <url> -e <file_extension> (DEFAULT = pdf) -d <download_directory>
#
#
from fenix import Fenix
import argparse
if __name__ == '__main__':
# TODO: argparse
parser = argparse.ArgumentParser(description='Download files from Fenix Edu pages')
parser.add_argument('login', type... | Add inital structure for fenix downloader
| |
f100faade749d86597e1c8c52b88d55261e7a4dc | suorganizer/wsgi.py | suorganizer/wsgi.py | """
WSGI config for suorganizer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... | """
WSGI config for suorganizer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Dj... | Use WhiteNoise for static content. | Ch29: Use WhiteNoise for static content.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | """
WSGI config for suorganizer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Dj... | Ch29: Use WhiteNoise for static content.
"""
WSGI config for suorganizer project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_ap... |
44035c166ffde209a47d7739af0d56acb4ec0422 | notebooks/test_notebooks.py | notebooks/test_notebooks.py | # -*- coding: utf-8 -*-
'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb
For jupyter configuration information, run: jupyter --path
'''
# Dependencies: nbformat, nbc... | Add script to automate notebooks testing | Add script to automate notebooks testing
| Python | agpl-3.0 | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia | # -*- coding: utf-8 -*-
'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb
For jupyter configuration information, run: jupyter --path
'''
# Dependencies: nbformat, nbc... | Add script to automate notebooks testing
| |
cfc95643733244275e605a8ff0c00d4861067a13 | character_shift/character_shift.py | character_shift/character_shift.py | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1)... | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BC... | Use bitwise operators on ordinals to reduce code size | Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
| Python | mit | TotempaaltJ/tiniest-code,TotempaaltJ/tiniest-code | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BC... | Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*dec... |
81b6a138c476084f9ddd6063f31d3efd0ba6e2cf | start.py | start.py | # -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.'... | # -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.'... | Make the logging level configurable | Make the logging level configurable
| Python | mit | DesertBot/DesertBot | # -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.'... | Make the logging level configurable
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(descri... |
ad70a7ec6543d64ec185eb2d52ccfa291a1dfad6 | servicerating/views.py | servicerating/views.py | import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact... | import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact... | Remove FK's from CSV export for massive speed boost | Remove FK's from CSV export for massive speed boost
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control | import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact... | Remove FK's from CSV export for massive speed boost
import csv
from django.http import HttpResponse
from servicerating.models import Response
def report_responses(request):
qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN ... |
c5d4c0cbfced859407c5569d879cfb7b9815eb57 | alerts/lib/alert_plugin_set.py | alerts/lib/alert_plugin_set.py | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summa... | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summa... | Convert debug message into unicode string | Convert debug message into unicode string
| Python | mpl-2.0 | Phrozyn/MozDef,mozilla/MozDef,gdestuynder/MozDef,mozilla/MozDef,Phrozyn/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,gdestuynder/Mo... | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summa... | Convert debug message into unicode string
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from plugin_set import PluginSet
from utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
... |
f80febf88c3f045493e75efc788d88058f021f0f | merge_sort.py | merge_sort.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [len(lyst)]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst,... | Fix initial buf variable to act as an array | Fix initial buf variable to act as an array
| Python | mit | nbeck90/data_structures_2 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst,... | Fix initial buf variable to act as an array
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [len(lyst)]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
... |
8112291023edff1a3803f2a3a404d83e69e1ee34 | astral/api/tests/__init__.py | astral/api/tests/__init__.py | import tornado.testing
from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session
class BaseTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return NodeWebAPI()
def get_http_port(self):
return 8000
def setUp(self):
super(B... | import tornado.testing
from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session
class BaseTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return NodeWebAPI()
def get_http_port(self):
return 8000
def setUp(self):
super(B... | Drop all tables after tests - looks like we're back in business. | Drop all tables after tests - looks like we're back in business.
| Python | mit | peplin/astral | import tornado.testing
from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session
class BaseTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return NodeWebAPI()
def get_http_port(self):
return 8000
def setUp(self):
super(B... | Drop all tables after tests - looks like we're back in business.
import tornado.testing
from astral.api.app import NodeWebAPI
from astral.models import drop_all, setup_all, create_all, session
class BaseTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return NodeWebAPI()
def get_http_por... |
fe7d96c9182831613f4f44bc6c4f5903c7e02858 | setup.py | setup.py | from setuptools import setup
def fread(fn):
return open(fn, 'rb').read().decode('utf-8')
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=fread('README.rst') + '\n\n' + fread('HISTORY.rst'),
author='Ryan Hiebert',
author_email='ryan@ryanhieb... | from setuptools import setup
def fread(fn):
return open(fn, 'rb').read().decode('utf-8')
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=fread('README.rst') + '\n\n' + fread('HISTORY.rst'),
author='Ryan Hiebert',
author_email='ryan@ryanhieb... | Add Python 3.5 trove classifier | Add Python 3.5 trove classifier
| Python | mit | rpkilby/tox-travis,ryanhiebert/tox-travis,tox-dev/tox-travis | from setuptools import setup
def fread(fn):
return open(fn, 'rb').read().decode('utf-8')
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=fread('README.rst') + '\n\n' + fread('HISTORY.rst'),
author='Ryan Hiebert',
author_email='ryan@ryanhieb... | Add Python 3.5 trove classifier
from setuptools import setup
def fread(fn):
return open(fn, 'rb').read().decode('utf-8')
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=fread('README.rst') + '\n\n' + fread('HISTORY.rst'),
author='Ryan Hiebert'... |
3617400a7c0915920384d15ff273aa4c8a805d9c | core/byzantinerandomizedconsensus.py | core/byzantinerandomizedconsensus.py | from base.consensus import Consensus
class ByzantineRandomizedConsensus(Consensus):
"""
Implements a Byzantine Fault Tolerant Randomized Consensus Broadcast protocol.
"""
def propose(self, message):
pass
def decide(self):
pass | Update Byzantine Randomized Consensus protocol class | Update Byzantine Randomized Consensus protocol class
| Python | mit | koevskinikola/ByzantineRandomizedConsensus | from base.consensus import Consensus
class ByzantineRandomizedConsensus(Consensus):
"""
Implements a Byzantine Fault Tolerant Randomized Consensus Broadcast protocol.
"""
def propose(self, message):
pass
def decide(self):
pass | Update Byzantine Randomized Consensus protocol class
| |
11bb0d7aa106e1cafee8b4f00bf75a2aa02e97cf | SecC/ErrMer_Proto.py | SecC/ErrMer_Proto.py | from __future__ import division
import numpy as np
from utilBMF.HTSUtils import pFastqProxy, pFastqFile
consInFq1 = pFastqFile("/home/brett/Projects/BMFTools_Devel/lamda_data/lamda-50di"
"v_S4_L001_R1_001.fastq.rescued.shaded.BS.fastq")
consInFq2 = pFastqFile("/home/brett/Projects/BMFTools_Devel/la... | Add small script to start calculating error from kmer motifs, prototyping | Add small script to start calculating error from kmer motifs, prototyping
| Python | mit | ARUP-NGS/BMFtools,ARUP-NGS/BMFtools,ARUP-NGS/BMFtools | from __future__ import division
import numpy as np
from utilBMF.HTSUtils import pFastqProxy, pFastqFile
consInFq1 = pFastqFile("/home/brett/Projects/BMFTools_Devel/lamda_data/lamda-50di"
"v_S4_L001_R1_001.fastq.rescued.shaded.BS.fastq")
consInFq2 = pFastqFile("/home/brett/Projects/BMFTools_Devel/la... | Add small script to start calculating error from kmer motifs, prototyping
| |
0d36640d47c30d8b9cd2b2eff1c8ccf1e97c13c5 | subscriptions/management/commands/add_missed_call_service_audio_notification_to_active_subscriptions.py | subscriptions/management/commands/add_missed_call_service_audio_notification_to_active_subscriptions.py | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call servic... | Add missed call service audio notification to active subscriptions | Add missed call service audio notification to active subscriptions
| Python | bsd-3-clause | praekelt/seed-staged-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call servic... | Add missed call service audio notification to active subscriptions
| |
77f4fca43b1d4be85894ad565801d8a333008fdc | Lib/test/test_pep263.py | Lib/test/test_pep263.py | #! -*- coding: koi8-r -*-
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
u"\".e... | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\x... | Add a comment explaining -kb. | Add a comment explaining -kb.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\x... | Add a comment explaining -kb.
#! -*- coding: koi8-r -*-
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.a... |
4666849791cad70ae1bb907a2dcc35ccfc0b7de4 | backend/populate_dimkarakostas.py | backend/populate_dimkarakostas.py | from string import ascii_lowercase
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9
target_1 ... | from string import ascii_lowercase
import django
import os
import string
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength ... | Update dimkarakostas population with alignmentalphabet | Update dimkarakostas population with alignmentalphabet
| Python | mit | esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/ruptu... | from string import ascii_lowercase
import django
import os
import string
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength ... | Update dimkarakostas population with alignmentalphabet
from string import ascii_lowercase
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper... |
7c33ff3ff94b933fe9e5c8b53fa08041ef8ee404 | runserver.py | runserver.py | from geomancer import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
| from geomancer import create_app
app = create_app()
if __name__ == "__main__":
import sys
try:
port = int(sys.argv[1])
except IndexError:
port = 5000
app.run(debug=True, port=port)
| Make it so we can choose port | Make it so we can choose port
| Python | mit | associatedpress/geomancer,associatedpress/geomancer,datamade/geomancer,associatedpress/geomancer,datamade/geomancer,datamade/geomancer | from geomancer import create_app
app = create_app()
if __name__ == "__main__":
import sys
try:
port = int(sys.argv[1])
except IndexError:
port = 5000
app.run(debug=True, port=port)
| Make it so we can choose port
from geomancer import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
|
90ab0bfbac851a52f0e48f5186a727692e699a6f | geodj/youtube.py | geodj/youtube.py | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'viewCount'
query.racy = 'exclude'
... | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'viewC... | Use smart_str and include artist in results | Use smart_str and include artist in results
| Python | mit | 6/GeoDJ,6/GeoDJ | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'viewC... | Use smart_str and include artist in results
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'view... |
a2b1d10e042d135c3c014622ffeabd7e96a46f9f | tests/test_update_target.py | tests/test_update_target.py | """
Tests for helper function for updating a target from a Vuforia database.
"""
import io
import pytest
from vws import VWS
from vws.exceptions import UnknownTarget
class TestUpdateTarget:
"""
Test for updating a target.
"""
def test_get_target(
self,
client: VWS,
high_qua... | """
Tests for helper function for updating a target from a Vuforia database.
"""
import io
import pytest
from vws import VWS
from vws.exceptions import UnknownTarget
class TestUpdateTarget:
"""
Test for updating a target.
"""
def test_get_target(
self,
client: VWS,
high_qua... | Comment out part done code | Comment out part done code
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python | """
Tests for helper function for updating a target from a Vuforia database.
"""
import io
import pytest
from vws import VWS
from vws.exceptions import UnknownTarget
class TestUpdateTarget:
"""
Test for updating a target.
"""
def test_get_target(
self,
client: VWS,
high_qua... | Comment out part done code
"""
Tests for helper function for updating a target from a Vuforia database.
"""
import io
import pytest
from vws import VWS
from vws.exceptions import UnknownTarget
class TestUpdateTarget:
"""
Test for updating a target.
"""
def test_get_target(
self,
c... |
3732b2ee099989ed46e264f031b9b47c414cf6c6 | imagekit/importers.py | imagekit/importers.py | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), s... | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), s... | Insert importer at beginning of list | Insert importer at beginning of list
| Python | bsd-3-clause | tawanda/django-imagekit,FundedByMe/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), s... | Insert importer at beginning of list
import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to ma... |
cd827059f9c500603d5c6b1d1bdf1621dc87a6a2 | pyaem/handlers.py | pyaem/handlers.py | from BeautifulSoup import *
import exception
def auth_fail(response, **kwargs):
code = response['http_code']
message = 'Authentication failed - incorrect username and/or password'
raise exception.PyAemException(code, message)
def method_not_allowed(response, **kwargs):
code = response['http_code']
soup... | from BeautifulSoup import *
import exception
def auth_fail(response, **kwargs):
code = response['http_code']
message = 'Authentication failed - incorrect username and/or password'
raise exception.PyAemException(code, message)
def method_not_allowed(response, **kwargs):
code = response['http_code']
soup... | Update unexpected handler message, with http code and body. | Update unexpected handler message, with http code and body.
| Python | mit | wildone/pyaem,Sensis/pyaem | from BeautifulSoup import *
import exception
def auth_fail(response, **kwargs):
code = response['http_code']
message = 'Authentication failed - incorrect username and/or password'
raise exception.PyAemException(code, message)
def method_not_allowed(response, **kwargs):
code = response['http_code']
soup... | Update unexpected handler message, with http code and body.
from BeautifulSoup import *
import exception
def auth_fail(response, **kwargs):
code = response['http_code']
message = 'Authentication failed - incorrect username and/or password'
raise exception.PyAemException(code, message)
def method_not_allowed... |
edd5adc9be2a700421bd8e98af825322796b8714 | dns/models.py | dns/models.py | from google.appengine.ext import db
TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
class Lookup(db.Model):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Updates since 2010-01-01 ... | from google.appengine.ext import db
TOP_LEVEL_DOMAINS = """
com net org biz info
ag am at
be by
ch ck
de
es eu
fm
in io is it
la li ly
me mobi ms
name
ru
se sh sy
tel th to travel tv
us
""".split()
# Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
class UpgradeStringProperty(db.IntegerProperty):
... | Upgrade Lookup model to Expando and DNS result properties from integer to string. | Upgrade Lookup model to Expando and DNS result properties from integer to string.
| Python | mit | jcrocholl/nxdom,jcrocholl/nxdom | from google.appengine.ext import db
TOP_LEVEL_DOMAINS = """
com net org biz info
ag am at
be by
ch ck
de
es eu
fm
in io is it
la li ly
me mobi ms
name
ru
se sh sy
tel th to travel tv
us
""".split()
# Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
class UpgradeStringProperty(db.IntegerProperty):
... | Upgrade Lookup model to Expando and DNS result properties from integer to string.
from google.appengine.ext import db
TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
class Lookup(db.Model):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN ... |
066a7dacf20ed3dd123790dc78e99317856ea731 | tutorial/polls/admin.py | tutorial/polls/admin.py | from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin) | from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'question_text']
fieldsets = [
(None, {'fields' : ['question_text']}),
('Date Information', { 'fields' : ['pub_date'], 'classes': ['collap... | Put Question Admin fields in a fieldset and added a collapse class to the date field | Put Question Admin fields in a fieldset and added a collapse class to the date field
| Python | mit | ikosenn/django_reignited,ikosenn/django_reignited | from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'question_text']
fieldsets = [
(None, {'fields' : ['question_text']}),
('Date Information', { 'fields' : ['pub_date'], 'classes': ['collap... | Put Question Admin fields in a fieldset and added a collapse class to the date field
from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin) |
10be723bf9396c3e513d09ce2a16a3aee0eebe36 | setup.py | setup.py | #!/usr/bin/env python
import os
from distutils.core import setup, Extension, Command
from distutils.command.sdist import sdist
from distutils.command.build_py import build_py
from numpy import get_include as get_numpy_include
numpy_includes = get_numpy_include()
ext_modules = [Extension("reproject._overlap_wrappe... | #!/usr/bin/env python
import os
from distutils.core import setup, Extension, Command
from distutils.command.sdist import sdist
from distutils.command.build_py import build_py
from numpy import get_include as get_numpy_include
numpy_includes = get_numpy_include()
ext_modules = [Extension("reproject._overlap_wrappe... | Make sure the package is built before it is tested | Make sure the package is built before it is tested | Python | bsd-3-clause | barentsen/reproject,mwcraig/reproject,astrofrog/reproject,astrofrog/reproject,bsipocz/reproject,barentsen/reproject,barentsen/reproject,astrofrog/reproject,bsipocz/reproject,mwcraig/reproject | #!/usr/bin/env python
import os
from distutils.core import setup, Extension, Command
from distutils.command.sdist import sdist
from distutils.command.build_py import build_py
from numpy import get_include as get_numpy_include
numpy_includes = get_numpy_include()
ext_modules = [Extension("reproject._overlap_wrappe... | Make sure the package is built before it is tested
#!/usr/bin/env python
import os
from distutils.core import setup, Extension, Command
from distutils.command.sdist import sdist
from distutils.command.build_py import build_py
from numpy import get_include as get_numpy_include
numpy_includes = get_numpy_include()
... |
6c8638c6e5801701d598509bb95036837ccd4a02 | setup.py | setup.py | import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='lazar.michael22@gm... | import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='... | Fix if encoding is not utf-8 | Fix if encoding is not utf-8
| Python | unlicense | michael-lazar/mailcap_fix | import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='... | Fix if encoding is not utf-8
import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
au... |
664ad090e7b4c2922b5c89932e61d7ddef326da9 | script/get_matrices.py | script/get_matrices.py | import sys
from HTMLParser import HTMLParser
class MyHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.state = 'NONE'
def handle_starttag(self, tag, attrs):
if self.state == 'FINISHED':
return
if tag == '<table>':
self.state = 'PA... | Add a simple python to fetch matrices from UoF collection. | Add a simple python to fetch matrices from UoF collection.
| Python | mit | caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask | import sys
from HTMLParser import HTMLParser
class MyHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.state = 'NONE'
def handle_starttag(self, tag, attrs):
if self.state == 'FINISHED':
return
if tag == '<table>':
self.state = 'PA... | Add a simple python to fetch matrices from UoF collection.
| |
0418027b186f146ff75170ecf5c8e63c3dab3cc1 | treeherder/client/setup.py | treeherder/client/setup.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.1'
setup(name='treeherder-client',
version=version,
description=... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.1'
setup(name='treeherder-client',
version=version,
description=... | Add various classifications for pypi | Add various classifications for pypi
| Python | mpl-2.0 | rail/treeherder,glenn124f/treeherder,parkouss/treeherder,tojon/treeherder,adusca/treeherder,akhileshpillai/treeherder,glenn124f/treeherder,adusca/treeherder,avih/treeherder,wlach/treeherder,moijes12/treeherder,akhileshpillai/treeherder,avih/treeherder,vaishalitekale/treeherder,vaishalitekale/treeherder,rail/treeherder,... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.1'
setup(name='treeherder-client',
version=version,
description=... | Add various classifications for pypi
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
version = '1.1'
setup(name='treeherder-client',
... |
2eeab9e35badba0c271b1d1671f08347a5c5e06e | penchy/tests/test_elements.py | penchy/tests/test_elements.py | import unittest2
from penchy.tests.util import MockPipelineElement
class PipelineElementHookTest(unittest2.TestCase):
def setUp(self):
self.e = MockPipelineElement()
self.list_ = [23, 42, 5]
def test_pre_hooks(self):
self.e.prehooks = [
lambda: self.list_.__setitem__(0, 1... | Add test for PipelineElement hooks. | tests: Add test for PipelineElement hooks.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy | import unittest2
from penchy.tests.util import MockPipelineElement
class PipelineElementHookTest(unittest2.TestCase):
def setUp(self):
self.e = MockPipelineElement()
self.list_ = [23, 42, 5]
def test_pre_hooks(self):
self.e.prehooks = [
lambda: self.list_.__setitem__(0, 1... | tests: Add test for PipelineElement hooks.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| |
e421a3cfd9ecfe05aa21b2b3da792f7ab824727d | experimental/db/remove_property.py | experimental/db/remove_property.py | """ Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando): pass
def remove(namespace, field):... | """ Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando): pass
def remove(namespace, field):... | Fix datastore delete field script. | Fix datastore delete field script.
| Python | mit | tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation | """ Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando): pass
def remove(namespace, field):... | Fix datastore delete field script.
""" Remove a property from the datastore.
How to use:
$ cd experimental/db/
$ PYTHONPATH=. remote_api_shell.py -s homeawesomation.appspot.com
> import remove_property
"""
from google.appengine.api import namespace_manager
from google.appengine.ext import db
class Base(db.Expando):... |
13ba81df82f2c43838066ec9cd0fa1222324349f | srsly/util.py | srsly/util.py | # coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
def force_path(location, require_exists=True):
if not isinstance(location, Path):
location = Path(location)
if require_exists and not location.exists():
raise ValueError("Can't read file: {}".format(loc... | # coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
is_python2 = sys.version_info[0] == 2
is_python3 = sys.version_info[0] == 3
if is_python2:
basestring_ = basestring # noqa: F821
else:
basestring_ = str
def force_path(location, require_exists=True):
if not isi... | Improve compat handling in force_string | Improve compat handling in force_string
If we know we already have a string, no need to force it into a strinbg
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly | # coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
is_python2 = sys.version_info[0] == 2
is_python3 = sys.version_info[0] == 3
if is_python2:
basestring_ = basestring # noqa: F821
else:
basestring_ = str
def force_path(location, require_exists=True):
if not isi... | Improve compat handling in force_string
If we know we already have a string, no need to force it into a strinbg
# coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
def force_path(location, require_exists=True):
if not isinstance(location, Path):
location = Path(lo... |
ed09a3ded286cc4d5623c17e65b2d40ef55ccee7 | valohai_yaml/parsing.py | valohai_yaml/parsing.py | from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a stri... | from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a stri... | Handle empty YAML files in parse() | Handle empty YAML files in parse()
Refs valohai/valohai-cli#170
| Python | mit | valohai/valohai-yaml | from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a stri... | Handle empty YAML files in parse()
Refs valohai/valohai-cli#170
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optional... |
e818860af87cad796699e27f8dfb4ff6fc9354e8 | h2o-py/h2o/model/autoencoder.py | h2o-py/h2o/model/autoencoder.py | """
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics)
def anomaly(se... | """
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics)
def anomaly(se... | Add extra argument to get per-feature reconstruction error for anomaly detection from Python. | PUBDEV-2078: Add extra argument to get per-feature reconstruction error for
anomaly detection from Python.
| Python | apache-2.0 | kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,brightchen/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,datachand/h2o-3,kyoren/https-github.com-h2oai-h2o-3,printedheart/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,datacha... | """
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
super(H2OAutoEncoderModel, self).__init__(dest_key, model_json,H2OAutoEncoderModelMetrics)
def anomaly(se... | PUBDEV-2078: Add extra argument to get per-feature reconstruction error for
anomaly detection from Python.
"""
AutoEncoder Models
"""
from model_base import *
from metrics_base import *
class H2OAutoEncoderModel(ModelBase):
"""
Class for AutoEncoder models.
"""
def __init__(self, dest_key, model_json):
... |
dda88345334985796dac2095f6e78bb106bc19b3 | pullpush/pullpush.py | pullpush/pullpush.py | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(se... | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(se... | Check of repo was pulled | Check of repo was pulled
| Python | mit | martialblog/git-pullpush | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(se... | Check of repo was pulled
#!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
se... |
518f9bff28585aa1eeb12b9b12d95e32fb257725 | src/district_distance.py | src/district_distance.py |
# coding: utf-8
# In[79]:
import math
import operator
import json
from geopy.distance import great_circle
# In[90]:
class Order_districts():
def get_district_info():
# -- get names and coordinates from csv file
with open('coordinates.json') as coord_file:
district_dict = j... | Return the districts name by distance given coordinates | Return the districts name by distance given coordinates
| Python | apache-2.0 | ldolberg/the_port_ors_hdx,ldolberg/the_port_ors_hdx |
# coding: utf-8
# In[79]:
import math
import operator
import json
from geopy.distance import great_circle
# In[90]:
class Order_districts():
def get_district_info():
# -- get names and coordinates from csv file
with open('coordinates.json') as coord_file:
district_dict = j... | Return the districts name by distance given coordinates
| |
ba2f2d7e53f0ffc58c882d78f1b8bc9a468eb164 | predicates.py | predicates.py | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class... | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(memb... | Fix problem rendering oneof() predicate when the members aren't strings | Fix problem rendering oneof() predicate when the members aren't strings
| Python | mit | mrozekma/pytypecheck | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(memb... | Fix problem rendering oneof() predicate when the members aren't strings
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ',... |
79460959472f44abaed3d03689f9d397a77399c7 | apps/careeropportunity/forms.py | apps/careeropportunity/forms.py | from django import forms
from apps.careeropportunity.models import CareerOpportunity
class AddCareerOpportunityForm(forms.ModelForm):
description = forms.CharField(label='Beskrivelse', required=True, widget=forms.Textarea(
attrs={'placeholder': 'Detaljert beskrivelse av karrieremuligheten'}))
ingress... | from django import forms
from apps.careeropportunity.models import CareerOpportunity
class AddCareerOpportunityForm(forms.ModelForm):
title = forms.CharField(label='Tittel', required=True, widget=forms.TextInput(
attrs={'placeholder': 'Tittel for karrieremuligheten'}))
ingress = forms.CharField(labe... | Add inputfields for new attributes on careeropportunities and placeholdertext | Add inputfields for new attributes on careeropportunities and placeholdertext
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 | from django import forms
from apps.careeropportunity.models import CareerOpportunity
class AddCareerOpportunityForm(forms.ModelForm):
title = forms.CharField(label='Tittel', required=True, widget=forms.TextInput(
attrs={'placeholder': 'Tittel for karrieremuligheten'}))
ingress = forms.CharField(labe... | Add inputfields for new attributes on careeropportunities and placeholdertext
from django import forms
from apps.careeropportunity.models import CareerOpportunity
class AddCareerOpportunityForm(forms.ModelForm):
description = forms.CharField(label='Beskrivelse', required=True, widget=forms.Textarea(
att... |
1ed040f9d64e12adf964e9f86cc1e18bd8d21593 | scripts/rename.py | scripts/rename.py | import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logger = logging.getLogger(__name__)
def rename(source, target, dry=True):
asser... | import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logger = logging.getLogger(__name__)
def rename(source, target, dry=True):
asser... | Stop cassandra from deleting documents, delete documents from old index as well | Stop cassandra from deleting documents, delete documents from old index as well
| Python | apache-2.0 | erinspace/scrapi,mehanig/scrapi,alexgarciac/scrapi,felliott/scrapi,fabianvf/scrapi,icereval/scrapi,jeffreyliu3230/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,ostwald/scrapi,fabianvf/scrapi,felliott/scrapi | import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logger = logging.getLogger(__name__)
def rename(source, target, dry=True):
asser... | Stop cassandra from deleting documents, delete documents from old index as well
import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logge... |
7f1f001802ffdf4a53e17b120e65af3ef9d1d2da | openfisca_france/conf/cache_blacklist.py | openfisca_france/conf/cache_blacklist.py | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logemen... | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logemen... | Add new variable to cache blacklist | Add new variable to cache blacklist
| Python | agpl-3.0 | sgmap/openfisca-france,antoinearnoud/openfisca-france,antoinearnoud/openfisca-france,sgmap/openfisca-france | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logemen... | Add new variable to cache blacklist
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide... |
82a00e48492f2d787c980c434d58e249c210818e | ffmpeg/_probe.py | ffmpeg/_probe.py | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exi... | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns ... | Add optional timeout argument to probe | Add optional timeout argument to probe
Popen.communicate() supports a timeout argument which is useful in case
there is a risk that the probe hangs.
| Python | apache-2.0 | kkroening/ffmpeg-python | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns ... | Add optional timeout argument to probe
Popen.communicate() supports a timeout argument which is useful in case
there is a risk that the probe hangs.
import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffpr... |
e11b3c344b52c84b5e86bdc381df2f359fe63dae | fparser/setup.py | fparser/setup.py |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
return config
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
config.add_data_files('log.config')
return config
| Add log.config to data files to fix installed fparser. | Add log.config to data files to fix installed fparser.
| Python | bsd-3-clause | dagss/f2py-g3,dagss/f2py-g3 |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
config.add_data_files('log.config')
return config
| Add log.config to data files to fix installed fparser.
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
return config
|
af4c6d9747197b23014ba71803da792f9e612a12 | django_mailbox/migrations/0004_bytestring_to_unicode.py | django_mailbox/migrations/0004_bytestring_to_unicode.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('django_mailbox', '0003_auto_20150409_0316'),
]
operations = [
migrations.AlterField(
model_name='message',
... | Add migration to resolve inconsistency between python2 and python3 strings | Add migration to resolve inconsistency between python2 and python3 strings
| Python | mit | Shekharrajak/django-mailbox,coddingtonbear/django-mailbox,ad-m/django-mailbox,leifurhauks/django-mailbox | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('django_mailbox', '0003_auto_20150409_0316'),
]
operations = [
migrations.AlterField(
model_name='message',
... | Add migration to resolve inconsistency between python2 and python3 strings
| |
810961f65c37d27c5e2d99cf102064d0b4e300f3 | project/apiv2/views.py | project/apiv2/views.py | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from bookmarks.m... | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bo... | Use ListCreateAPIView as base class to support bookmark creation | Use ListCreateAPIView as base class to support bookmark creation
| Python | mit | hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bo... | Use ListCreateAPIView as base class to support bookmark creation
from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
from rest_framew... |
29061254e99f8e02e8285c3ebc965866c8c9d378 | testing/chess_engine_fight.py | testing/chess_engine_fight.py | #!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
whil... | #!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
whil... | Check that engine fight files are deleted before test | Check that engine fight files are deleted before test
| Python | mit | MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess | #!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
whil... | Check that engine fight files are deleted before test
#!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './... |
7741968b9d48afc7ac135742774ae911e2611c83 | tests/test_util.py | tests/test_util.py | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | Cover case when seq is oneven | Cover case when seq is oneven
| Python | mit | CodersOfTheNight/verata | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | Cover case when seq is oneven
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60... |
5cdc5755b1a687c9b34bfd575163ac367816f12a | migrations/versions/3961ccb5d884_increase_artifact_name_length.py | migrations/versions/3961ccb5d884_increase_artifact_name_length.py | """increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Create Date: 2015-11-05 15:34:28.189700
"""
# revision identifiers, used by Alembic.
revision = '3961ccb5d884'
down_revision = '1b229c83511d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('artifact... | """increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Create Date: 2015-11-05 15:34:28.189700
"""
# revision identifiers, used by Alembic.
revision = '3961ccb5d884'
down_revision = '1b229c83511d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('artifact... | Fix extend artifact name migration script. | Fix extend artifact name migration script.
Test Plan: ran migration locally and checked table schema
Reviewers: anupc, kylec
Reviewed By: kylec
Subscribers: changesbot
Differential Revision: https://tails.corp.dropbox.com/D151824
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | """increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Create Date: 2015-11-05 15:34:28.189700
"""
# revision identifiers, used by Alembic.
revision = '3961ccb5d884'
down_revision = '1b229c83511d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('artifact... | Fix extend artifact name migration script.
Test Plan: ran migration locally and checked table schema
Reviewers: anupc, kylec
Reviewed By: kylec
Subscribers: changesbot
Differential Revision: https://tails.corp.dropbox.com/D151824
"""increase artifact name length
Revision ID: 3961ccb5d884
Revises: 1b229c83511d
Cr... |
8cac0c660eee774c32b87d2511e4d2eeddf0ffe8 | scripts/slave/chromium/dart_buildbot_run.py | scripts/slave/chromium/dart_buildbot_run.py | #!/usr/bin/env python
# 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.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | #!/usr/bin/env python
# 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.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process. | Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
Additionally, start calling a new script for release builds (there are none yet, but this is what will be used to build the sdk and editor)
TBR=foo
Review URL: https://chromiumcodereview... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | #!/usr/bin/env python
# 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.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
Additionally, start calling a new script for release builds (there are none yet, but this is what will be used to build the sdk and editor)
TBR=foo
Review URL: https://chromiumcodereview... |
67fcadfa8fd3e6c4161ca4756cc65f0db1386c06 | usercustomize.py | usercustomize.py | """ Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages
for Mac framework builds, and... | """ Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages
for Mac framework builds, and... | Add OS X GTK to Python path. | Add OS X GTK to Python path.
| Python | mit | fossilet/dotfiles,fossilet/dotfiles,fossilet/dotfiles | """ Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages
for Mac framework builds, and... | Add OS X GTK to Python path.
""" Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.