commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
2548a0c5e108fa22867c6a0e4f5b06ceba52dac0 | bottery/message.py | bottery/message.py | import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
raw = attr.ib()
@property
de... | import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
ra... | Extend templates dirs on settings.py | Extend templates dirs on settings.py
| Python | mit | rougeth/bottery |
0d73f5d18a927ffebc3fa32180b608f0c96dcdf1 | Exe_04.py | Exe_04.py | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
p... | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
p... | Update exercise of variables and names | Update exercise of variables and names
| Python | mit | Oreder/PythonSelfStudy |
cc51207881be9c76690bcbc1ce14d048ecc71d76 | commweb/cartridge_hook.py | commweb/cartridge_hook.py | from cartridge.shop.checkout import CheckoutError
from cartridge.shop.models import Cart
from commweb.exc import PaymentDeclinedError
from commweb.purchase import Purchase
def cartridge_payment_handler(request, order_form, order):
cart = Cart.objects.from_request(request)
trans_id = 'WFS_%d' % order.id
p... | from cartridge.shop.checkout import CheckoutError
from commweb.exc import PaymentDeclinedError
from commweb.purchase import Purchase
def cartridge_payment_handler(request, order_form, order):
trans_id = 'WFS_%d' % order.id
p = Purchase(order.total, trans_id,
order_form.cleaned_data['card_number']... | Fix bug where shipping wasn't included in payment amount with cartridge handler | Fix bug where shipping wasn't included in payment amount with cartridge handler
| Python | bsd-2-clause | sjkingo/django-commweb |
83cbec4ccf669c997bbe6c7131f63ad08a482c39 | examples/mnist-deepautoencoder.py | examples/mnist-deepautoencoder.py | #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, ... | #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, ('tied', 64), ('tied', 256), ('tied', 784)),
train_batches=100,
)
e.train(... | Update example with newer tied layer specification. | Update example with newer tied layer specification.
| Python | mit | lmjohns3/theanets,chrinide/theanets,devdoer/theanets |
79fd5586625d2d7873bc71514eda121325a9646a | linkedin_scraper/commands/people_search.py | linkedin_scraper/commands/people_search.py | from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
return "[options] <query>"
def add... | from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
from scrapy.exceptions import UsageError
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
... | Fix IndexError when running command without arguments. | Fix IndexError when running command without arguments.
| Python | mit | nihn/linkedin-scraper,nihn/linkedin-scraper |
5dc4a262771e616458feeaa9bf4ca8568736761a | docs/contributors/generate.py | docs/contributors/generate.py | """
Generate snippets to copy-paste.
"""
import sys
from jinja2 import Template
from fetch import HERE, load_awesome_people
TPL_FILE = HERE / 'snippet.jinja2'
HTTPIE_TEAM = {
'BoboTiG',
'claudiatd',
'jakubroztocil',
'jkbr',
}
def generate_snippets(release: str) -> str:
people = load_awesome_peo... | """
Generate snippets to copy-paste.
"""
import sys
from jinja2 import Template
from fetch import HERE, load_awesome_people
TPL_FILE = HERE / 'snippet.jinja2'
HTTPIE_TEAM = {
'claudiatd',
'jakubroztocil',
'jkbr',
}
def generate_snippets(release: str) -> str:
people = load_awesome_people()
contr... | Remove myself from the HTTPie team | Remove myself from the HTTPie team | Python | bsd-3-clause | jakubroztocil/httpie,PKRoma/httpie,jakubroztocil/httpie,jakubroztocil/httpie,PKRoma/httpie |
f16d93216e1f0890b0551ca3b741130bb12781ef | gold_digger/settings/__init__.py | gold_digger/settings/__init__.py | # -*- coding: utf-8 -*-
from os import environ, path
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
profile = environ.get("GOLD_DIGGER_PROFILE", "local")
if profile == "master":
from ._settings_master import *
elif profile == "local":
try:
from ._settings_local import... | # -*- coding: utf-8 -*-
from os import environ, path
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
PROFILE = environ.get("GOLD_DIGGER_PROFILE", "local")
if PROFILE == "master":
from ._settings_master import *
elif PROFILE == "local":
try:
from ._settings_local import... | Make global variable upper-case and use f-strings | Make global variable upper-case and use f-strings
| Python | apache-2.0 | business-factory/gold-digger |
763051db8cb4efe9b3e85fdb3d974674cf435607 | us_ignite/snippets/management/commands/snippets_load_fixtures.py | us_ignite/snippets/management/commands/snippets_load_fixtures.py | from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': ... | from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': ... | Add fixture for the advert in the blog sidebar advert. | Add fixture for the advert in the blog sidebar advert.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
49a371728a2e9167494264e0c07c6dd90abec0ff | saleor/core/views.py | saleor/core/views.py | from django.template.response import TemplateResponse
from ..product.utils import products_with_availability, products_with_details
def home(request):
products = Product.objects.get_available_products()[:6]
products = products.prefetch_related('categories', 'images',
... | from django.template.response import TemplateResponse
from ..product.utils import products_with_availability, products_with_details
def home(request):
products = products_with_details(request.user)[:6]
products = products_with_availability(
products, discounts=request.discounts, local_currency=reques... | Fix homepage after wrong rebase | Fix homepage after wrong rebase
| Python | bsd-3-clause | jreigel/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,mociepka/saleor,car3oon/saleor,KenMutemi/saleor,jreigel/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,itbabu/saleor,UITools/saleor,KenMutemi/saleor,mociepka/saleor,itbabu/saleor,... |
ef7163a18ee1cf11c1290f2a8832d8cf39fb552c | fjord/base/tests/test_commands.py | fjord/base/tests/test_commands.py | from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint... | from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint... | Adjust test_polint to be less stdout-spammy | Adjust test_polint to be less stdout-spammy
| Python | bsd-3-clause | hoosteeno/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,lgp171188/fjord,rlr/fjord,staranjeet/fjord,DESHRAJ/fjord,hoosteeno/fjord,Ritsyy/fjord,rlr/fjord,lgp171188/fjord,DESHRAJ/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,rlr/fjord,Ritsyy/fjord,staranjeet/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,DESHRA... |
c0c822df243894106a7fd376582598e4aebb4c24 | kobo/hub/decorators.py | kobo/hub/decorators.py | # -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authenticated():
... | # -*- coding: utf-8 -*-
import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authentic... | Check worker's FQDN against username. | Check worker's FQDN against username.
| Python | lgpl-2.1 | pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo |
337e7ae58abc7c192633144cc3913078ae3d38bf | hc2002/plugin/symbolic_values.py | hc2002/plugin/symbolic_values.py | import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:')
def apply(instance):
def _r... | import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:')
def apply(instance):
def re... | Fix infinite loop with missing symbol definition | Fix infinite loop with missing symbol definition
The local function _resolve_symbol is renamed for improved tracebacks.
| Python | apache-2.0 | biochimia/hc2000 |
ad766ba20db73ceb433b9afe3b5db3e52cf1494a | addons/sale_stock/models/stock_config_settings.py | addons/sale_stock/models/stock_config_settings.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
security_lead = fields.Float(related='company_id.security_lead')
default_new_security_le... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
security_lead = fields.Float(related='company_id.security_lead')
default_new_security_le... | Make default_picking_policy a required field in settings | [IMP] stock: Make default_picking_policy a required field in settings
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
96dd8312cded04e5f5758495e72238d58905be7b | count.py | count.py | import json
from collections import Counter
from Bio import SeqIO
from Bio.SeqUtils import GC
for seq_record in SeqIO.parse("samples/test.fasta", "fasta"):
cnt = Counter()
line = str(seq_record.seq)
i = 0
for j in range(((len(line))/ 3)):
cnt[line[i:i+3]] += 1
i += 3
print json.dumps(
... | #!/usr/bin/python
import getopt
import json
import sys
from collections import Counter
from Bio import SeqIO
from Bio.SeqUtils import GC
def compute(inputfile):
for seq_record in SeqIO.parse(inputfile, "fasta"):
cnt = Counter()
line = str(seq_record.seq)
i = 0
for j in range(((len(line))/ 3... | Add -i flag for input | Add -i flag for input
| Python | apache-2.0 | PDX-Flamingo/codonpdx-python,PDX-Flamingo/codonpdx-python |
29562b08e436abc8465404e49d9193537721b717 | src/odin/contrib/money/fields.py | src/odin/contrib/money/fields.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from odin import exceptions
from odin.fields import ScalarField
from odin.validators import EMPTY_VALUES
from .datatypes import Amount
__all__ = ('AmountField', )
class AmountField(ScalarField):
"""
Field that contains a monetary ... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from odin import exceptions
from odin.fields import ScalarField
from odin.validators import EMPTY_VALUES
from .datatypes import Amount
__all__ = ("AmountField",)
class AmountField(ScalarField):
"""
Field that contains a monetary a... | Correct issue from Sonar (and black file) | Correct issue from Sonar (and black file)
| Python | bsd-3-clause | python-odin/odin |
6b93f6a6bedf875d4bad1af2493c91b28a625ea9 | chempy/electrochemistry/tests/test_nernst.py | chempy/electrochemistry/tests/test_nernst.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..nernst import nernst_potential
def test_nernst_potential():
# Sodium in cells
assert abs(1000 * nernst_potential(145, 15, 1, 310) - 60.605) < 1e-4
# Potassium in cells
assert abs(1000 * nernst_potential(... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..nernst import nernst_potential
from chempy.util.testing import requires
from chempy.units import default_units, default_constants, units_library
def test_nernst_potential():
"""
Test cases obtained from textbook... | Add additional testing to electrochemistry/Nernst | Add additional testing to electrochemistry/Nernst
| Python | bsd-2-clause | bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/chempy,bjodah/aqchem |
2735d4a7b1ae0af0d58ea0accb973ab11477783e | django_hosts/tests/urls/simple.py | django_hosts/tests/urls/simple.py | from django.conf.urls.defaults import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('django.views.generic.simple',
url(r'^simple/$', TemplateView.as_view(), name='simple-direct'),
)
| from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('django.views.generic.simple',
url(r'^simple/$', 'django.shortcuts.render', name='simple-direct'),
)
| Use django.shortcuts.render instead of TemplateView | Use django.shortcuts.render instead of TemplateView | Python | bsd-3-clause | jezdez/django-hosts |
0ca07405b864f761ae1d7ed659cac67c799bf39a | src/core/queue.py | src/core/queue.py | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
... | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pa... | Move those methods to own class | Move those methods to own class [ci skip]
| Python | mit | le717/ICU |
facfa3bcd7d35163e0504ef4b6f9b3b15e778993 | modeltranslation/management/commands/update_translation_fields.py | modeltranslation/management/commands/update_translation_fields.py | # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help... | # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help... | Revert "Added a workaround for abstract models not being handled correctly." | Revert "Added a workaround for abstract models not being handled correctly."
This reverts commit a3e44c187b5abfa6d9b360cecc5c1daa746134f5.
| Python | bsd-3-clause | marctc/django-modeltranslation,akheron/django-modeltranslation,nanuxbe/django-modeltranslation,marctc/django-modeltranslation,nanuxbe/django-modeltranslation,SideStudios/django-modeltranslation,akheron/django-modeltranslation,yoza/django-modeltranslation,extertioner/django-modeltranslation,extertioner/django-modeltrans... |
ae6ed4e7dc6510637d322eb6403f43b9d4aa5d25 | karteikarten/helpers/exporters.py | karteikarten/helpers/exporters.py | # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | Remove carriage returns in Anki exporter | Remove carriage returns in Anki exporter
| Python | agpl-3.0 | meoblast001/kksystem,meoblast001/kksystem,meoblast001/kksystem |
24d3af9288102e5061c3a1f9e6fe2d7d578f6cc5 | astro.py | astro.py | import ephem
m = getattr(ephem, (raw_input('Planet: ')))
print ephem.constellation(m(raw_input('yyyy/mm/dd: '))) | import ephem
def const(planet_name, date_string): # function name and parameters
planet_class = getattr(ephem, planet_name) # sets ephem object class
planet = planet_class() # sets planet variable
south_bend = ephem.Observer() # Creates the Observer object
... | Select planet and display alt/az data | Select planet and display alt/az data
Created a function localized to South Bend, IN, to display altitude and
azimuth data for a planet selected.
| Python | mit | bennettscience/PySky |
071926edc64241b0359c9a0148fc0825a09cb6ba | marionette/__init__.py | marionette/__init__.py |
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
@classmethod
def as_view(cls):
... |
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
@classmethod
def as_view(cls):
... | Add execute hook to allow wrapping handler calls | Add execute hook to allow wrapping handler calls
| Python | mit | funkybob/django-marionette |
6f947c99411692f8fe4899203ed9bf202b0412a3 | cihai/__about__.py | cihai/__about__.py | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'... | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__docs__ = 'https://cihai.git-pull.com'
__tracker__ = 'https://g... | Add tracker and doc URL to metadata | Add tracker and doc URL to metadata
| Python | mit | cihai/cihai,cihai/cihai |
d6ddc3b41040a374c61d4624e052fa8f1e58ee37 | metakernel/__init__.py | metakernel/__init__.py | from .metakernel import MetaKernel
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, metakernel, parser, process_metakernel
| from .metakernel import MetaKernel
import .pyexpect
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, metakernel, parser, process_metakernel, pyexpect
| Fix import error in Python 2 | Fix import error in Python 2
| Python | bsd-3-clause | Calysto/metakernel |
ec9239fda210f3d71a81045fdba9d72bab04a05b | indra/sources/drugbank/__init__.py | indra/sources/drugbank/__init__.py | """This module provides an API and processor for DrugBank content.
It builds on the XML-formatted data schema of DrugBank and expects
the XML file to be available locally. The full DrugBank download
can be obtained at: https://www.drugbank.ca/releases/latest. Once the
XML file is decompressed, it can be processed using... | """This module provides an API and processor for DrugBank content.
It builds on the XML-formatted data schema of DrugBank and expects
the XML file to be available locally. The full DrugBank download
can be obtained at: https://www.drugbank.ca/releases/latest. Once the
XML file is decompressed, it can be processed using... | Add more docs on how to get drugbank quickly | Add more docs on how to get drugbank quickly
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra |
922db591ca726acae07e2628119b95aa705f414c | leetcode/ds_string_word_pattern.py | leetcode/ds_string_word_pattern.py |
# @file Word Pattern
# @brief Given 2 sets check if it is a bijection
# https://leetcode.com/problems/word-pattern/
'''
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty word in str.
Exa... |
# @file Word Pattern
# @brief Given 2 sets check if it is a bijection
# https://leetcode.com/problems/word-pattern/
'''
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty word in str.
Exa... | Add two approaches for string word pattern | Add two approaches for string word pattern | Python | mit | ngovindaraj/Python |
c1f270700d9de209577b64c40b71b5f5b69c5aae | cards.py | cards.py | from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
s... | from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
s... | Refactor create_card method to take a list of card dictionaries. Rename method accordingly. | Refactor create_card method to take a list of card dictionaries. Rename method accordingly.
| Python | isc | wwu-nosql/cards |
f70b2a187c274685cb19def1b48256822b0e3f9f | tests/conftest.py | tests/conftest.py | import py
import pytest
from tests.lib.path import Path
@pytest.fixture
def tmpdir(request):
"""
Return a temporary directory path object which is unique to each test
function invocation, created as a sub directory of the base temporary
directory. The returned object is a ``tests.lib.path.Path`` obje... | import py
import pytest
from tests.lib.path import Path
from tests.lib.scripttest import PipTestEnvironment
from tests.lib.venv import VirtualEnvironment
@pytest.fixture
def tmpdir(request):
"""
Return a temporary directory path object which is unique to each test
function invocation, created as a sub di... | Use our classes from tests.lib.* in pytest fixtures | Use our classes from tests.lib.* in pytest fixtures
| Python | mit | KarelJakubec/pip,qbdsoft/pip,alquerci/pip,nthall/pip,dstufft/pip,nthall/pip,esc/pip,blarghmatey/pip,chaoallsome/pip,wkeyword/pip,alex/pip,jmagnusson/pip,James-Firth/pip,msabramo/pip,atdaemon/pip,natefoo/pip,rouge8/pip,h4ck3rm1k3/pip,zvezdan/pip,haridsv/pip,rbtcollins/pip,Ivoz/pip,luzfcb/pip,harrisonfeng/pip,willingc/pi... |
ff3123e21e366a5908655dbd8130ac60ec5eee10 | uvt_user/utils.py | uvt_user/utils.py | from __future__ import unicode_literals
import re
from ldap3 import Server, Connection
class LDAPError(Exception):
pass
def search_ldap(username):
'''Searches the Tilburg University LDAP server for the given username and returns a tuple of first name, last name, full name, ANR, emplId and email address. Perm... | from __future__ import unicode_literals
import re
from ldap3 import Server, Connection
class LDAPError(Exception):
pass
def search_ldap(username):
'''Searches the Tilburg University LDAP server for the given username and returns a tuple of first name, last name, full name, ANR, emplId and email address. Perm... | Fix potential bug in case LDAP does not return lists | Fix potential bug in case LDAP does not return lists
| Python | agpl-3.0 | JaapJoris/bps,JaapJoris/bps |
a7622fc3d996407799cec166968c1e56baf07ea9 | wqflask/wqflask/markdown_routes.py | wqflask/wqflask/markdown_routes.py | """Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
@glossary_blueprint.route('/')
def glossary():
markdown... | """Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import os
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
def render_markdown(file_name):
"""Try to fet... | Move logic for fetching md files to it's own function | Move logic for fetching md files to it's own function
* wqflask/wqflask/markdown_routes.py
(render_markdown): New function.
(glossary): use render_markdown function.
| Python | agpl-3.0 | genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2 |
1abfdea38e868d68c532961459d2b4cbef5a9b71 | src/zeit/website/section.py | src/zeit/website/section.py | import zeit.website.interfaces
from zeit.cms.section.interfaces import ISectionMarker
import grokcore.component as grok
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zope.interface
@grok.subscribe(
zeit.cms.content.interfaces.ICommonMetadata,
zeit.cms.checkout.interfaces.IBefor... | import zeit.website.interfaces
from zeit.cms.section.interfaces import ISectionMarker
import grokcore.component as grok
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zope.interface
@grok.subscribe(
zeit.cms.content.interfaces.ICommonMetadata,
zeit.cms.checkout.interfaces.IBefor... | Remove iface, if rebrush_contetn ist not set | Remove iface, if rebrush_contetn ist not set
| Python | bsd-3-clause | ZeitOnline/zeit.website |
533d6294a47a4a974dfda1743e9fcd6146ede27f | codonpdx/insert.py | codonpdx/insert.py | #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
if args.json:
data = json.loads(args.json)
else:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
db.... | #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
if hasattr(args, 'json'):
data = json.loads(args.json)
else:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
... | Fix testing for JSON parameter existence. | Fix testing for JSON parameter existence.
| Python | apache-2.0 | PDX-Flamingo/codonpdx-python,PDX-Flamingo/codonpdx-python |
215c6d714df53f6f52f2bf819f2a01f1c1eab294 | learntris.py | learntris.py | #!/usr/bin/env python
import sys
class Grid(object):
def __init__(self):
self.board = ['. '*10 for row in range(0,22)]
self.score = 0
self.lines_clear = 0
def draw_board(self):
for cell in self.board:
print cell
def given(self):
self.board = []
... | #!/usr/bin/env python
import sys
class Grid(object):
def __init__(self):
self.board = [[None] * 10 for i in range(22)]
self.score = 0
self.lines_clear = 0
def draw_board(self):
current_board = self.board
for row in current_board:
row = map(lambda... | Change data structure to multidimensional array Now passing Test 2 | Change data structure to multidimensional array
Now passing Test 2
| Python | mit | mosegontar/learntris |
ba745d03c11d7478c4da5a68246ec9d461077365 | experiments/rnnencdec/__init__.py | experiments/rnnencdec/__init__.py | from encdec import RNNEncoderDecoder
from encdec import get_batch_iterator
from encdec import parse_input
from encdec import create_padded_batch
from state import prototype_state
from state import prototype_search_state
from state import prototype_sentence_state
from state import prototype_autoenc_state
from state imp... | from encdec import RNNEncoderDecoder
from encdec import get_batch_iterator
from encdec import parse_input
from encdec import create_padded_batch
from state import prototype_state
from state import prototype_search_state
from state import prototype_sentence_state
| Remove states that do not exist anymore | Remove states that do not exist anymore
| Python | bsd-3-clause | sebastien-j/LV_groundhog,ZenDevelopmentSystems/GroundHog,kyunghyuncho/GroundHog,dmitriy-serdyuk/EncDecASR,OlafLee/LV_groundhog,ZenDevelopmentSystems/GroundHog,sebastien-j/LV_groundhog,lisa-groundhog/GroundHog,vseledkin/LV_groundhog,vseledkin/LV_groundhog,zerkh/GroundHog,hezhenghao/GroundHog,zerkh/GroundHog,OlafLee/LV_g... |
befe47c35c68e17231e21febbf52041f245b8985 | django_mailer/managers.py | django_mailer/managers.py | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)... | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)... | Update the retries count of a queued message when it is changed back from deferred | Update the retries count of a queued message when it is changed back from deferred
| Python | mit | APSL/django-mailer-2,Giftovus/django-mailer-2,davidmarble/django-mailer-2,SmileyChris/django-mailer-2,kvh/django-mailer-2,maykinmedia/django-mailer-2,PSyton/django-mailer-2,APSL/django-mailer-2,colinhowe/django-mailer-2,rofrankel/django-mailer-2,maykinmedia/django-mailer-2,APSL/django-mailer-2,GreenLightGo/django-maile... |
53a38a716c01cfd15bc1aff89c6c7908a5218bfb | integration_tests/experiment_type.py | integration_tests/experiment_type.py | from enum import unique, IntEnum
@unique
class ExperimentType(IntEnum):
Detumbling = 1
EraseFlash = 2
SunS = 3
LEOP = 4
RadFET = 5
SADS = 6
Sail = 7
Fibo = 8
Payload = 9
Camera = 10
@unique
class StartResult(IntEnum):
Success = 0
Failure = 1
@unique
class IterationR... | from enum import unique, IntEnum
@unique
class ExperimentType(IntEnum):
Detumbling = 1
EraseFlash = 2
SunS = 3
LEOP = 4
RadFET = 5
SADS = 6
Sail = 7
Fibo = 8
Payload = 9
Camera = 10
@unique
class StartResult(IntEnum):
Success = 0
Failure = 1
@unique
class IterationR... | Fix python projection of experiment iteration result enumeration. | Fix python projection of experiment iteration result enumeration.
| Python | agpl-3.0 | PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC |
31212104810f6c700ccc9561ac3d355b1894ef47 | glimpse/__init__.py | glimpse/__init__.py | """
Hierarchical visual models in C++ and Python
============================================
The Glimpse project is a library for implementing hierarchical visual models
in C++ and Python. The goal of this project is to allow a broad range of
feed-forward, hierarchical models to be encoded in a high-level declarative... | """
Hierarchical visual models in C++ and Python
============================================
The Glimpse project is a library for implementing hierarchical visual models
in C++ and Python. The goal of this project is to allow a broad range of
feed-forward, hierarchical models to be encoded in a high-level declarative... | Fix PIL bug on OS X. | Fix PIL bug on OS X.
| Python | mit | mthomure/glimpse-project,mthomure/glimpse-project,mthomure/glimpse-project |
bf7f726821f2ac74e99fd5fd06729ea2becab0c9 | ModuleInterface.py | ModuleInterface.py | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Comma... | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Comma... | Return false if no alias. | [ModuleInteface] Return false if no alias.
| Python | mit | HubbeKing/Hubbot_Twisted |
bdc51bb7a71dba4a25fcded0d2758a9af5e15679 | pythran/tests/test_doc.py | pythran/tests/test_doc.py | import unittest
import doctest
class TestDoctest(unittest.TestCase):
modules = ('passes',)
def test_package(self):
import pythran
failed, _ = doctest.testmod(pythran)
self.assertEqual(failed, 0)
def test_passes(self):
from pythran import passes
failed, _ = doctest... | import unittest
import doctest
import pythran
import inspect
class TestDoctest(unittest.TestCase):
'''
Enable automatic doctest integration to unittest
Every module in the pythran package is scanned for doctests
and one test per module is created
'''
pass
def generic_test_package(self, mod):
... | Make doctest integration in unittest generic. | Make doctest integration in unittest generic.
Rely on introspection rather than redundant typing.
| Python | bsd-3-clause | pbrunet/pythran,artas360/pythran,pbrunet/pythran,pbrunet/pythran,serge-sans-paille/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,hainm/pythran,pombredanne/pythran,pombredanne/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran |
0e2275c0d2623a7ec62e7109d3ffdd859118ed9d | external_tools/src/main/python/images/move_corrupt_images.py | external_tools/src/main/python/images/move_corrupt_images.py | """
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
... | """
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
... | Use os.rename instead of os.path in moving dirs | Use os.rename instead of os.path in moving dirs
| Python | apache-2.0 | mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData |
4b193d9f0c46f91c5a58446e6443d8779e7ca5ce | server/plugins/ardinfo/scripts/ard_info.py | server/plugins/ardinfo/scripts/ard_info.py | #!/usr/bin/python
import os
import sys
sys.path.append("/usr/local/munki/munkilib")
import FoundationPlist
sys.path.append("/usr/local/sal")
import utils
def main():
ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist"
if os.path.exists(ard_path):
ard_prefs = FoundationPlist.readPlist(ar... | #!/usr/bin/python
import os
import sys
sys.path.append("/usr/local/munki")
from munkilib import FoundationPlist
sys.path.append("/usr/local/sal")
import utils
def main():
ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist"
if os.path.exists(ard_path):
ard_prefs = FoundationPlist.readPli... | Fix name clash over "utils" in ardinfo plugin script. | Fix name clash over "utils" in ardinfo plugin script.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal |
5bbd288c40e3a2bc1ee791545d704452699334f3 | cr8/aio.py | cr8/aio.py |
from tqdm import tqdm
import asyncio
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
async def map_async(q, corof, iterable):
for i in iterable:
task = asyncio.ensure_future(corof(*i))
await q.put(task)
await q.join()
await q... |
from tqdm import tqdm
import asyncio
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
async def map_async(q, corof, iterable):
for i in iterable:
task = asyncio.ensure_future(corof(*i))
await q.put(task)
await q.put(None)
async ... | Remove q.join() / task_done() usage | Remove q.join() / task_done() usage
Don't have to block producer anymore - it will wait for the consumer to
finish anyway
| Python | mit | mikethebeer/cr8,mfussenegger/cr8 |
7698ec18abd25ed41b3104a382e7d8ca38d755ca | tests/unit/test_describe.py | tests/unit/test_describe.py | import pytest
from mock import Mock
from formica import cli
from tests.unit.constants import STACK
def test_describes_change_set(boto_client, change_set):
cli.main(['describe', '--stack', STACK])
boto_client.assert_called_with('cloudformation')
change_set.assert_called_with(stack=STACK)
change_set.re... | import pytest
from mock import Mock
from formica import cli
from tests.unit.constants import STACK
def test_describes_change_set(boto_client, change_set):
cli.main(['describe', '--stack', STACK])
change_set.assert_called_with(stack=STACK)
change_set.return_value.describe.assert_called_once()
| Remove Assert Call not necessary anymore | Remove Assert Call not necessary anymore
| Python | mit | flomotlik/formica |
d6b3f4e0798f430761f51529ea61c368e1ce610a | utest/contrib/testrunner/test_pybot_arguments_validation.py | utest/contrib/testrunner/test_pybot_arguments_validation.py | import unittest
import robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_... | import unittest
import robotide.lib.robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
... | Fix unit test for when robotframework is not installed. | Fix unit test for when robotframework is not installed.
| Python | apache-2.0 | HelioGuilherme66/RIDE,robotframework/RIDE,robotframework/RIDE,HelioGuilherme66/RIDE,HelioGuilherme66/RIDE,robotframework/RIDE,HelioGuilherme66/RIDE,robotframework/RIDE |
45275a48fb434e6a9d895da03e290b84c52694f6 | orbitdeterminator/kep_determination/least_squares.py | orbitdeterminator/kep_determination/least_squares.py | """Computes the least-squares optimal Keplerian elements for a sequence of
cartesian position observations.
"""
import numpy as np
import matplotlib.pyplot as plt
# convention:
# a: semi-major axis
# e: eccentricity
# eps: mean longitude at epoch
# Euler angles:
# I: inclination
# Omega: longitude of ascending nod... | """Computes the least-squares optimal Keplerian elements for a sequence of
cartesian position observations.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
# convention:
# a: semi-major axis
# e: eccentricity
# eps: mean longitude at epoch
# Euler angles:
# I: inclination
# Omega: longitude of a... | Add rotation matrix, from orbital plane to inertial frame | Add rotation matrix, from orbital plane to inertial frame
| Python | mit | aerospaceresearch/orbitdeterminator |
e5a7c7a7c163047f35af6f6f06fa58ca71757aa2 | ExposedAccessKeys/lambda_functions/delete_access_key_pair.py | ExposedAccessKeys/lambda_functions/delete_access_key_pair.py | import boto3
iam = boto3.client('iam')
def lambda_handler(event, context):
details = event['check-item-detail']
username = details['User Name (IAM or Root)']
access_key_id = details['Access Key ID']
exposed_location = details['Location']
print('Deleting exposed access key pair...')
delete_exp... | import boto3
iam = boto3.client('iam')
def lambda_handler(event, context):
details = event['detail']['check-item-detail']
username = details['User Name (IAM or Root)']
access_key_id = details['Access Key ID']
exposed_location = details['Location']
print('Deleting exposed access key pair...')
... | Fix event detail variable key lookup | Fix event detail variable key lookup
| Python | apache-2.0 | robperc/Trusted-Advisor-Tools,robperc/Trusted-Advisor-Tools |
4fb54ac1b06f368d788526a7400c377c715f594c | epf.py | epf.py | from __future__ import division # for Python 2.x compatibility
import numpy
class EuclidField(object):
p = 5.0
r = 30.0
@staticmethod
def dist(x, y):
return numpy.hypot(x[0]-y[0], x[1]-y[1])
def __init__(self, size, dst, obstacles):
w, h = size
self.shape = (h, w)
se... | from __future__ import division # for Python 2.x compatibility
import numpy
class EuclidField(object):
p = 5.0
r = 30.0
@staticmethod
def dist(x, y):
return numpy.hypot(x[0]-y[0], x[1]-y[1])
def __init__(self, size, dst, obstacles):
w, h = size
self.shape = (h, w)
se... | Remove a line of debugging code | Remove a line of debugging code
| Python | bsd-2-clause | z-rui/pf |
ff39d53b3892477ac7fa690471afbd3099cbd5bd | modules/urlparser/__init__.py | modules/urlparser/__init__.py | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible... | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible... | Change urlparser to use reply | Change urlparser to use reply
| Python | mit | billyvg/piebot |
309fcf2b4a429396016716545a9982cf62a2a089 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.extension import Extension
#from Cython.Distutils import build_ext
import numpy
from numpy.distutils.system_info import get_info
mpfit_sources = [
'mpyfit/mpyfit.c',
'mpyfit/cmpfit/mpfit.c',
]
# Avoid some numpy warn... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.core import Extension
#from Cython.Distutils import build_ext
import numpy
from numpy.distutils.system_info import get_info
mpfit_sources = [
'mpyfit/mpyfit.c',
'mpyfit/cmpfit/mpfit.c',
]
# Avoid some numpy warnings,... | Fix for Python 3.4 extension compilation. | Fix for Python 3.4 extension compilation.
An extra extension compilation option introduced in Python 3.4 collided with
-std=c99; added -Wno-declaration-after-statement negates this.
| Python | bsd-2-clause | evertrol/mpyfit,evertrol/mpyfit |
5eabea682317fe53d89fcf1b2ec98a1f44de51d3 | rt/syslog/simpleConfig.py | rt/syslog/simpleConfig.py | # capture executables on all nodes
hostname_patterns = [
['KEEP', '.*']
]
path_patterns = [
['PKGS', r'.*\/test_record_pkg'],
['SKIP', r'.*\/lua'],
['SKIP', r'.*\/expr'],
['SKIP', r'.*\/cc1'],
['SKIP', r'.*\/bash'],
['SKIP', r'.*\/collect2'],
['SKIP', r'.*\/mpich/.*'],
['SKIP', r'.*\/x86_64-linux-gnu... | # capture executables on all nodes
hostname_patterns = [
['KEEP', '.*']
]
path_patterns = [
['PKGS', r'.*\/test_record_pkg'],
['PKGS', r'.*\/python[0-9][^/][^/]*'],
['SKIP', r'.*\/lua'],
['SKIP', r'.*\/expr'],
['SKIP', r'.*\/cc1'],
['SKIP', r'.*\/bash'],
['SKIP', r'.*\/collect2'],
['SKIP', r'.*\/mpich... | Add in python patterns for py pkg test | Add in python patterns for py pkg test
| Python | lgpl-2.1 | xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt,xalt/xalt |
079240a28c648a56fd30cbf3b0b4115a7f2259bc | example.py | example.py | import requests
ACCOUNT_SID = None
AUTH_TOKEN = None
FROM_NUMBER = None
response = requests.post(
'https://{account_sid}:{auth_token}@api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages'.format(
account_sid=ACCOUNT_SID,
auth_token=AUTH_TOKEN,
),
data={'From': FROM_NUMBER,
'... | import requests
ACCOUNT_SID = None
AUTH_TOKEN = None
FROM_NUMBER = None
# Send text message
response = requests.post(
'https://{account_sid}:{auth_token}@api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json'.format(
account_sid=ACCOUNT_SID,
auth_token=AUTH_TOKEN,
),
data={'From':... | Add get message details code. | Add get message details code.
| Python | mit | richardxia/twilio-tutorial |
88be5325c3d006b822c8d8ee2db4512ea538c800 | rapidsms/views.py | rapidsms/views.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login as django_login
from django.contrib.auth.views import logout as django_logout
from django.shortcuts import render_to_response
from django.template import RequestConte... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login as django_login
from django.contrib.auth.views import logout as django_logout
from django.shortcuts import render
from django.template import RequestContext
from djan... | Use render, rather than render_to_response | Use render, rather than render_to_response
| Python | bsd-3-clause | lsgunth/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms |
41bdb951e61f5601c380fd81690d74d35136455f | django_evolution/builtin_evolutions/__init__.py | django_evolution/builtin_evolutions/__init__.py | from django.contrib.sessions.models import Session
BUILTIN_SEQUENCES = {
'django.contrib.auth': [],
'django.contrib.contenttypes': [],
'django.contrib.sessions': [],
}
# Starting in Django 1.3 alpha, Session.expire_date has a db_index set.
# This needs to be reflected in the evolutions. Rather than hard... | from django.contrib.sessions.models import Session
BUILTIN_SEQUENCES = {
'django.contrib.auth': [],
'django.contrib.contenttypes': [],
'django.contrib.sessions': [],
}
# Starting in Django 1.3 alpha, Session.expire_date has a db_index set.
# This needs to be reflected in the evolutions. Rather than hard... | Fix a field lookup to be compatible with all versions of Django. | Fix a field lookup to be compatible with all versions of Django.
Recent versions of Django removed Meta.get_field_by_name(), which our
built-in evolutions were trying to use. Fortunately, all supported
versions have Meta.get_field(), which works just as well. This change
switches over to that.
We'll want to revisit t... | Python | bsd-3-clause | beanbaginc/django-evolution |
54683555997032cccf97f5fedf88b7a2402f0449 | sponsorship_tracking/migrations/10.0.2.0.0/post-migration.py | sponsorship_tracking/migrations/10.0.2.0.0/post-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | FIX only sponsorships can go through waiting_welcome state | FIX only sponsorships can go through waiting_welcome state
| Python | agpl-3.0 | eicher31/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,maxime-beck/compassion-modules,eicher31/compassion-modules,maxime-beck/compassion-modules,maxime-beck/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,Comp... |
e9c6b22ffaf498dc64f590689cc637a152444665 | forms.py | forms.py | from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newco... | from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newco... | Change LoginForm parameter for BooleanField | Change LoginForm parameter for BooleanField
| Python | mit | jinjiaho/project57,jinjiaho/project57,jinjiaho/project57,jinjiaho/project57 |
4af8f60598e216adb04e4ed04394e8835beedcac | src/som/vmobjects/object_without_fields.py | src/som/vmobjects/object_without_fields.py | from rlib.jit import promote
from som.vmobjects.abstract_object import AbstractObject
class ObjectWithoutFields(AbstractObject):
_immutable_fields_ = ["_object_layout?"]
def __init__(self, layout): # pylint: disable=W
self._object_layout = layout
def get_class(self, universe):
assert ... | from rlib.jit import promote
from som.vmobjects.abstract_object import AbstractObject
class ObjectWithoutFields(AbstractObject):
_immutable_fields_ = ["_object_layout?"]
def __init__(self, layout): # pylint: disable=W
self._object_layout = layout
def get_class(self, universe):
assert ... | Improve ObjectWithoutField.__str__ to idenfify singleton values | Improve ObjectWithoutField.__str__ to idenfify singleton values
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
| Python | mit | smarr/PySOM,smarr/PySOM,SOM-st/PySOM,SOM-st/PySOM |
eec47f7a6988d4472bc99789fcc7ba894b74c17b | files/install_workflow.py | files/install_workflow.py | #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file'... | #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file... | Use .get methods when retrieving uuid keys | Use .get methods when retrieving uuid keys
| Python | mit | anmoljh/ansible-galaxy-tools,galaxyproject/ansible-galaxy-tools,galaxyproject/ansible-tools,nuwang/ansible-galaxy-tools |
a3a2ad5099663bb92a04db41e531c776b9e02d41 | dxtbx/tst_dxtbx.py | dxtbx/tst_dxtbx.py | def tst_dxtbx():
import libtbx.load_env
import os
dials_regression = libtbx.env.dist_path('dials_regression')
from boost.python import streambuf
from dxtbx import read_uint16
from dxtbx.format.Registry import Registry
for directory, image in [('SLS_X06SA', 'mar225_2_001.img')]:
file... | def tst_dxtbx():
import libtbx.load_env
import os
dials_regression = libtbx.env.dist_path('dials_regression')
from boost.python import streambuf
from dxtbx import read_uint16
from dxtbx.format.Registry import Registry
from dials_regression.image_examples.get_all_working_images import \
... | Use from dials_regression.image_examples.get_all_working_images import get_all_working_images method to get list of images | Use from dials_regression.image_examples.get_all_working_images import get_all_working_images method to get list of images | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials |
66e67e53360a9f49ae73c8c8f2de49991525363b | txircd/modules/cmode_t.py | txircd/modules/cmode_t.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class TopiclockMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "TOPIC":
return data
if "topic" not in data:
return data
targetChannel = data["targetchan"]
if "t" in targetChannel.mode and not user.hasAccess(self.ir... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class TopiclockMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "TOPIC":
return data
if "topic" not in data:
return data
targetChannel = data["targetchan"]
if "t" in targetChannel.mode and not user.hasAccess(targetC... | Fix the order of parameters to hasAccess, which broke all topic changing when +t was set | Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
| Python | bsd-3-clause | Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd |
61e8b679c64c7c2155c1c3f5077cf058dd6610d3 | forms.py | forms.py | """
JP-specific Form helpers
"""
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import RegexField, Select
class JPPostalCodeField(RegexField):
"""
A form field that validates its input is a Japanese postcode.
Accepts 7 digits, with or without a hyphen.
"""
defaul... | """
JP-specific Form helpers
"""
from __future__ import absolute_import
from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
class JPPostalCodeField(RegexField):
"""
A form field tha... | Remove all relative imports. We have always been at war with relative imports. | Remove all relative imports. We have always been at war with relative imports.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@17009 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | luyikei/django-localflavor-jp |
8164d048b47299377b4db7d9fc0198e24b07bdb3 | engine/geometry.py | engine/geometry.py | from math import cos, sin, pi, hypot
def rotate(polygon, angle):
rotated_points = []
cos_result = cos(angle)
sin_result = sin(angle)
for point in polygon:
x = point[0] * cos_result - point[1] * sin_result
y = point[0] * sin_result + point[1] * cos_result
rotated_points.append((x... | from math import cos, sin, pi, hypot
def rotate(polygon, angle):
rotated_points = []
cos_result = cos(angle)
sin_result = sin(angle)
for point in polygon:
x = point[0] * cos_result - point[1] * sin_result
y = point[0] * sin_result + point[1] * cos_result
rotated_points.append((x... | Fix move to return only int, draw functions cannot handle floats as coordinates | Fix move to return only int, draw functions cannot handle floats as coordinates
| Python | apache-2.0 | PGHM/spacebattle |
e292705df44ba511a0650e5b4d70ab5f2404e412 | ghutil/cli/pr/__init__.py | ghutil/cli/pr/__init__.py | import click
from ghutil.util import default_command, package_group
@package_group(__package__, __file__, invoke_without_command=True)
@click.pass_context
def cli(ctx):
""" Manage pull requests """
default_command(ctx, 'list')
| import click
from ghutil.util import default_command, package_group
@package_group(__package__, __file__, invoke_without_command=True)
@click.pass_context
def cli(ctx):
"""
Manage pull requests
GitHub pull requests may be specified on the command line using any of the
following formats:
\b
... | Document PR command line syntax | Document PR command line syntax
| Python | mit | jwodder/ghutil |
a45042c504fcb1b11741fb9ce786c5afb94219a7 | qual/tests/test_iso.py | qual/tests/test_iso.py | import unittest
from hypothesis import given
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d... | import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d ... | Add a new test for roundtripping in the opposite direction. | Add a new test for roundtripping in the opposite direction.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon |
9749cdaaebacd7316b581c5d368a5082fb6d3789 | test_projects/test_module_b/test_feat_4.py | test_projects/test_module_b/test_feat_4.py | import unittest
class TestG(unittest.TestCase):
def test_feat_1_case_1(self):
pass
def test_feat_1_case_2(self):
pass
def test_feat_1_case_3(self):
pass
def test_feat_1_case_4(self):
pass
class TestH(unittest.TestCase):
def test_feat_1_case_1(self):
pas... | import time
import unittest
class TestG(unittest.TestCase):
def test_feat_1_case_1(self):
pass
def test_feat_1_case_2(self):
pass
def test_feat_1_case_3(self):
pass
def test_feat_1_case_4(self):
pass
class TestH(unittest.TestCase):
def test_feat_1_case_1(self):... | Add empty time tests (for ui testing) | Add empty time tests (for ui testing)
| Python | mit | martinsmid/pytest-ui |
6603657df4626a9e2c82a3658c63314c7a9537f4 | src/experimental/os_walk_with_filechecker.py | src/experimental/os_walk_with_filechecker.py | #!/usr/bin/python3
# THIS FILE IS AN EXPERIMENTAL PROGRAM TO LEARN ABOUT OS_WALK
import os, sys
walk_dir = sys.argv[1]
print("walk directory: " + walk_dir)
print("Walk directory (absolute) = " + os.path.abspath(walk_dir))
print("\n\n\n\n\n\n\n\n\n")
for root, subdirs, files in os.walk(walk_dir):
print(root)
#lis... | #!/usr/bin/python3
# THIS FILE IS AN EXPERIMENTAL PROGRAM TO LEARN ABOUT OS_WALK
import os, sys, datetime
#dt = datetime.datetime(1970,1,1).total_seconds()
# print(dt)
walk_dir = sys.argv[1]
with open("fsscan.scan", "w") as f:
print("SCANFROM" + walk_dir)
for root, subdirs, files in os.walk(walk_dir):
f.write... | Add write dump to file | Add write dump to file
| Python | bsd-3-clause | paulkramme/btsoot |
fbb5addbb6b61a127066fd443d70f1cfe94f7c03 | marshmallow/__init__.py | marshmallow/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
__version__ = '1.0.0-dev'
__author__ = 'Steven Loria'
__license__ = 'MIT'
from marshmallow.schema import (
Schema,
SchemaOpts,
MarshalResult,
UnmarshalResult,
Serializer,
)
from marshmallow.utils import pprint
from marshmallow.exceptio... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
__version__ = '1.0.0-dev'
__author__ = 'Steven Loria'
__license__ = 'MIT'
from marshmallow.schema import (
Schema,
SchemaOpts,
MarshalResult,
UnmarshalResult,
Serializer,
)
from marshmallow.utils import pprint
from marshmallow.exceptio... | Put ValidationError on top-level namespace | Put ValidationError on top-level namespace
| Python | mit | 0xDCA/marshmallow,dwieeb/marshmallow,bartaelterman/marshmallow,maximkulkin/marshmallow,Tim-Erwin/marshmallow,mwstobo/marshmallow,VladimirPal/marshmallow,daniloakamine/marshmallow,xLegoz/marshmallow,marshmallow-code/marshmallow,0xDCA/marshmallow,etataurov/marshmallow,quxiaolong1504/marshmallow,Bachmann1234/marshmallow |
c55dbf067d85c3a060a6ffeff2aad24991e95eae | pandas/tests/series/test_validate.py | pandas/tests/series/test_validate.py | import pytest
from pandas.core.series import Series
class TestSeriesValidate(object):
"""Tests for error handling related to data types of method arguments."""
s = Series([1, 2, 3, 4, 5])
def test_validate_bool_args(self):
# Tests for error handling related to boolean arguments.
invalid_v... | import pytest
from pandas.core.series import Series
class TestSeriesValidate(object):
"""Tests for error handling related to data types of method arguments."""
s = Series([1, 2, 3, 4, 5])
def test_validate_bool_args(self):
# Tests for error handling related to boolean arguments.
invalid_v... | Remove duplicate Series sort_index check | MAINT: Remove duplicate Series sort_index check
Duplicate boolean validation check for sort_index in series/test_validate.py | Python | bsd-3-clause | pratapvardhan/pandas,rs2/pandas,winklerand/pandas,jorisvandenbossche/pandas,zfrenchee/pandas,winklerand/pandas,TomAugspurger/pandas,pandas-dev/pandas,harisbal/pandas,jmmease/pandas,pratapvardhan/pandas,TomAugspurger/pandas,DGrady/pandas,jorisvandenbossche/pandas,cython-testbed/pandas,zfrenchee/pandas,nmartensen/pandas,... |
3acd7d885e6c660c3acb0b584b7ed07c8a1a4df3 | docs/source/_examples/myclient.py | docs/source/_examples/myclient.py | import socket, ssl
import h11
class MyHttpClient:
def __init__(self, host, port):
self.sock = socket.create_connection((host, port))
if port == 443:
self.sock = ssl.wrap_socket(self.sock)
self.conn = h11.Connection(our_role=h11.CLIENT)
def send(self, *events):
for e... | import socket, ssl
import h11
class MyHttpClient:
def __init__(self, host, port):
self.sock = socket.create_connection((host, port))
if port == 443:
ctx = ssl.create_default_context()
self.sock = ctx.wrap_socket(self.sock, server_hostname=host)
self.conn = h11.Connec... | Support SNI in the example client | Support SNI in the example client
Fixes: gh-36
| Python | mit | python-hyper/h11,njsmith/h11 |
23d92f1a24e919bd1b232cb529dbe022f6cdd463 | gwv/gwv.py | gwv/gwv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from gwv import version
from validator import validate
def main(args=None):
if args is None:
args = sys.argv[1:]
import argparse
parser = argparse.ArgumentParser(description="GlyphWiki data validator")
parser.add_argument("d... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from gwv import version
from validator import validate
def open_dump(filename):
dump = {}
with open(filename) as f:
if filename[-4:] == ".csv":
for l in f:
row = l.rstrip("\n").split(",")
i... | Use dict for dump data format | Use dict for dump data format
| Python | mit | kurgm/gwv |
d3f8c8639462feffe15c457d0009b36816fd3264 | HOME/bin/lib/setup/__init__.py | HOME/bin/lib/setup/__init__.py | from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this program lives in $repo/HOME/bin/lib, so $repo/HOME/bin/../../.. will
# get the root of the repos... | from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__fi... | Refactor setup.root to never again need to be changed if the file moves | Refactor setup.root to never again need to be changed if the file moves
| Python | mit | kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup |
58620934b0a49cdde573ed7090053e3316fcf215 | xpserver_api/serializers.py | xpserver_api/serializers.py | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer... | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
... | Add user registration via api | Add user registration via api
| Python | mit | xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server |
4a0569d129d770fead45f3b0d9069ff54e8ddc56 | xoinvader/game.py | xoinvader/game.py | #! /usr/bin/env python3
"""Main XOInvader module, that is entry point to game.
Prepare environment for starting game and start it."""
import curses
from xoinvader.menu import MainMenuState
from xoinvader.ingame import InGameState
from xoinvader.render import Renderer
from xoinvader.common import Settings
from xoin... | #! /usr/bin/env python3
"""Main XOInvader module, that is entry point to game.
Prepare environment for starting game and start it."""
import curses
from xoinvader.menu import MainMenuState
from xoinvader.ingame import InGameState
from xoinvader.render import Renderer
from xoinvader.common import Settings
from xoin... | Add stop method, fix dangerous args. | Add stop method, fix dangerous args.
| Python | mit | pkulev/xoinvader,pankshok/xoinvader |
b8656ae21ab494b49013a7cd67facff7bdbd7cf5 | index.py | index.py | from flask import Flask
from flask_redis import FlaskRedis
from config import BaseConfig
app = Flask(__name__)
app.config.from_object(BaseConfig)
db = FlaskRedis(app)
| from flask import Flask
from flask_redis import FlaskRedis
from redis import StrictRedis
from config import BaseConfig
class DecodedRedis(StrictRedis):
@classmethod
def from_url(cls, url, db=None, **kwargs):
kwargs['decode_responses'] = True
return StrictRedis.from_url(url, db, **kwargs)
app... | Add decode_responses option to redis | Add decode_responses option to redis
| Python | mit | tferreira/Flask-Redis |
5cadb19aec67945efa5c4367ee4d1aab6bbc66e7 | git-issues/git-handler.py | git-issues/git-handler.py | import os
import re
import subprocess
import requests
GITHUB_API_ADDRESS = "https://api.github.com/"
def get_git_address():
response = subprocess.check_output(['git', 'remote', '-v'])
dirty = response.split('\n')
repos = {}
for repo in dirty:
rep = repo.split('\t')
if len(rep) > 1:
... | import os
import re
import subprocess
import requests
GITHUB_API_ADDRESS = "https://api.github.com/"
def get_git_address():
response = subprocess.check_output(['git', 'remote', '-v'])
dirty = response.split('\n')
repos = {}
for repo in dirty:
rep = repo.split('\t')
if len(rep) > 1:
... | Split out writing to disk into it's own mfunction | Split out writing to disk into it's own mfunction
| Python | apache-2.0 | AutomatedTester/git-issues,AutomatedTester/git-issues,AutomatedTester/git-issues |
bc6af25366aacf394f96b5a93008109904a89e93 | wlauto/common/android/resources.py | wlauto/common/android/resources.py | # Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Add a UiautoApk resource type. | AndroidResource: Add a UiautoApk resource type.
When moving to Uiautomation 2, tests are now complied into apk files rather than
jar files. To avoid conflicts with regular workload apks a new resource type is
added to retrieve the test files which will be renamed to have the extension
.uiautoapk
| Python | apache-2.0 | bjackman/workload-automation,bjackman/workload-automation,bjackman/workload-automation,bjackman/workload-automation,jimboatarm/workload-automation,jimboatarm/workload-automation,jimboatarm/workload-automation,bjackman/workload-automation,bjackman/workload-automation,jimboatarm/workload-automation,jimboatarm/workload-au... |
15c58fb05a9bfb06b87d8d00a1b26d50ee68c1f7 | django/publicmapping/redistricting/management/commands/makelanguagefiles.py | django/publicmapping/redistricting/management/commands/makelanguagefiles.py | #!/usr/bin/python
from django.core.management.base import BaseCommand
from redistricting.utils import *
class Command(BaseCommand):
"""
This command prints creates and compiles language message files
"""
args = None
help = 'Create and compile language message files'
def handle(self, *args, **o... | #!/usr/bin/python
from django.core.management.base import BaseCommand
from redistricting.utils import *
class Command(BaseCommand):
"""
This command prints creates and compiles language message files
"""
args = None
help = 'Create and compile language message files'
def handle(self, *args, **o... | Add creation of js message files to management command | Add creation of js message files to management command
| Python | apache-2.0 | JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder |
8ddcabe29dfaa6716578664224620fc5a0116a2b | tests/test_cli_eigenvals.py | tests/test_cli_eigenvals.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bands_inspect as bi
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import c... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""
Tests for the 'eigenvals' command.
"""
import os
import tempfile
import numpy as np
import bands_inspect as bi
from click.testing import CliRunner
from tbmodels.... | Fix pre-commit issue for the cli_eigenvals test. | Fix pre-commit issue for the cli_eigenvals test.
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
842ab1d53224117fc750d963b6c5f3b6f5af5f1d | hakoblog/db.py | hakoblog/db.py | import MySQLdb
import MySQLdb.cursors
from hakoblog.config import CONFIG
class DB():
def __init__(self):
self.conn = MySQLdb.connect(
db=CONFIG.DATABASE,
host=CONFIG.DATABASE_HOST,
user=CONFIG.DATABASE_USER,
password=CONFIG.DATABASE_PASS,
cursorc... | import MySQLdb
import MySQLdb.cursors
from hakoblog.config import CONFIG
class DB():
def __init__(self):
self.conn = MySQLdb.connect(
db=CONFIG.DATABASE,
host=CONFIG.DATABASE_HOST,
user=CONFIG.DATABASE_USER,
password=CONFIG.DATABASE_PASS,
cursorc... | Add charset to connect mysql | Add charset to connect mysql
| Python | mit | hakobe/hakoblog-python,hakobe/hakoblog-python,hakobe/hakoblog-python |
d478c966192241cccf53ac665820fd9a62ebcdeb | huxley/api/permissions.py | huxley/api/permissions.py | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_pe... | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_pe... | Make IsPostOrSuperuserOnly a non-object-level permission. | Make IsPostOrSuperuserOnly a non-object-level permission.
| Python | bsd-3-clause | nathanielparke/huxley,bmun/huxley,bmun/huxley,nathanielparke/huxley,bmun/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,bmun/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley |
f88d747f7959808884451245aeba65edf7c490bf | synapse/replication/slave/storage/filtering.py | synapse/replication/slave/storage/filtering.py | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Add a comment explaining why the filter cache doesn't need exipiring | Add a comment explaining why the filter cache doesn't need exipiring
| Python | apache-2.0 | TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,TribeMedia/synapse |
6e724725fca65d3e63b1bfe44f9c2bcb22ae862d | banana/maya/__init__.py | banana/maya/__init__.py | # __
# | |--.---.-.-----.---.-.-----.---.-. .--------.---.-.--.--.---.-.
# | _ | _ | | _ | | _ |__| | _ | | | _ |
# |_____|___._|__|__|___._|__|__|___._|__|__|__|__|___._|___ |___._|
# ... | # __
# | |--.---.-.-----.---.-.-----.---.-. .--------.---.-.--.--.---.-.
# | _ | _ | | _ | | _ |__| | _ | | | _ |
# |_____|___._|__|__|___._|__|__|___._|__|__|__|__|___._|___ |___._|
# ... | Remove a leftover module from the `__all__` attribute. | Remove a leftover module from the `__all__` attribute.
| Python | mit | christophercrouzet/bana,christophercrouzet/banana.maya |
e6c9ceb3f838a613d182a3fdea961ca1f73e90c4 | translator/models.py | translator/models.py | # coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.decorators import classproperty
from taggit.managers import TaggableManager
from translator.util import get_key
class TranslationBase(models.Model):
key = models.CharField(max_length... | # coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from taggit.managers import TaggableManager
from translator.util import get_key
try:
# Django 3.1 and above
from django.utils.functional import classproperty
except ImportError:
from django.uti... | Update import for classproperty in django 3.1 and above | Update import for classproperty in django 3.1 and above
| Python | mit | dreipol/django-translator |
b19eb216f1f1e9c059b083af7ff72864994f5920 | project_name/project_name/urls.py | project_name/project_name/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# include urls from your app like so
# url(r'^', include('my_app.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
# include urls from your app like so
# url(r'^', include('my_app.urls')),
)
| Put admin at the top of the default URLs | Put admin at the top of the default URLs
| Python | mit | jimray/django-project-skeleton,jimray/django-project-skeleton |
5883ccc3ca5ff073f571fa9cfe363d7a0be59d47 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online e... | #!/usr/bin/env python
from distutils.core import setup
import request
setup(
name='django-request',
version='%s' % request.__version__,
description='django-request is a statistics module for django. It stores requests in a database for admins to see, it can also be used to get statistics on who is online e... | Set the download link to the current version of django-request, not latest git. | Set the download link to the current version of django-request, not latest git.
| Python | bsd-2-clause | kylef/django-request,gnublade/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request,kylef/django-request |
21220dee455cb51b26a82caa1fbe11c09ac18351 | linter.py | linter.py | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
... | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Markdownlint(NodeLinter):
... | Remove empty defaults and deprecated settings | Remove empty defaults and deprecated settings
| Python | mit | jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint |
7da1482f93090bcafc420e96aa07515be61c8c50 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Joshua Hagins
# Copyright (c) 2015 Joshua Hagins
#
# License: MIT
#
"""This module exports the RubyLint plugin class."""
from SublimeLinter.lint import RubyLinter
class RubyLint(RubyLinter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Joshua Hagins
# Copyright (c) 2015 Joshua Hagins
#
# License: MIT
#
"""This module exports the RubyLint plugin class."""
from SublimeLinter.lint import RubyLinter
class RubyLint(RubyLinter):
"""Provides an in... | Use 'ruby -S' to find ruby-lint executable | Use 'ruby -S' to find ruby-lint executable
| Python | mit | jawshooah/SublimeLinter-contrib-ruby-lint |
e6d3d60265db1947b8af2d1c59c575c632ddc20b | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | Add support for handling errors and warnings | Add support for handling errors and warnings
| Python | mit | lzwme/SublimeLinter-contrib-stylelint,lzwme/SublimeLinter-contrib-stylelint,kungfusheep/SublimeLinter-contrib-stylelint |
da9628271be108b1236b9dbbcaf6cda9494b7b63 | setup.py | setup.py | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | Change PyPI development status from pre-alpha to beta. | Change PyPI development status from pre-alpha to beta.
| Python | bsd-3-clause | nghung270192/colorama,nghung270192/colorama |
4c12f68e5d86acb4152acf5ace6a02b6968db925 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='icalendar',
version='0.10',
description='iCalendar support module',
package_dir = {'': 'src'},
packages=['icalendar'],
)
| #!/usr/bin/env python
from distutils.core import setup
f = open('version.txt', 'r')
version = f.read().strip()
f.close()
setup(name='icalendar',
version=version,
description='iCalendar support module',
package_dir = {'': 'src'},
packages=['icalendar'],
)
| Tweak so that version information is picked up from version.txt. | Tweak so that version information is picked up from version.txt.
| Python | bsd-2-clause | nylas/icalendar,geier/icalendar,untitaker/icalendar |
03d321f5700f2cd3f02de8aa2b601fa14d3de144 | setup.py | setup.py | #!/usr/bin/python
# from setuptools
# import setup
import os
__author__ = "Andre Christoga"
input = raw_input("> (eg plus, minus, divide...)")
if input == "plus":
os.system("pymain/plus.py")
if input == "minus":
os.system("pymain/minus.py")
if input == "multi":
os.system("pymain/multi.py")
if input == "divide":
o... | #!/usr/bin/python
# from setuptools
# import setup
import os
__author__ = "Andre Christoga"
input = raw_input("> (eg plus, minus, divide...)")
if input == "plus":
os.system("pymain/plus.py")
if input == "minus":
os.system("pymain/minus.py")
if input == "multi":
os.system("pymain/multi.py")
if input == "divide":
o... | Remove not found script message | Remove not found script message
| Python | mit | codingsmartschool/PyMaIn |
0163e8821288db826b595051a6312b19c66e05f0 | ideascaly/utils.py | ideascaly/utils.py | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.r... | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.r... | Add a conditional to check whther 'arg' is a byte | Add a conditional to check whther 'arg' is a byte
| Python | mit | joausaga/ideascaly |
abd5c75dbe8eab93504888c2483f63e77e72ffb2 | macroeco/misc/__init__.py | macroeco/misc/__init__.py | """
===============================
Misc (:mod:`macroeco.misc`)
===============================
This module contains miscellaneous functions that support the functions of
other modules of macroeco.
Support Functions
=================
.. autosummary::
:toctree: generated/
setup_log
log_start_end
inherit_... | """
===============================
Misc (:mod:`macroeco.misc`)
===============================
This module contains miscellaneous functions that support the functions of
other modules of macroeco.
Support Functions
=================
.. autosummary::
:toctree: generated/
log_start_end
inherit_docstring_fro... | Remove setup_log function from misc init (no longer present) | Remove setup_log function from misc init (no longer present)
| Python | bsd-2-clause | jkitzes/macroeco |
edb73a4d8bba1c1265bfc00e5a765ff47c120e02 | plasma/test/__init__.py | plasma/test/__init__.py | # Copyright (c) 2007-2009 The Plasma Project.
# See LICENSE.txt for details.
| # Copyright (c) 2007-2009 The Plasma Project.
# See LICENSE.txt for details.
import unittest
def failUnlessIdentical(self, first, second, msg=None):
"""
Fail the test if C{first} is not C{second}. This is an
obect-identity-equality test, not an object equality (i.e. C{__eq__}) test.
@param msg: if ... | Add assertIdentical support from twisted.trial | Add assertIdentical support from twisted.trial
| Python | mit | hydralabs/plasma,hydralabs/plasma |
5f5530205b54ca7929376c3c8e8d2c1fd68378a4 | rollbar/contrib/asgi/__init__.py | rollbar/contrib/asgi/__init__.py | import rollbar
class ASGIMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
try:
await self.app(scope, receive, send)
except Exception:
rollbar.report_exc_info()
raise
def _hook(request, data):
... | import rollbar
try:
from starlette.types import ASGIApp, Scope, Receive, Send
except ImportError:
STARLETTE_INSTALLED = False
else:
STARLETTE_INSTALLED = True
if STARLETTE_INSTALLED is True:
class ASGIMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
as... | Add typing support for Starlette-based apps | Add typing support for Starlette-based apps
| Python | mit | rollbar/pyrollbar |
23cc21bd441ac0c058d9df43276085badb27d905 | srrun.py | srrun.py | #!/usr/bin/env python
# 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/.
import copy
import os
import platform
import subprocess
import sys
mypath = os.path.abspath(__fil... | #!/usr/bin/env python
# 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/.
import copy
import os
import platform
import subprocess
import sys
mypath = os.path.abspath(__fil... | Use the appropriate path separator | Use the appropriate path separator
| Python | mpl-2.0 | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge |
971b36aedd700b23d791b72f60a9a534cc1be0ec | src/SALib/test_functions/Ishigami.py | src/SALib/test_functions/Ishigami.py | from __future__ import division
import math
import numpy as np
# Non-monotonic Ishigami Function (3 parameters)
# Using Saltelli sampling with a sample size of ~1000
# the expected first-order indices would be:
# x1: 0.3139
# x2: 0.4424
# x3: 0.0
def evaluate(values):
Y = np.zeros([values.shape[0]... | from __future__ import division
import numpy as np
# Non-monotonic Ishigami Function (3 parameters)
# Using Saltelli sampling with a sample size of ~1000
# the expected first-order indices would be:
# x1: 0.3139
# x2: 0.4424
# x3: 0.0
def evaluate(values):
Y = np.zeros(values.shape[0])
A = 7
... | Use numpy functions to allow future vectorization | Use numpy functions to allow future vectorization
| Python | mit | SALib/SALib,jdherman/SALib,jdherman/SALib |
504764d36344921b1c765f6ef19b21bbe0a29653 | cpnest/__init__.py | cpnest/__init__.py | import logging
from .logger import CPNestLogger
from .cpnest import CPNest
# Get the version number from git tag
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version(__name__)
except PackageNotFoundError:
# package is not installed
__version__ = "unknown"
logging.setLog... | import logging
from .logger import CPNestLogger
from .cpnest import CPNest
# Get the version number from git tag
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
__version__ = "dev"... | Revert "Get version using importlib" | Revert "Get version using importlib"
This reverts commit 5df63fc784121f113c14195c5ae63a6591e92ae6.
| Python | mit | johnveitch/cpnest |
fa07eded66aa0d0e8d1eeb127e9d29a3df971cbc | poradnia/cases/admin.py | poradnia/cases/admin.py | from django.utils.translation import ugettext as _
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from records.models import Record
from .models import Case, PermissionGroup
class RecordInline(admin.StackedInline):
'''
Stacked Inline View for Record
'''
model = Recor... | from django.utils.translation import ugettext as _
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from records.models import Record
from .models import Case, PermissionGroup
class RecordInline(admin.StackedInline):
'''
Stacked Inline View for Record
'''
model = Recor... | Add filter by tags in CaseAdmin | Add filter by tags in CaseAdmin
| Python | mit | watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl |
b1a21354735e3e4b58cf63c3fc81b6e8e2ee5ed7 | concourse/scripts/builds/GpBuild.py | concourse/scripts/builds/GpBuild.py | import os
import subprocess
import sys
from GpdbBuildBase import GpdbBuildBase
class GpBuild(GpdbBuildBase):
def __init__(self, mode):
self.mode = 'on' if mode == 'orca' else 'off'
def configure(self):
return subprocess.call(["./configure",
"--enable-mapreduce",... | import os
import subprocess
import sys
from GpdbBuildBase import GpdbBuildBase
class GpBuild(GpdbBuildBase):
def __init__(self, mode):
self.mode = 'on' if mode == 'orca' else 'off'
def configure(self):
return subprocess.call(["./configure",
"--enable-mapreduce",... | Disable PXF in ORCA CI | Disable PXF in ORCA CI
| Python | apache-2.0 | greenplum-db/gpdb,xinzweb/gpdb,adam8157/gpdb,adam8157/gpdb,greenplum-db/gpdb,lisakowen/gpdb,yuanzhao/gpdb,yuanzhao/gpdb,lisakowen/gpdb,lisakowen/gpdb,Chibin/gpdb,lisakowen/gpdb,Chibin/gpdb,adam8157/gpdb,Chibin/gpdb,Chibin/gpdb,xinzweb/gpdb,ashwinstar/gpdb,jmcatamney/gpdb,edespino/gpdb,janebeckman/gpdb,janebeckman/gpdb,... |
c3876cd1ad2c73fa4278469b75c6d42b89fac8ea | Friends-By-Age.py | Friends-By-Age.py | from pyspark import SparkConf, SparkContext
import collections
conf = SparkConf().setMaster("local").setAppName("FriendsByAge")
sc = SparkContext(conf = conf)
def parseLine(line):
fields = line.split(',')
age = int(fields[2])
numFriends = int(fields[3])
return (age, numFriends)
lines = sc... | from pyspark import SparkConf, SparkContext
import collections
conf = SparkConf().setMaster("local").setAppName("FriendsByAge")
sc = SparkContext(conf = conf)
def parseLine(line):
fields = line.split(',')
age = int(fields[2])
numFriends = int(fields[3])
return (age, numFriends)
lines = sc... | Sort the resulted list of items | Sort the resulted list of items
| Python | mit | tonirilix/apache-spark-hands-on |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.