commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
bc1c65315fe22146b2d9a0955acc6e286b069657 | Add problem 48 | mc10/project-euler | problem_48.py | problem_48.py | '''
Problem 48
@author: Kevin Ji
'''
def self_power_with_mod(number, mod):
product = 1
for _ in range(number):
product *= number
product %= mod
return product
MOD = 10000000000
number = 0
for power in range(1, 1000 + 1):
number += self_power_with_mod(power, MOD)
number %= MOD
... | mit | Python | |
008625fef55f8f58ab80b883d34ae5d40e55c721 | Add initial test for binheap | constanthatz/data-structures | test_binheap.py | test_binheap.py | import pytest
from binheap import Binheap
def test_init_bh():
b = Binheap()
assert b.binlist is []
c = Binheap([1, 2])
assert c.binlist == [1, 2]
| mit | Python | |
d43c67a59dcf6c43667d633df8b6f8a3eb84d611 | add HelloKhalaClient2.py | moyangvip/khala,moyangvip/khala,moyangvip/khala | examples/testClient/HelloKhalaClient2.py | examples/testClient/HelloKhalaClient2.py | #moss's HelloKhala Client
#add time type
import socket
import struct
import json
def login():
send = {'type': 'login'}
return send
def logout():
send = {'type': 'logout'}
return send
def devType():
send = {'type': 'dev'}
return send
def isLogin():
send = {'type': 'isLogin'}
return send
def n... | bsd-2-clause | Python | |
80e80bff7603e852710df6c9de613b1781877b2d | Test case for two classes with the same name in one module. | retoo/pystructure,retoo/pystructure,retoo/pystructure,retoo/pystructure | tests/python/typeinference/same_name.py | tests/python/typeinference/same_name.py | class A(object):
def method(self):
return 1
A().method() ## type int
class A(object):
def method(self):
return "test"
A().method() ## type str
| lgpl-2.1 | Python | |
4887a269a28656c288461165078943f99e2390be | add settings template for ansible later | naggie/crates,naggie/crates,naggie/crates | ansible/crates_settings.py | ansible/crates_settings.py | from base_settings import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zhj_+x#q-&vqh7&)7a3it@tcsf50@fh9$3&&j0*4pmt1x=ye+1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['.']
# where will nginx look for static files for product... | mit | Python | |
4143f5381b8ff47a80a550065e831c306551cd77 | solve problem 035 | ringsd/projecteuler | python/035.py | python/035.py |
def base10_to_base2( n ):
base2n = 0
if n == 0:
return 0
return base10_to_base2( n/2 ) * 10 + n % 2
def palindromes( s ):
flag = True
str_len = len(s)
half_len = str_len / 2
for i in range( 0, half_len+1 ):
if s[i] != s[str_len-i-1]:
flag = False
bre... | mit | Python | |
a5a7d6c3097571a9ef050a75127a2eb24ad2746c | Remove test code. | pearsontechnology/st2contrib,pearsontechnology/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,pidah/st2contrib,armab/st2contrib,StackStorm/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,StackStorm/st2cont... | packs/alertlogic/actions/scan_list_scan_executions.py | packs/alertlogic/actions/scan_list_scan_executions.py | #!/usr/bin/env python
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licens... | #!/usr/bin/env python
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licens... | apache-2.0 | Python |
7ecec2d2b516d9ae22a3a0f652424045d547d811 | Put object_tools in the correct order in settings | felixxm/django-object-tools,praekelt/django-object-tools,shubhamdipt/django-object-tools,shubhamdipt/django-object-tools,praekelt/django-object-tools,sky-chen/django-object-tools,felixxm/django-object-tools,sky-chen/django-object-tools | test_settings.py | test_settings.py | DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = '123'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'object_tools',
'djan... | DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = '123'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
... | bsd-3-clause | Python |
35296b1c87a86a87fbcf317e26a497fc91c287c7 | Update receiver to catch value error | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | lexos/receivers/kmeans_receiver.py | lexos/receivers/kmeans_receiver.py | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... | mit | Python |
89d83b9ca8c1c52537aae0c5339b0cb5ae64c6c4 | Add additional test for template filters: for filter queries and filter with variable argument | GrAndSE/lighty,GrAndSE/lighty-template | tests/filters.py | tests/filters.py | """Test cases for variable fields
"""
import unittest
from lighty.templates import Template
from lighty.templates.filter import filter_manager
def simple_filter(value):
return str(value).upper()
filter_manager.register(simple_filter)
def argument_filter(value, arg):
return str(value) + ', ' + str(arg)
filte... | """Test cases for variable fields
"""
import unittest
from lighty.templates import Template
from lighty.templates.filter import filter_manager
def simple_filter(value):
return str(value).upper()
filter_manager.register(simple_filter)
def argument_filter(value, arg):
return str(value) + ', ' + str(arg)
filte... | bsd-3-clause | Python |
8874af7c0db371f63da687c5398db1c7b80f58cd | Fix import of django during install time (for environments like Heroku) (#120) | shacker/django-todo,shacker/django-todo,shacker/django-todo | todo/__init__.py | todo/__init__.py | """
A multi-user, multi-group task management and assignment system for Django.
"""
__version__ = "2.4.10"
__author__ = "Scot Hacker"
__email__ = "shacker@birdhouse.org"
__url__ = "https://github.com/shacker/django-todo"
__license__ = "BSD License"
try:
from . import check
except ModuleNotFoundError:
# this can ha... | """
A multi-user, multi-group task management and assignment system for Django.
"""
__version__ = "2.4.10"
__author__ = "Scot Hacker"
__email__ = "shacker@birdhouse.org"
__url__ = "https://github.com/shacker/django-todo"
__license__ = "BSD License"
from . import check
| bsd-3-clause | Python |
4d2f3ee1343b9aef24f599b8acd07ed8340f0bff | convert that to a list so we can measure it's len in a template | tndatacommons/tndata_backend,izzyalonso/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend | tndata_backend/notifications/views.py | tndata_backend/notifications/views.py | from collections import defaultdict
from django.contrib.auth.decorators import user_passes_test
from django.contrib import messages
from django.shortcuts import render, redirect
from . import queue
from .models import GCMMessage
@user_passes_test(lambda u: u.is_staff, login_url='/')
def dashboard(request):
"""A... | from collections import defaultdict
from django.contrib.auth.decorators import user_passes_test
from django.contrib import messages
from django.shortcuts import render, redirect
from . import queue
from .models import GCMMessage
@user_passes_test(lambda u: u.is_staff, login_url='/')
def dashboard(request):
"""A... | mit | Python |
6618ea7c1b67d87acff86338415e2a322a01cc3c | add loopback support | danudey/pypcap,danudey/pypcap | testsniff.py | testsniff.py | #!/usr/bin/env python
import getopt, sys
import dpkt, pcap
def usage():
print >>sys.stderr, 'usage: %s [-i device] [pattern]' % sys.argv[0]
sys.exit(1)
def main():
opts, args = getopt.getopt(sys.argv[1:], 'i:h')
name = None
for o, a in opts:
if o == '-i': name = a
else: usage()
... | #!/usr/bin/env python
import getopt, sys
import pcap
from dpkt.ethernet import Ethernet
def usage():
print >>sys.stderr, 'usage: %s [-i device] [pattern]' % sys.argv[0]
sys.exit(1)
def main():
opts, args = getopt.getopt(sys.argv[1:], 'i:h')
name = None
for o, a in opts:
if o == '-i': name... | bsd-3-clause | Python |
a1bda82bd06cbfd12e6074f22cb31d88f2abd96a | update py +x | ray26/google-hosts,ayyb1988/google-hosts,ChaneyZhao/google-hosts,SolaWing/google-hosts,ray26/google-hosts,bgarrels/google-hosts,xiaozihan2011/google-hosts,9618211/google-hosts,EasonYi/google-hosts,DavikChen/google-hosts,manfy/google-hosts,monkeytest15/google-hosts,peterdocter/google-hosts,shenleilei/google-hosts,fengsh... | tools/fuckGFW.py | tools/fuckGFW.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Update hosts for *nix
Author: cloud@txthinking.com
Version: 0.0.1
Date: 2012-10-24 14:35:39
'''
import urllib2
import os
import sys
HOSTS_PATH = "/etc/hosts"
HOSTS_SOURCE = "http://tx.txthinking.com/hosts"
SEARCH_STRING = "#TX-HOSTS"
def GetRemoteHosts(url):
f = ... | '''
Update hosts for *nix
Author: cloud@txthinking.com
Version: 0.0.1
Date: 2012-10-24 14:35:39
'''
import urllib2
import os
import sys
HOSTS_PATH = "/etc/hosts"
HOSTS_SOURCE = "http://tx.txthinking.com/hosts"
SEARCH_STRING = "#TX-HOSTS"
def GetRemoteHosts(url):
f = urllib2.urlopen(url, timeout=5)
hosts = [l... | mit | Python |
145e9141af1e1abdf0a9ab3c035ed8df6298ba0f | rebase migration dependency. | masschallenge/django-accelerator,masschallenge/django-accelerator | accelerator/migrations/0015_expert_bio_add_max_length_validation.py | accelerator/migrations/0015_expert_bio_add_max_length_validation.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-25 15:00
from __future__ import unicode_literals
import django.core.validators
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0014_alter_fluent_page_type_manage... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-25 15:00
from __future__ import unicode_literals
import django.core.validators
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0013_allocator'),
]
opera... | mit | Python |
837f05228fac7f6addd28069c6387f798e01ff8c | Add checksum test. | andrewguy9/farmfs,andrewguy9/farmfs | tests/test_fs.py | tests/test_fs.py | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
import pytest
def test_create_path():
p1 = Path("/")
p2 = Path("/a")
p2 = Path("/a/b")
p3 = Path(p1)
p4 = Path("a", p1)
with pytest.raises(AssertionError):
p5 = Path("/a/b", p2)
with py... | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
import pytest
def test_create_path():
p1 = Path("/")
p2 = Path("/a")
p2 = Path("/a/b")
p3 = Path(p1)
p4 = Path("a", p1)
with pytest.raises(AssertionError):
p5 = Path("/a/b", p2)
with py... | mit | Python |
9786c5f242f2b70240e7bb23c866c864cb4ed4ca | Add registrations to admin | small-worlds/expedition-manager,small-worlds/expedition-manager | expeditions/admin.py | expeditions/admin.py | from django.contrib import admin
from expeditions.models import Expedition, Waypoint, Registration
# Register your models here.
class ExpeditionAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'start_date', 'end_date', 'published')
list_display_links = ('id', 'name')
search_fields = ('name', 'start_d... | from django.contrib import admin
from expeditions.models import Expedition, Waypoint
# Register your models here.
class ExpeditionAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'start_date', 'end_date', 'published')
search_fields = ('name', 'start_date')
list_filter = ('published', )
class Waypoi... | mit | Python |
ab23ea60457720d0a7414b1b84191945f529b23c | Update _version.py | theno/fabsetup,theno/fabsetup | fabsetup/_version.py | fabsetup/_version.py | __version__ = "0.7.9" # semantic versioning: https://semver.org
| __version__ = "0.7.9"
| mit | Python |
8c4edd4cc8fdd6c7c470e25436b6c6b4c146ad58 | Fix error casting datetime objects | dicortazar/xen-code-review-analysis | data-analysis/utils.py | data-analysis/utils.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This ... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This ... | artistic-2.0 | Python |
9f405a3b4e01ee0a42a8530cfc5b509a38067250 | Remove unused import | reinikai/mugloar | mugloar/dragon.py | mugloar/dragon.py |
class Dragon:
# By default, stay home.
scaleThickness = 0
clawSharpness = 0
wingStrength = 0
fireBreath = 0
def __init__(self, weather_code):
if weather_code == 'T E':
# Draught requires a 'balanced' dragon, ha ha
self.scaleThickness = 5
self.clawSh... | import json
class Dragon:
# By default, stay home.
scaleThickness = 0
clawSharpness = 0
wingStrength = 0
fireBreath = 0
def __init__(self, weather_code):
if weather_code == 'T E':
# Draught requires a 'balanced' dragon, ha ha
self.scaleThickness = 5
... | mit | Python |
b8701f04d049101c8c92b468b4fc3dc863f1e292 | Add bulk accept and reject for talks | pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,djds23/pygotham-1,PyGotham/pygotham,pathunstrom/pygotham,djds23/pygotham-1,djds23/pygotham-1,PyGotham/pygotham | pygotham/admin/talks.py | pygotham/admin/talks.py | """Admin for talk-related models."""
from flask.ext.admin import actions
from flask.ext.admin.contrib.sqla import ModelView
from pygotham.admin.utils import model_view
from pygotham.core import db
from pygotham.talks import models
__all__ = ('CategoryModelView', 'talk_model_view', 'TalkReviewModelView')
CATEGORY = ... | """Admin for talk-related models."""
from pygotham.admin.utils import model_view
from pygotham.talks import models
__all__ = ('CategoryModelView', 'TalkModelView', 'TalkReviewModelView')
CategoryModelView = model_view(
models.Category,
'Categories',
'Talks',
form_columns=('name', 'slug'),
)
TalkMod... | bsd-3-clause | Python |
ec261fdaf41bd91558e4df143be8dfd9940bde81 | Rewrite bubble sort. | atariskorpion/simple-coding-solutions,atariskorpion/simple-coding-solutions | py/sorting/05_bubbleSort.py | py/sorting/05_bubbleSort.py | def bubbleSort(A):
for k in range(len(A)-1, 0, -1):
for i in range(k):
if A[i] > A[i+1]:
tempValue = A[i]
A[i] = A[i+1]
A[i+1] = tempValue
return A
print(bubbleSort([54,26,93,17,77,31,44,55,20]))
def bubbleSortReverse(A):
for k in range(... | def bubbleSort(A):
tempValue = 0
for k in range(1, len(A)):
flag = 0
for i in range(0, len(A) - k):
if A[i+1] > A[i]:
tempValue = A[i+1]
A[i+1] = A[i]
A[i] = tempValue
flag += 1
if flag == 0:
break
... | mit | Python |
c2a99a33455e3b01ccce3faebd3a541b4a76e579 | Bump version | rigal-m/Yamale,23andMe/Yamale | yamale/__init__.py | yamale/__init__.py | from .yamale import make_schema, make_data, validate
VERSION = (1, 0, 1, 'final', 0)
# Dynamically calculate the version based on VERSION.
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', '... | from .yamale import make_schema, make_data, validate
VERSION = (1, 0, 0, 'final', 0)
# Dynamically calculate the version based on VERSION.
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', '... | mit | Python |
33b4c181b2d9a3d74f45ee1ced971b5bca58b35b | remove unused import | NetstationMurator/django-treenav,NetstationMurator/django-treenav,caktus/django-treenav,caktus/django-treenav | treenav/admin.py | treenav/admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from treenav import models as treenav
from treenav.forms import MenuItemForm, GenericInlineMenuItemForm
class GenericMenuItemInline(generic.GenericStackedInline):
"""
Add this inline to your admin class to support editing relate... | from django.contrib import admin
from django import forms
from django.contrib.contenttypes import generic
from treenav import models as treenav
from treenav.forms import MenuItemForm, GenericInlineMenuItemForm
class GenericMenuItemInline(generic.GenericStackedInline):
"""
Add this inline to your admin class ... | bsd-3-clause | Python |
6c8a9edb6d733ac680ea2cbcb1c8d12511aa72be | Update webserver.py | NeXTHorizon/nhzpool,NeXTHorizon/nhzpool | webserver.py | webserver.py | #!/usr/bin/env python
# author: brendan@shellshockcomputer.com.au
import ConfigParser
from bottle import route, install, run, template, static_file, PasteServer
from bottle_sqlite import SQLitePlugin
import json
import urllib
import urllib2
import datetime
config = ConfigParser.RawConfigParser()
config.read('config.... | #!/usr/bin/env python
# author: brendan@shellshockcomputer.com.au
import ConfigParser
from bottle import route, install, run, template, static_file, PasteServer
from bottle_sqlite import SQLitePlugin
import json
import urllib
import urllib2
import datetime
config = ConfigParser.RawConfigParser()
config.read('config.... | mit | Python |
6902b88472826f6042dda6acda6f8a22d2fef64f | Change food color. | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents | enactiveagents/model/structure.py | enactiveagents/model/structure.py | """
Module that holds classes that represent structures.
"""
import world
class Structure(world.Entity):
"""
Class representing structures in the world (i.e., static but potentially
interactable with by agents).
"""
def collidable(self):
return True
class Wall(Structure):
"""
Clas... | """
Module that holds classes that represent structures.
"""
import world
class Structure(world.Entity):
"""
Class representing structures in the world (i.e., static but potentially
interactable with by agents).
"""
def collidable(self):
return True
class Wall(Structure):
"""
Clas... | mit | Python |
738ec72f78847bb31c89305247fcbe2d994117f0 | Optimize case ObjectMixin.setUp | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | feder/cases/tests.py | feder/cases/tests.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from feder.users.factories import UserFactory
from feder.main.mixins import PermissionStatusMixin
from .factories import CaseFactory
class ObjectMixin(object):
def setUp(self):
self.user = UserFactory(username="john")
se... | from django.core.urlresolvers import reverse
from django.test import RequestFactory, TestCase
from feder.monitorings.factories import MonitoringFactory
from feder.cases.models import Case
from feder.users.factories import UserFactory
from feder.institutions.factories import InstitutionFactory
from feder.main.mixins imp... | mit | Python |
8f280cece4d59e36ebfeb5486f25c7ac92718c13 | Clean it up a bit | DoublePlusGood23/lc-president-challenge | third_problem.py | third_problem.py | not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
# Remove sapces
phrase = phrase.replace(' ', '')
for char in phrase:
if char in not_vowel:
output += char # Add non vowel to output
else:
vowels += char # Add vowels to vowels
print(output)
pri... | letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
phrase = phrase.replace(' ', '')
for char in phrase:
if char in letters:
output += char
else:
vowels += char
print(output)
print(vowels) | mit | Python |
ac0d1036e56e8c24945abedbc372c717b5d7064a | improve imprort style. | lzkelley/zcode,lzkelley/zcode | zcode/constants.py | zcode/constants.py | """Common Numerical and Physical Constants.
"""
import numpy as np
import astropy as ap
import astropy.constants
import astropy.cosmology
# from astropy.cosmology import WMAP9 as cosmo
cosmo = astropy.cosmology.WMAP9
# Fundamental Constants
# ---------------------
NWTG = ap.constants.G.cgs.value
SPLC = ap.constants.c... | """Common Numerical and Physical Constants.
"""
import numpy as np
import astropy as ap
import astropy.constants
import astropy.cosmology
from astropy.cosmology import WMAP9 as cosmo
# Fundamental Constants
# ---------------------
NWTG = ap.constants.G.cgs.value
SPLC = ap.constants.c.cgs.value
MSOL = ap.constants.M_s... | mit | Python |
b64e7714e581cfc0c0a0d0f055b22c5edca27e24 | Raise KeyboardInterrupt to allow the run to handle logout | gryffon/SusumuTakuan,gryffon/SusumuTakuan | susumutakuan.py | susumutakuan.py | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
async def sigterm_handler(signum, frame):
print("Logging out...")
raise KeyboardInterrupt
print('Shutting do... | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print("Logging out...")
client.logout()
print('Shutting down...')
sy... | mit | Python |
13e30fe6af93bbb48a4795ee22f4f3ba760adc14 | add get_session_names | sk1418/retmux | tmuxback/tmux.py | tmuxback/tmux.py | # -*- coding:utf-8 -*-
import subprocess
import re
#tmux commands
#list sessions
CMD_LIST_SESSIONS='tmux list-sessions -F#S'
def get_session_names():
""" return a list of tmux session names """
s = subprocess.check_output(CMD_LIST_SESSIONS.split(' '))
s = re.sub('\n$','',s)
return s.split('\n')
#... | # -*- coding:utf-8 -*-
def get_session_names():
"""get session names"""
pass
| mit | Python |
2e382c8bff2d0c3733b9b525168254971ca1175e | Update atexit function to avoid issues with late binding | milliman/spark,milliman/spark,milliman/spark,milliman/spark,milliman/spark,milliman/spark,milliman/spark | python/pyspark/shell.py | python/pyspark/shell.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | apache-2.0 | Python |
10e6c53a39d3ee57d855ada1aa6e9d620f094465 | add 'save' command | frans-fuerst/track,frans-fuerst/track | track-cli.py | track-cli.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
import zmq
import logging
log = logging.getLogger('track_cli')
def print_info():
log.info("zeromq version: %s" % zmq.zmq_version())
log.info("pyzmq version: %s" % zmq.pyzmq_version())
def send_request(request):
context = zmq.Context()
req_so... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
import zmq
import logging
log = logging.getLogger('track_cli')
def print_info():
log.info("zeromq version: %s" % zmq.zmq_version())
log.info("pyzmq version: %s" % zmq.pyzmq_version())
def send_request(request):
context = zmq.Context()
req_so... | apache-2.0 | Python |
0dea5f2b6a2e6d702167c3415d10a47275e30601 | update the version to 0.6.0 | ronnyandersson/zignal | zignal/__init__.py | zignal/__init__.py | """
This is the zignal library
@author: Ronny Andersson (ronny@andersson.tk)
@copyright: (c) 2013 Ronny Andersson
@license: MIT
"""
__version__ = "0.6.0"
from .audio import *
from . import filters
from . import measure
from . import music
from . import sndcard
__all__ = [
'filters',
'measure',... | """
This is the zignal library
@author: Ronny Andersson (ronny@andersson.tk)
@copyright: (c) 2013 Ronny Andersson
@license: MIT
"""
__version__ = "0.5.0"
from .audio import *
from . import filters
from . import measure
from . import music
from . import sndcard
__all__ = [
'filters',
'measure',... | mit | Python |
c91240cd43c4f714a404cf5f2ce566dad290c0c5 | Add url mapping for ProjectEntrySumsAPIView | bjoernricks/trex,bjoernricks/trex | trex/urls.py | trex/urls.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... | mit | Python |
7cbee5e817b6d2bbf4fbcbf8cf1cf327bdbabc9c | rename locator_string to package_id | gymnasium/edx-platform,zadgroup/edx-platform,Softmotions/edx-platform,zubair-arbi/edx-platform,jamesblunt/edx-platform,longmen21/edx-platform,morenopc/edx-platform,mjirayu/sit_academy,IONISx/edx-platform,shubhdev/edxOnBaadal,sameetb-cuelogic/edx-platform-test,4eek/edx-platform,vasyarv/edx-platform,ahmadiga/min_edx,eduN... | cms/djangoapps/contentstore/management/commands/migrate_to_split.py | cms/djangoapps/contentstore/management/commands/migrate_to_split.py | """
Django management command to migrate a course from the old Mongo modulestore
to the new split-Mongo modulestore.
"""
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from xmodule.modulestore import Location
from xmodule.modulestore.django import modulesto... | """
Django management command to migrate a course from the old Mongo modulestore
to the new split-Mongo modulestore.
"""
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from xmodule.modulestore import Location
from xmodule.modulestore.django import modulesto... | agpl-3.0 | Python |
c61187382c968c3018f88637806874ddd0b63b71 | add log for debug | ieiayaobb/lushi8,ieiayaobb/lushi8,ieiayaobb/lushi8 | web/views.py | web/views.py | import requests
from django.http import Http404
from django.shortcuts import render, render_to_response, redirect
# Create your views here.
from django.template import RequestContext
from web.fetch import Fetcher
from settings import LEAN_CLOUD_ID, LEAN_CLOUD_SECRET
import leancloud
# @api_view(('GET',)... | import requests
from django.http import Http404
from django.shortcuts import render, render_to_response, redirect
# Create your views here.
from django.template import RequestContext
from web.fetch import Fetcher
from settings import LEAN_CLOUD_ID, LEAN_CLOUD_SECRET
import leancloud
# @api_view(('GET',)... | mit | Python |
0921f78660b7b0784ebe2fa586dd54551704699e | Fix fix_gir.py to work with ginterfaces and to support delegates. | GNOME/caribou,GNOME/caribou,GNOME/caribou | tools/fix_gir.py | tools/fix_gir.py | #!/usr/bin/python
from xml.dom import minidom
def purge_white_space_and_fix_namespace(node, indent=0):
if getattr(node, "tagName", None) == "namespace":
name = node.getAttribute("name")
node.setAttribute("name", name.lstrip('_'))
for child in [c for c in node.childNodes]:
if child.node... | #!/usr/bin/python
from xml.dom import minidom
def purge_white_space_and_fix_namespace(node, indent=0):
if getattr(node, "tagName", None) == "namespace":
name = node.getAttribute("name")
node.setAttribute("name", name.lstrip('_'))
for child in [c for c in node.childNodes]:
if child.node... | lgpl-2.1 | Python |
2c4cf38b7251ddffaba954f71bbca9632123777c | Add start_wizbit_server function that registers and publishes a wizbit server. | wizbit-archive/wizbit,wizbit-archive/wizbit | wizd/wizd.py | wizd/wizd.py | #! /usr/bin/env python
import sys
import socket
import os
import SimpleXMLRPCServer
import gobject
from wizbit import ServicePublisher, ServiceBrowser
WIZBIT_SERVER_PORT = 3492
from wizbit import Shares, Directory
from wizbit import *
class WizbitServer():
def getShares(self):
shares = Shares.getShares()
retur... | #! /usr/bin/env python
import sys
import socket
import os
import SimpleXMLRPCServer
import gobject
from wizbit import ServicePublisher, ServiceBrowser
WIZBIT_SERVER_PORT = 3492
from wizbit import Shares, Directory
from wizbit import *
class WizbitServer():
def getShares(self):
shares = Shares.getShares()
retur... | lgpl-2.1 | Python |
5258c7d70796a03361ad865a15fd3896bb7a95f1 | Fix tests | mhcomm/pypeman,Zluurk/pypeman,jrmi/pypeman,mhcomm/pypeman,Zluurk/pypeman,jrmi/pypeman,Zluurk/pypeman,jrmi/pypeman,mhcomm/pypeman | pypeman/tests/test_nodes.py | pypeman/tests/test_nodes.py | import unittest
import asyncio
import logging
class FakeChannel():
def __init__(self):
self.logger = logging.getLogger()
self.uuid = 'fakeChannel'
class NodesTests(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
#asyncio.set_event_loop(None)
def test_l... | import unittest
import asyncio
class FakeChannel():
def __init__(self):
self.uuid = 'fakeChannel'
class NodesTests(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
#asyncio.set_event_loop(None)
def test_log_node(self):
""" if Log() node is functionnal "... | apache-2.0 | Python |
175cfe45aba554d1544be3ee71bdb8a7b499d879 | add radius in request | cyplp/wtm | wtm/views.py | wtm/views.py | import urllib2
from lxml import etree
from deform import Form
from pyramid.view import view_config
from wtm.schemas.home import HomeSchema
@view_config(route_name='home', renderer='templates/home.pt')
def home(request):
"""
home page
"""
homeForm = Form(HomeSchema(), buttons=('submit',), action=req... | import urllib2
from lxml import etree
from deform import Form
from pyramid.view import view_config
from wtm.schemas.home import HomeSchema
@view_config(route_name='home', renderer='templates/home.pt')
def home(request):
"""
home page
"""
homeForm = Form(HomeSchema(), buttons=('submit',), action=req... | mit | Python |
2313a796842cbe65563a62fe12edec06c4112531 | Add YEARS_PEY_DAY. | GeoscienceAustralia/PyRate,GeoscienceAustralia/PyRate | pyrate/core/ifgconstants.py | pyrate/core/ifgconstants.py | # This Python module is part of the PyRate software package.
#
# Copyright 2017 Geoscience Australia
#
# 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/... | # This Python module is part of the PyRate software package.
#
# Copyright 2017 Geoscience Australia
#
# 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/... | apache-2.0 | Python |
d43cf2adeb5bc5e5546dbf58532bfc283fc94ea8 | fix sort order of combined citation information | rafaqz/citation.vim | python/citation_vim/item.py | python/citation_vim/item.py | # -*- coding:utf-8 -*-
import collections
from citation_vim.utils import compat_str, is_current
class Item(object):
"""
Intermediary object between bibtex/zotero and unite source output.
"""
def combine(self):
pairs = collections.OrderedDict([
('Key', self.key),
('Tit... | # -*- coding:utf-8 -*-
from citation_vim.utils import compat_str, is_current
class Item(object):
"""
Intermediary object between bibtex/zotero and unite source output.
"""
def combine(self):
pairs = {
'Key': self.key,
'Title': self.title,
'Author(s)': self... | mit | Python |
fb786e6fa254bf9b041b58ae3ba524257892bea8 | Make payloads larger for tests. | mvaled/sentry,alexm92/sentry,looker/sentry,mvaled/sentry,mvaled/sentry,looker/sentry,beeftornado/sentry,mvaled/sentry,fotinakis/sentry,ifduyue/sentry,ifduyue/sentry,looker/sentry,JackDanger/sentry,JamesMura/sentry,BuildingLink/sentry,beeftornado/sentry,alexm92/sentry,nicholasserra/sentry,imankulov/sentry,JamesMura/sent... | timelines.py | timelines.py | from sentry.utils.runner import configure
configure()
import contextlib
import functools
import logging
import random
import sys
import time
import uuid
from sentry.app import timelines
from sentry.timelines.redis import Record
logging.basicConfig(level=logging.DEBUG)
@contextlib.contextmanager
def timer(preambl... | from sentry.utils.runner import configure
configure()
import contextlib
import functools
import logging
import random
import sys
import time
import uuid
from sentry.app import timelines
from sentry.timelines.redis import Record
logging.basicConfig(level=logging.DEBUG)
@contextlib.contextmanager
def timer(preambl... | bsd-3-clause | Python |
4e3ebcf98e2bfb2cea1f92b66e5205194744482a | add level 11 | au9ustine/org.au9ustine.puzzles.pythonchallenge | pythonchallenge/level_11.py | pythonchallenge/level_11.py | import unittest
import urllib
import requests
import logging
import re
import urllib
import os
import os.path
import Image
import ImageDraw
from StringIO import StringIO
# Default is warning, it's to suppress requests INFO log
logging.basicConfig(format='%(message)s')
def solution():
url = 'http://www.pythonchal... | import unittest
import urllib
import requests
import logging
import re
import urllib
import os
import os.path
import Image
import ImageDraw
# Default is warning, it's to suppress requests INFO log
logging.basicConfig(format='%(message)s')
def solution():
url = 'http://www.pythonchallenge.com/pc/return/cave.jpg'
... | mit | Python |
fb5ad293c34387b1ab7b7b7df3aed3942fdd9282 | Add default to max_places in proposal form | hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web | src/webapp/activities/forms.py | src/webapp/activities/forms.py | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... | agpl-3.0 | Python |
3b5f322d8fe76251b322b2d81cecf6abbee5e4bd | rename python class method | intel-analytics/BigDL,intel-analytics/BigDL,yangw1234/BigDL,yangw1234/BigDL,yangw1234/BigDL,intel-analytics/BigDL,yangw1234/BigDL,intel-analytics/BigDL | python/dllib/src/bigdl/dllib/feature/image/imagePreprocessing.py | python/dllib/src/bigdl/dllib/feature/image/imagePreprocessing.py | #
# Copyright 2016 The BigDL Authors.
#
# 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 ... | #
# Copyright 2016 The BigDL Authors.
#
# 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 ... | apache-2.0 | Python |
6a84b885be67e8a9f424c2b36f50e8fe9347dbc9 | Remove duplicate constant in ipmi.py | eliran-stratoscale/rackattack-physical,Stratoscale/rackattack-physical,eliran-stratoscale/rackattack-physical,Stratoscale/rackattack-physical | rackattack/physical/ipmi.py | rackattack/physical/ipmi.py | import subprocess
import time
import logging
import multiprocessing.pool
class IPMI:
IPMITOOL_FILENAME = "ipmitool"
_CONCURRENCY = 4
_pool = None
def __init__(self, hostname, username, password):
self._hostname = hostname
self._username = username
self._password = password
... | import subprocess
import time
import logging
import multiprocessing.pool
class IPMI:
IPMITOOL_FILENAME = "ipmitool"
_CONCURRENCY = 4
IPMITOOL_FILENAME = "ipmitool"
_pool = None
def __init__(self, hostname, username, password):
self._hostname = hostname
self._username = username
... | apache-2.0 | Python |
356a7c4d83a5289e7b30a07b0f76829e274b7481 | Fix Eventlet transport on Python 3 | lepture/raven-python,akalipetis/raven-python,jmp0xf/raven-python,getsentry/raven-python,jmagnusson/raven-python,recht/raven-python,johansteffner/raven-python,danriti/raven-python,getsentry/raven-python,dbravender/raven-python,jmagnusson/raven-python,ronaldevers/raven-python,johansteffner/raven-python,danriti/raven-pyth... | raven/transport/eventlet.py | raven/transport/eventlet.py | """
raven.transport.eventlet
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import sys
from raven.transport.http import HTTPTransport
try:
import eventlet
try:
... | """
raven.transport.eventlet
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import sys
from raven.transport.http import HTTPTransport
try:
import eventlet
from eventl... | bsd-3-clause | Python |
b30befbf39009ed566dbb7ff725de05bad2be990 | Add link to permissions management doc for ExportTables. (#520) | all-of-us/raw-data-repository,all-of-us/raw-data-repository,all-of-us/raw-data-repository | rdr_client/export_tables.py | rdr_client/export_tables.py | # Exports the entire contents of database tables to Unicode CSV files stored in GCS.
# Used instead of Cloud SQL export because it handles newlines and null characters properly.
#
# Documentation of permissions management:
# https://docs.google.com/document/d/1vKiu2zcSy97DQTIuSezr030kTyeDthome9XzNy98B6M
#
# Usage: ./ru... | # Exports the entire contents of database tables to Unicode CSV files stored in GCS.
# Used instead of Cloud SQL export because it handles newlines and null characters properly.
#
# Usage: ./run_client.sh --project <PROJECT> --account <ACCOUNT> \
# --service_account exporter@<PROJECT>.iam.gserviceaccount.com export_tab... | bsd-3-clause | Python |
f210ef3e6b4122c75b4df9eee6be6ee4ac81efa4 | Remove a useless table from the db | dubzzz/py-mymoney,dubzzz/py-mymoney,dubzzz/py-mymoney | www/scripts/generate_db.py | www/scripts/generate_db.py | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
import sys
from os import path
SCRIPT_PATH = path.dirname(__file__)
DEFAULT_DB = path.join(SCRIPT_PATH, "../mymoney.db")
def generate_tables(db=DEFAULT_D... | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
import sys
from os import path
SCRIPT_PATH = path.dirname(__file__)
DEFAULT_DB = path.join(SCRIPT_PATH, "../mymoney.db")
def generate_tables(db=DEFAULT_D... | mit | Python |
c02036f26bfd1eb6b1fed2dc10c73c91e97dae0b | Update __init__.py | r0h4n/node-agent,Tendrl/node_agent,Tendrl/node_agent,Tendrl/node-agent,Tendrl/node-agent,Tendrl/node-agent,r0h4n/node-agent,r0h4n/node-agent | tendrl/node_agent/objects/cluster_message/__init__.py | tendrl/node_agent/objects/cluster_message/__init__.py | from tendrl.commons import etcdobj
from tendrl.commons.message import Message as message
from tendrl.commons import objects
class ClusterMessage(objects.BaseObject, message):
internal = True
def __init__(self, **cluster_message):
self._defs = {}
message.__init__(self, **cluster_message)
... | from tendrl.commons import etcdobj
from tendrl.commons.message import Message as message
from tendrl.commons import objects
class ClusterMessage(message, objects.BaseObject):
internal = True
def __init__(self, **cluster_message):
self._defs = {}
super(ClusterMessage, self).__init__(**cluster_m... | lgpl-2.1 | Python |
551dddbb80d512ec49d8a422b52c24e98c97b38c | Add waiting for new data to parse | m4tx/techswarm-receiver | tsparser/main.py | tsparser/main.py | from time import sleep
from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_... | from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_file: file to read inpu... | mit | Python |
d2a0c928b9cdb693ca75731e1ae2cefb4c7ae722 | fix Episode JSON export | tvd-dataset/tvd | tvd/core/json.py | tvd/core/json.py | #!/usr/bin/env python
# encoding: utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2013-2014 CNRS (Hervé BREDIN -- http://herve.niderb.fr/)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software... | #!/usr/bin/env python
# encoding: utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2013-2014 CNRS (Hervé BREDIN -- http://herve.niderb.fr/)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software... | mit | Python |
cd4da2e0fbed7bbadd4b110f45b7356795075aeb | add min_level to Logger | wearpants/twiggy,wearpants/twiggy | twiggy/Logger.py | twiggy/Logger.py | from Message import Message
import Levels
class Logger(object):
__slots__ = ['_fields', 'emitters', 'min_level']
def __init__(self, fields = None, emitters = None, min_level = Levels.DEBUG):
self._fields = fields if fields is not None else {}
self.emitters = emitters if emitters is not None el... | from Message import Message
import Levels
class Logger(object):
__slots__ = ['_fields', 'emitters']
def __init__(self, fields = None, emitters = None):
self._fields = fields if fields is not None else {}
self.emitters = emitters if emitters is not None else {}
def fields(self, **kwargs):
... | bsd-3-clause | Python |
04f2c9005a04559a48ad0919b840d709c0f4eeaa | Update version. | itdxer/neupy,itdxer/neupy,itdxer/neupy,stczhc/neupy,stczhc/neupy,stczhc/neupy,stczhc/neupy,itdxer/neupy | neupy/__init__.py | neupy/__init__.py | """
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.1.1'
| """
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.1.1a'
| mit | Python |
b2859bfde66d7d91f98e3cfb61e205c1d2f5dbfe | Make CommentFactory use fuzzy attrs | NiGhTTraX/hackernews-scraper | hackernews_scraper/test/factories.py | hackernews_scraper/test/factories.py | from datetime import datetime, timedelta
import factory
from factory.fuzzy import FuzzyText, FuzzyInteger
import time
class ItemFactory(factory.Factory):
FACTORY_FOR = dict
objectID = 21
created_at_i = 42
title = "Test item"
class CommentFactory(factory.Factory):
FACTORY_FOR = dict
@factor... | import factory
class ItemFactory(factory.Factory):
FACTORY_FOR = dict
objectID = 21
created_at_i = 42
title = "Test item"
class CommentFactory(factory.Factory):
FACTORY_FOR = dict
created_at = "2014-04-03T10:17:28.000Z"
title = "Test comment"
url = "www.google.com"
comment_text... | bsd-2-clause | Python |
5e1e0ba1dca301eb597fb319c68280f7ee761037 | Add twopeasandtheirpod and simplyrecipes to __init__ | hhursev/recipe-scraper | recipe_scrapers/__init__.py | recipe_scrapers/__init__.py | import re
from .allrecipes import AllRecipes
from .simplyrecipes import SimplyRecipes
from .twopeasandtheirpod import TwoPeasAndTheirPod
SCRAPERS = {
AllRecipes.host(): AllRecipes,
SimplyRecipes.host(): SimplyRecipes,
TwoPeasAndTheirPod.host(): TwoPeasAndTheirPod,
}
def url_path_to_dict(path):
patt... | import re
from .allrecipes import AllRecipes
SCRAPERS = {
AllRecipes.host(): AllRecipes,
}
def url_path_to_dict(path):
pattern = (r'^'
r'((?P<schema>.+?)://)?'
r'((?P<user>.+?)(:(?P<password>.*?))?@)?'
r'(?P<host>.*?)'
r'(:(?P<port>\d+?))?'
... | mit | Python |
5fd70e01f648da6dfc994bfe0e5c666c69fa9e45 | return None (null) in preference to empty string when recipe yield is unavailable | hhursev/recipe-scraper | recipe_scrapers/vegolosi.py | recipe_scrapers/vegolosi.py | from ._abstract import AbstractScraper
from ._utils import get_minutes, get_yields, normalize_string
class Vegolosi(AbstractScraper):
@classmethod
def host(cls):
return "vegolosi.it"
def title(self):
return self.soup.find("h1").get_text().strip()
def preparation_time(self):
p... | from ._abstract import AbstractScraper
from ._utils import get_minutes, get_yields, normalize_string
class Vegolosi(AbstractScraper):
@classmethod
def host(cls):
return "vegolosi.it"
def title(self):
return self.soup.find("h1").get_text().strip()
def preparation_time(self):
p... | mit | Python |
631270eeafad8fd6b20973673f6d6e8b733e9029 | enable email | doubleDragon/QuantBot | quant/tool/email_box.py | quant/tool/email_box.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from email.mime.text import MIMEText
from quant import config
import smtplib
mail_to = ["aiai373824745_wy@163.com"]
mail_host = "smtp.163.com"
mail_user = "aiai373824745_wy@163.com"
'''163邮箱smtp生成的密码'''
mail_pass = config.EMAIL_PASSWORD_163
mail_subject = 'logging'
def ... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from email.mime.text import MIMEText
from quant import config
import smtplib
mail_to = ["aiai373824745_wy@163.com"]
mail_host = "smtp.163.com"
mail_user = "aiai373824745_wy@163.com"
'''163邮箱smtp生成的密码'''
mail_pass = config.EMAIL_PASSWORD_163
mail_subject = 'logging'
def ... | mit | Python |
0caec903579e4cf3f22ea3e5ea1df3ecd8ad0fe3 | remove nigthly test hgemm_asm | ROCmSoftwarePlatform/Tensile,ROCmSoftwarePlatform/Tensile,ROCmSoftwarePlatform/Tensile | test/nightly.py | test/nightly.py | #
# These nightly tests are slow but have good coverage. Fast tests with less coverage are in pre_checkin.py.
#
# To execute this test file, apt-get install python-pytest, then
# PYTHONPATH=. py.test -v test/nightly.py
#
# To run test directly, with complete output:
# mkdir build && cd build
# python ../Tensile/T... | #
# These nightly tests are slow but have good coverage. Fast tests with less coverage are in pre_checkin.py.
#
# To execute this test file, apt-get install python-pytest, then
# PYTHONPATH=. py.test -v test/nightly.py
#
# To run test directly, with complete output:
# mkdir build && cd build
# python ../Tensile/T... | mit | Python |
94fc7881052fea4e7d83f35e41fab4f5ed108f34 | fix styling | rmorshea/spectate | spectate/utils.py | spectate/utils.py | class Sentinel:
__slots__ = "_name"
def __init__(self, name):
self._name = name
def __repr__(self):
return self._name # pragma: no cover
| from collections.abc import Mapping
class Sentinel:
__slots__ = "_name"
def __init__(self, name):
self._name = name
def __repr__(self):
return self._name # pragma: no cover
| mit | Python |
7329757e1ad30e327c1ae823a8302c79482d6b9c | Update BUILD_OSS to 4632 | fcitx/mozc,google/mozc,google/mozc,google/mozc,fcitx/mozc,fcitx/mozc,google/mozc,google/mozc,fcitx/mozc,fcitx/mozc | src/data/version/mozc_version_template.bzl | src/data/version/mozc_version_template.bzl | # Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | # Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | bsd-3-clause | Python |
e243e907e58047e18c0a16e061f7aa718e3b5854 | Remove unavailable imports | bashtage/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,jseabold/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,jseabold/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/stat... | statsmodels/compat/__init__.py | statsmodels/compat/__init__.py | from .python import ( # noqa:F401
PY3, PY37,
bytes, str, unicode, string_types,
asunicode, asbytes, asstr, asstr2,
range, zip, filter, map,
lrange, lzip, lmap, lfilter,
cStringIO, StringIO, BytesIO,
cPickle, pickle,
iteritems, iterkeys, itervalues,
urlopen, urljoin, urlencode, HTTPE... | from .python import ( # noqa:F401
PY3, PY37,
bytes, str, unicode, string_types,
asunicode, asbytes, asstr, asstr2, asunicode_nested, asbytes_nested,
range, zip, filter, map,
lrange, lzip, lmap, lfilter,
cStringIO, StringIO, BytesIO,
cPickle, pickle,
iteritems, iterkeys, itervalues,
... | bsd-3-clause | Python |
0629b30ade8b619697e8cc28d651904e742cd70e | Correct inst method names in system info, add Docker version (#36360) | GenericStudent/home-assistant,tboyce1/home-assistant,home-assistant/home-assistant,nkgilley/home-assistant,soldag/home-assistant,Danielhiversen/home-assistant,partofthething/home-assistant,mezz64/home-assistant,pschmitt/home-assistant,w1ll1am23/home-assistant,w1ll1am23/home-assistant,mKeRix/home-assistant,mKeRix/home-a... | homeassistant/helpers/system_info.py | homeassistant/helpers/system_info.py | """Helper to gather system info."""
import os
import platform
from typing import Dict
from homeassistant.const import __version__ as current_version
from homeassistant.loader import bind_hass
from homeassistant.util.package import is_virtual_env
from .typing import HomeAssistantType
@bind_hass
async def async_get_s... | """Helper to gather system info."""
import os
import platform
from typing import Dict
from homeassistant.const import __version__ as current_version
from homeassistant.loader import bind_hass
from homeassistant.util.package import is_virtual_env
from .typing import HomeAssistantType
@bind_hass
async def async_get_s... | apache-2.0 | Python |
c1b19af7229d582f7bd474a05a679cf45e3c9bf8 | add proxy + fix import modules | nrivet84/ig | tests/basics.py | tests/basics.py | # -*- coding: utf-8 -*-
"""
@author: Nicolas Rivet
test the connection to IG API
do some basic operations
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'ig')))
import ig_service as igs
import ig_tools as igt
def main():
"""Main module for... | # -*- coding: utf-8 -*-
"""
@author: Nicolas Rivet
test the connection to IG API
do some basic operations
"""
from ig.ig_service import IGservice as igs
import ig.ig_tools as igt
def main():
"""Main module for testing."""
#get config for demo API
proxy_user, proxy_password, api_key, use... | mit | Python |
d23a68d464c62cdefb76dbe5855110374680ae61 | Add coverage metrics to python code | willbarton/regulations-site,ascott1/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,grapesmoker/regulations-site,adderall/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,EricSchles/regulations-site,EricSchles/regulations-site,grapesmoker/regul... | regulations/settings/dev.py | regulations/settings/dev.py | from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATICFILES_DIRS = (
root('static'),
)
OFFLINE_OUTPUT_DIR = '/tmp/'
INSTALLED_APPS += (
'django_nose',
)
NOSE_ARGS = [
'--with-coverage',
'--cover-package=regulations',
'--exclude-dir=regulations/uitests'
]
try:
from local_settings i... | from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
STATICFILES_DIRS = (
root('static'),
)
OFFLINE_OUTPUT_DIR = '/tmp/'
INSTALLED_APPS += (
'django_nose',
)
NOSE_ARGS = [
'--exclude-dir=regulations/uitests'
]
try:
from local_settings import *
except ImportError:
pass
| cc0-1.0 | Python |
8cc36a325e8bedb7894f31fe049aee1aef903811 | remove unused code | dennisobrien/bokeh,timsnyder/bokeh,aavanian/bokeh,philippjfr/bokeh,ericmjl/bokeh,schoolie/bokeh,ptitjano/bokeh,stonebig/bokeh,rs2/bokeh,jakirkham/bokeh,gpfreitas/bokeh,percyfal/bokeh,aavanian/bokeh,stonebig/bokeh,msarahan/bokeh,ptitjano/bokeh,schoolie/bokeh,quasiben/bokeh,azjps/bokeh,percyfal/bokeh,jakirkham/bokeh,htyg... | examples/glyphs/buttons_server.py | examples/glyphs/buttons_server.py | from __future__ import print_function
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.plotting import curdoc
from bokeh.models.widgets import (
VBox, Icon,
Button, Toggle, Dropdown,
CheckboxGroup, RadioGroup,
CheckboxButtonGroup, RadioButtonGroup,
)
from bokeh.client i... | from __future__ import print_function
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.plotting import curdoc
from bokeh.models.widgets import (
VBox, Icon,
Button, Toggle, Dropdown,
CheckboxGroup, RadioGroup,
CheckboxButtonGroup, RadioButtonGroup,
)
from bokeh.models i... | bsd-3-clause | Python |
93cab6327aef7386dba6f293a22099272af6af10 | create resouce only if not exist | oVirt/ovirt-engine-sdk-tests | src/infrastructure/annotations/requires.py | src/infrastructure/annotations/requires.py | '''
Created on Jun 19, 2013
@author: mpastern
'''
from src.resource.resourcemanager import ResourceManager
from src.errors.resourcemanagernotfounderror import ResourceManagerNotFoundError
class resources(object):
def __init__(self, params):
self.params = params
def __call__(self, original_func):
... | '''
Created on Jun 19, 2013
@author: mpastern
'''
from src.resource.resourcemanager import ResourceManager
from src.errors.resourcemanagernotfounderror import ResourceManagerNotFoundError
class resources(object):
def __init__(self, params):
self.params = params
def __call__(self, original_func):
... | apache-2.0 | Python |
71b4c326e18ce7e3d0b6aaab5203b3a403a85810 | Update solution_2.py | DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectEuler,DestructHub/ProjectE... | Problem033/Python/solution_2.py | Problem033/Python/solution_2.py | import math
frac=1.0
for b in range(1,10):
for a in range(1,b):
for c in range(1,10):
if (a*10+b)/(b*10+c)==a/c:
frac*=(a/c)
print(math.ceil(1/frac))
| import math
frac=1.0
for b in range(1,10):
for a in range(1,b):
for c in range(1,10):
if (a*10+b)/(b*10+c)==a/c:
frac*=(a/c)
print(math.ceil(1/frac))
| mit | Python |
6d7e597ce216093d52ecdcb7db5c087dc6040bb1 | Fix initiation of settings object | jonge-democraten/mezzanine-fullcalendar | fullcalendar/conf.py | fullcalendar/conf.py | from datetime import timedelta
from django.conf import settings as django_settings
default = {
'FULLCALENDAR_FIRST_WEEKDAY': 0,
'FULLCALENDAR_OCCURRENCE_DURATION': timedelta(hours=1),
'FULLCALENDAR_SITE_COLORS': {}
}
settings = type('SettingsDummy', (), default)
for key, value in default.items():
se... | from datetime import timedelta
from django.conf import settings as django_settings
default = {
'FULLCALENDAR_FIRST_WEEKDAY': 0,
'FULLCALENDAR_OCCURRENCE_DURATION': timedelta(hours=1),
'FULLCALENDAR_SITE_COLORS': {}
}
settings = object()
for key, value in default.items():
setattr(settings, key,
... | mit | Python |
52e614f811fb9dfcd0dde46de43f13731a3717a5 | Reformat doc string for txStatHat.__init__ | hynek/txStatHat | txstathat.py | txstathat.py | # -*- coding: utf-8 -*-
"""StatHat bindings"""
from __future__ import division, print_function, unicode_literals
import urllib
from twisted.web.client import getPage
try:
from OpenSSL import SSL # noqa
have_ssl = True
except:
have_ssl = False
API_URI = b'http{}://api.stathat.com/ez'.format(b's' if h... | # -*- coding: utf-8 -*-
"""StatHat bindings"""
from __future__ import division, print_function, unicode_literals
import urllib
from twisted.web.client import getPage
try:
from OpenSSL import SSL # noqa
have_ssl = True
except:
have_ssl = False
API_URI = b'http{}://api.stathat.com/ez'.format(b's' if h... | mit | Python |
b2b123b15f178e81737127a4dda399a31ebb5240 | Update Dice_Probability.py | LamaHamadeh/Harvard-PH526x | Week2-Python-Libraries-and-Concepts-Used-in-Research/Dice_Probability.py | Week2-Python-Libraries-and-Concepts-Used-in-Research/Dice_Probability.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 16:26:48 2017
@author: lamahamadeh
"""
#First: Python-based implementation
#------------------------------------
'''
source:
-------
Video 2.4.2: Examples Involving Randomness
Week 2 Overview/Python Libraries and Concepts Used in Research
Using... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 16:26:48 2017
@author: lamahamadeh
source:
-------
Video 2.4.2: Examples Involving Randomness
Week 2 Overview/Python Libraries and Concepts Used in Research
Using python for research
Harvard
online course provided by edx.org
url: https://courses... | mit | Python |
67c4d077ee4693290bf9883e90e4ed381b3cd227 | Fix a mistake. | jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets | python/matplotlib/hist_logscale_xy.py | python/matplotlib/hist_logscale_xy.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See:
# -
import numpy as np
import matplotlib.pyplot as plt
# SETUP #######################################################################
# histtype : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’]
HIST_TYPE='bar'
ALPHA=0.5
# MAKE DATA ###########################... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See:
# -
import numpy as np
import matplotlib.pyplot as plt
# SETUP #######################################################################
# histtype : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’]
HIST_TYPE='bar'
ALPHA=0.5
# MAKE DATA ###########################... | mit | Python |
e300d739bf0040b76a0deee75cc01b1410ba8953 | change image field to name in CatalogoLandsat serializer | ibamacsr/indicar_process,ibamacsr/indicar_process,ibamacsr/indicar_process,ibamacsr/indicar-process,ibamacsr/indicar-process | indicarprocess/tmsapi/serializers.py | indicarprocess/tmsapi/serializers.py | # -*- coding: utf-8 -*-
from rest_framework.serializers import ModelSerializer, SerializerMethodField
from catalogo.models import CatalogoLandsat
class LandsatSerializer(ModelSerializer):
southwest = SerializerMethodField()
northeast = SerializerMethodField()
name = SerializerMethodField()
class Met... | # -*- coding: utf-8 -*-
from rest_framework.serializers import ModelSerializer, SerializerMethodField
from catalogo.models import CatalogoLandsat
class LandsatSerializer(ModelSerializer):
southwest = SerializerMethodField()
northeast = SerializerMethodField()
class Meta:
model = CatalogoLandsat
... | agpl-3.0 | Python |
05a8f2a2e499b25472fbaf1b06e899f589a7101f | fix migration | CivicKnowledge/metaeditor,CivicKnowledge/metaeditor,CivicKnowledge/metaeditor | editor/migrations/0003_auto_20150125_0430.py | editor/migrations/0003_auto_20150125_0430.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from editor.models import Source, Category, Format
# add root data for Source and Category model
def add_root_data(apps, schema_editor):
cat = Category(name ="root", parent=None)
cat.save()
source = S... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from editor.models import Source, Category
# add root data for Source and Category model
def add_root_data(apps, schema_editor):
cat = Category(name ="root", parent=None)
cat.save()
source = Source(
... | mit | Python |
53df723a1574e62b4a74d56667c131793cf6c506 | add retrieve all users and one user queries | sebasvega95/dist-systems-chat,sebasvega95/dist-systems-chat,sebasvega95/dist-systems-chat | users_handler.py | users_handler.py | from models.users import User
import logging
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
class UsersHandler:
def __init__(self, DB):
self.db = DB
def create_user(self, user_data):
collection = self.db.users
user = collection.find_one({"username": user... | from models.users import User
class UsersHandler:
def __init__(self, DB):
self.db = DB
def create_user(self, user_data):
collection = self.db.users
new_user = User(user_data)
collection.insert_one(new_user.__dict__)
| mit | Python |
7674437d752be0791688533dd1409fa083672bb2 | Switch from dictionary to namedtuple | hatchery/Genepool2,hatchery/genepool | genes/java/config.py | genes/java/config.py | #!/usr/bin/env python
from collections import namedtuple
JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version'])
def config():
return JavaConfig(
is_oracle=True,
version='oracle-java8',
)
| #!/usr/bin/env python
def config():
return {
'is-oracle': True,
'version': 'oracle-java8',
}
| mit | Python |
becf684fc06890679f4c0cdfed1761962e16a343 | Make extra_context at browse_repository view not overriding provided variables | codeinn/vcs,codeinn/vcs | vcs/web/simplevcs/views/repository.py | vcs/web/simplevcs/views/repository.py | from django.contrib import messages
from django.template import RequestContext
from django.shortcuts import render_to_response
from vcs.exceptions import VCSError
def browse_repository(request, repository, template_name, revision=None,
node_path='', extra_context={}):
"""
Generic repository browser.
... | from django.contrib import messages
from django.template import RequestContext
from django.shortcuts import render_to_response
from vcs.exceptions import VCSError
def browse_repository(request, repository, template_name, revision=None,
node_path='', extra_context={}):
"""
Generic repository browser.
... | mit | Python |
7ecaeba33a4fe559f6122953581e533720cb2404 | Add select mkl libs (#22580) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/intel-oneapi-mkl/package.py | var/spack/repos/builtin/packages/intel-oneapi-mkl/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from sys import platform
from spack import *
class IntelOneapiMkl(IntelOneApiLibraryPackage):
"""Intel oneAPI MKL.... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from sys import platform
from spack import *
class IntelOneapiMkl(IntelOneApiLibraryPackage):
"""Intel oneAPI MKL.... | lgpl-2.1 | Python |
67cea85323195440330580cc3731447956a4ad32 | add default user settings packet | nullpixel/litecord,nullpixel/litecord | litecord/managers/user_settings.py | litecord/managers/user_settings.py |
class SettingsManager:
"""User settings manager.
Provides functions for users to change their settings and retrieve them back.
Attributes
----------
server: :class:`LitecordServer`
Litecord server instance.
settings_coll: `mongo collection`
User settings MongoDB collection... |
class SettingsManager:
"""User settings manager.
Provides functions for users to change their settings and retrieve them back.
Attributes
----------
server: :class:`LitecordServer`
Litecord server instance.
settings_coll: `mongo collection`
User settings MongoDB collection... | mit | Python |
603a59785f24aa98662e72d954b3aa0521ad0629 | Make repeatability tests for severities specified by CLI | RianFuro/vint,Kuniwak/vint,Kuniwak/vint,RianFuro/vint | test/unit/vint/linting/config/test_config_cmdargs_source.py | test/unit/vint/linting/config/test_config_cmdargs_source.py | import unittest
from test.asserting.config_source import ConfigSourceAssertion
from vint.linting.config.config_cmdargs_source import ConfigCmdargsSource
from vint.linting.level import Level
class TestConfigFileSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
env = {
... | import unittest
from test.asserting.config_source import ConfigSourceAssertion
from vint.linting.config.config_cmdargs_source import ConfigCmdargsSource
from vint.linting.level import Level
class TestConfigFileSource(ConfigSourceAssertion, unittest.TestCase):
def test_get_config_dict(self):
expected_conf... | mit | Python |
54cea5e302820c35025e1afc64b2058a48c5b174 | Implement pop in the data storage module | DesertBot/DesertBot | desertbot/datastore.py | desertbot/datastore.py | import json
import os
class DataStore(object):
def __init__(self, storagePath, defaultsPath):
self.storagePath = storagePath
self.defaultsPath = defaultsPath
self.data = {}
self.load()
def load(self):
# if a file data/defaults/<module>.json exists, it has priority on l... | import json
import os
class DataStore(object):
def __init__(self, storagePath, defaultsPath):
self.storagePath = storagePath
self.defaultsPath = defaultsPath
self.data = {}
self.load()
def load(self):
# if a file data/defaults/<module>.json exists, it has priority on l... | mit | Python |
e3753ac4b2c24c43014aab8121a34b9ad76d6b7a | update tests to v2.1.1 (#1597) (#1597) | smalley/python,N-Parsons/exercism-python,behrtam/xpython,jmluy/xpython,smalley/python,behrtam/xpython,exercism/xpython,exercism/python,N-Parsons/exercism-python,exercism/python,exercism/xpython,jmluy/xpython | exercises/hamming/hamming_test.py | exercises/hamming/hamming_test.py | import unittest
import hamming
# Tests adapted from `problem-specifications//canonical-data.json` @ v2.1.1
class HammingTest(unittest.TestCase):
def test_empty_strands(self):
self.assertEqual(hamming.distance("", ""), 0)
def test_identical_strands(self):
self.assertEqual(hamming.distance("... | import unittest
import hamming
# Tests adapted from `problem-specifications//canonical-data.json` @ v2.1.0
class HammingTest(unittest.TestCase):
def test_empty_strands(self):
self.assertEqual(hamming.distance("", ""), 0)
def test_identical_strands(self):
self.assertEqual(hamming.distance("... | mit | Python |
d47cfd7c1a4dd22ab175539dcb0e3702a21f8bb7 | Move scaling factors to constant and explain | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ynr/apps/moderation_queue/management/commands/moderation_queue_detect_faces_in_queued_images.py | ynr/apps/moderation_queue/management/commands/moderation_queue_detect_faces_in_queued_images.py | import json
import boto3
from django.core.management.base import BaseCommand, CommandError
from moderation_queue.models import QueuedImage
# These magic values are because the AWS API crops faces quite tightly by
# default, meaning we literally just get the face. These values are about
# right or, they are more ri... | import json
import boto3
from django.core.management.base import BaseCommand, CommandError
from moderation_queue.models import QueuedImage
class Command(BaseCommand):
def handle(self, **options):
rekognition = boto3.client("rekognition", "eu-west-1")
attributes = ["ALL"]
any_failed = ... | agpl-3.0 | Python |
a0e0f7867e8e9805fb035a8db75e9d187fc06f3b | fix merge | PhilipGarnero/django-rest-framework-social-oauth2,villoid/django-rest-framework-social-oauth2 | rest_framework_social_oauth2/views.py | rest_framework_social_oauth2/views.py | # -*- coding: utf-8 -*-
import json
from braces.views import CsrfExemptMixin
from oauth2_provider.ext.rest_framework import OAuth2Authentication
from oauth2_provider.models import Application, AccessToken
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views.mixins import OAuthLibMixin
from r... | # -*- coding: utf-8 -*-
import json
from braces.views import CsrfExemptMixin
from oauth2_provider.ext.rest_framework import OAuth2Authentication
from oauth2_provider.models import Application, AccessToken
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views.mixins import OAuthLibMixin
from r... | mit | Python |
e13a74ae4e1884017593143e01e8882d7e802d7b | clean up imports | compas-dev/compas | src/compas_rhino/geometry/__init__.py | src/compas_rhino/geometry/__init__.py | """
********************************************************************************
geometry
********************************************************************************
.. currentmodule:: compas_rhino.geometry
"""
from __future__ import absolute_import
__all__ = []
| """
********************************************************************************
geometry
********************************************************************************
.. currentmodule:: compas_rhino.geometry
Classes
=======
.. autosummary::
:toctree: generated/
:nosignatures:
RhinoGeometry
R... | mit | Python |
3fb93c4b839457430180f65f1feae4c7abdba0ac | tag celery syslog messages | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | dbaas/dbaas/celery.py | dbaas/dbaas/celery.py | from __future__ import absolute_import
import os
import logging
from datetime import timedelta
from celery import Celery
from django.conf import settings
from dbaas import celeryconfig
from logging.handlers import SysLogHandler
from celery.log import redirect_stdouts_to_logger
from celery.signals import after_setu... | from __future__ import absolute_import
import os
import logging
from datetime import timedelta
from celery import Celery
from django.conf import settings
from dbaas import celeryconfig
from logging.handlers import SysLogHandler
from celery.log import redirect_stdouts_to_logger
from celery.signals import after_setu... | bsd-3-clause | Python |
c0f917c6098b18479a69fe129a0fd19d11f67df7 | Fix startup | paulkramme/btsoot | src/btsoot.py | src/btsoot.py | #!/usr/bin/env python3.5
#MIT License
#
#Copyright (c) 2016 Paul Kramme
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, co... | bsd-3-clause | Python | |
21620653125f33fd0d19c1bb2f16b51ec3c853f9 | fix tmin/tmax | teuben/masc,teuben/pyASC,teuben/masc,warnerem/pyASC,teuben/pyASC,teuben/pyASC,teuben/pyASC,warnerem/pyASC,warnerem/pyASC,warnerem/pyASC,teuben/pyASC,teuben/pyASC,warnerem/pyASC,teuben/pyASC,warnerem/pyASC,teuben/masc,warnerem/pyASC | ASC/SkyPie.py | ASC/SkyPie.py | #! /usr/bin/env python
#
# Takes about 15" for 1400 images on laptop with a local fast disk (100% cpu)
# But 60" on the Xeon, but at 300% cpu
#
import matplotlib.pyplot as plt
import numpy as np
import sys
table = sys.argv[1]
png = table + '.png'
twopi = 2*np.pi
# table of decimal hour time and median sky brightn... | #! /usr/bin/env python
#
# Takes about 15" fpr 1400 images on laptop with a local fast disk
#
import matplotlib.pyplot as plt
import numpy as np
import sys
date = ''
table = sys.argv[1]
png = table + '.png'
twopi = 2*np.pi
# table of time index (1...N) and median sky brightness (50,000 is very bright)
(t,s) = np.... | mit | Python |
d84034db71abac46ef765f1640f3efa6712f5c42 | Update RegisterHandler.py | emeric254/gala-stri-website,emeric254/gala-stri-website,emeric254/gala-stri-website | Handlers/RegisterHandler.py | Handlers/RegisterHandler.py | # -*- coding: utf-8 -*-
import logging
from Handlers.BaseHandler import BaseHandler
from Tools import PostgreSQL, VerifyFields
logger = logging.getLogger(__name__)
class RegisterHandler(BaseHandler):
"""handle / endpoint"""
def get(self):
"""Serve Get and return main page"""
self.render('re... | # -*- coding: utf-8 -*-
import logging
from Handlers.BaseHandler import BaseHandler
from Tools import PostgreSQL, VerifyFields
logger = logging.getLogger(__name__)
class RegisterHandler(BaseHandler):
"""handle / endpoint"""
def initialize(self):
self.conn = PostgreSQL.get_session()
def get(sel... | mit | Python |
0aaa9000f8cf545bd5bfa41b6538d56c91dbde97 | Update base box in sample config too | f-droid/fdroid-server,f-droid/fdroid-server,f-droid/fdroid-server,matlink/fdroidserver,matlink/fdroidserver,fdroidtravis/fdroidserver,matlink/fdroidserver,OneEducation/AppUniverse_Server,f-droid/fdroid-server,OneEducation/AppUniverse_Server,f-droid/fdroidserver,f-droid/fdroidserver,matlink/fdroidserver,f-droid/fdroidse... | sampleconfigs/makebs.config.sample.py | sampleconfigs/makebs.config.sample.py | #!/usr/bin/env python2
# You will need to alter these before running ./makebuildserver
# Name of the base box to use...
basebox = "testing32"
# Location where raring32.box can be found, if you don't already have
# it. For security reasons, it's recommended that you make your own
# in a secure environment using trust... | #!/usr/bin/env python2
# You will need to alter these before running ./makebuildserver
# Name of the base box to use...
basebox = "raring32"
# Location where raring32.box can be found, if you don't already have
# it. Could be set to https://f-droid.org/raring32.box if you like...
baseboxurl = "/shares/software/OS an... | agpl-3.0 | Python |
32aec3e5595fe0868b77260cb64be718d4e7f3b8 | Update Keras.py | paperrune/Neural-Networks,paperrune/Neural-Networks | Momentum/Keras.py | Momentum/Keras.py | from keras.datasets import mnist
from keras.initializers import RandomUniform
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import SGD
from keras.utils import to_categorical
batch_size = 128
epochs = 30
learning_rate = 0.1
momentum = 0.9
num_classes = 10
(x_trai... | from keras.datasets import mnist
from keras.initializers import RandomUniform
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import SGD
from keras.utils import to_categorical
batch_size = 128
epochs = 30
learning_rate = 0.1
momentum = 0.9
num_classes = 10
(x_trai... | mit | Python |
aa6090b69f64721391dec38de04e8d01d23c48bf | Add tests for differential calculus methods | kaichogami/sympy,lindsayad/sympy,jbbskinny/sympy,Titan-C/sympy,Titan-C/sympy,wanglongqi/sympy,Vishluck/sympy,Shaswat27/sympy,Shaswat27/sympy,drufat/sympy,debugger22/sympy,rahuldan/sympy,Davidjohnwilson/sympy,sahmed95/sympy,sampadsaha5/sympy,Shaswat27/sympy,ahhda/sympy,AkademieOlympia/sympy,farhaanbukhsh/sympy,skidzo/sy... | sympy/calculus/tests/test_singularities.py | sympy/calculus/tests/test_singularities.py | from sympy import Symbol, exp, log
from sympy.calculus.singularities import (singularities, is_increasing,
is_strictly_increasing, is_decreasing,
is_strictly_decreasing)
from sympy.sets import Interval
from sympy import oo, S
from symp... | from sympy import Symbol, exp, log
from sympy.calculus.singularities import singularities
from sympy.utilities.pytest import XFAIL
def test_singularities():
x = Symbol('x', real=True)
assert singularities(x**2, x) == ()
assert singularities(x/(x**2 + 3*x + 2), x) == (-2, -1)
@XFAIL
def test_singularit... | bsd-3-clause | Python |
f84f7e9091725d638e93d1dc14b830118a1833c8 | add returns for views | crucl0/gps_tracker,crucl0/gps_tracker,crucl0/gps_tracker | gps_tracker/views.py | gps_tracker/views.py | from pyramid.view import view_config
points_list = [
{"_id": 'ObjectId("52e3eb56a7cade5d0898e012")', "latitude": "45.215",
"longitude": "14.131", "gas_station": "Lukoil", "odometer": "24100",
"description": "Bad coffee"},
{"_id": 'ObjectId("52e3eb79a7cade5d0898e013")', "latitude": "47.412",
"lon... | from pyramid.view import view_config
points_list = [
{"_id": 'ObjectId("52e3eb56a7cade5d0898e012")', "latitude": "45.215",
"longitude": "14.131", "gas_station": "Lukoil", "odometer": "24100",
"description": "Bad coffee"},
{"_id": 'ObjectId("52e3eb79a7cade5d0898e013")', "latitude": "47.412",
"lon... | mit | Python |
d5f84783c376906dd5733391593ceae792b5edda | Bump version to 0.1.0 | dbcli/vcli,dbcli/vcli | vcli/__init__.py | vcli/__init__.py | __version__ = '0.1.0'
| __version__ = '0.0.1'
| bsd-3-clause | Python |
42e26737d083b82716c3adb8c19fb66a5063dc65 | change version number to v3.0.1 | civalin/cmdlr,civalin/cmdlr | src/cmdlr/info.py | src/cmdlr/info.py | """Cmdlr infomation files."""
VERSION = '3.0.1'
DESCRIPTION = ('An extensible comic subscriber.')
LICENSE = 'MIT'
AUTHOR = 'Civalin'
AUTHOR_EMAIL = 'larinawf@gmail.com'
PROJECT_URL = 'https://github.com/civalin/cmdlr'
PROJECT_NAME = 'cmdlr'
| """Cmdlr infomation files."""
VERSION = '3.0.0'
DESCRIPTION = ('An extensible comic subscriber.')
LICENSE = 'MIT'
AUTHOR = 'Civalin'
AUTHOR_EMAIL = 'larinawf@gmail.com'
PROJECT_URL = 'https://github.com/civalin/cmdlr'
PROJECT_NAME = 'cmdlr'
| mit | Python |
49e301ac6a74a30cfdf00bf4178889f9ecb74889 | Patch release for bug-fix #166 | akaszynski/vtkInterface | vtki/_version.py | vtki/_version.py | """ version info for vtki """
# major, minor, patch
version_info = 0, 18, 2
# Nice string for the version
__version__ = '.'.join(map(str, version_info))
| """ version info for vtki """
# major, minor, patch
version_info = 0, 18, 1
# Nice string for the version
__version__ = '.'.join(map(str, version_info))
| mit | Python |
4c6ec1413d1a12165c1231095783aa94d235389a | Add __version__ to vumi package. | harrissoerja/vumi,harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi | vumi/__init__.py | vumi/__init__.py | """
Vumi scalable text messaging engine.
"""
__version__ = "0.5.0a"
| bsd-3-clause | Python | |
3bb474a4506abb569d5c54703ba3bf2c9c933fd9 | Add tof-server to path | P1X-in/Tanks-of-Freedom-Server | tof-server.wsgi | tof-server.wsgi | import sys
activate_this = '/var/www/tof-server/flask/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
sys.path.append('/var/www/tof-server')
#activator = 'some/path/to/activate_this.py'
#with open(activator) as f:
# exec(f.read(), {'__file__': activator})
from tof_server import app as... | activate_this = '/var/www/tof-server/flask/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
#activator = 'some/path/to/activate_this.py'
#with open(activator) as f:
# exec(f.read(), {'__file__': activator})
from tof_server import app as application | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.