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 |
|---|---|---|---|---|---|---|---|---|
9cce47d37f6e2d08a66b9deedfc6f2f74b02720a | add int validator | faycheng/tpl,faycheng/tpl | tpl/prompt/validator.py | tpl/prompt/validator.py | # -*- coding:utf-8 -*-
from prompt_toolkit.validation import Validator, ValidationError
class StrValidator(Validator):
def validate(self, document):
pass
class IntValidator(Validator):
def validate(self, document):
text = document.text
for index, char in enumerate(text):
... | # -*- coding:utf-8 -*-
from prompt_toolkit.validation import Validator, ValidationError
class StrValidator(Validator):
def validate(self, document):
pass
| mit | Python |
4f73601c843ff9507064b85ddd33179af9fed653 | Raise stderr message | hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2 | utils/unfiltered_pbf.py | utils/unfiltered_pbf.py | # -*- coding: utf-8 -*-
import logging
import os
from string import Template
from subprocess import PIPE, Popen
from .artifact import Artifact
from .osm_xml import OSM_XML
LOG = logging.getLogger(__name__)
class InvalidOsmXmlException(Exception):
pass
class UnfilteredPBF(object):
name = 'full_pbf'
de... | # -*- coding: utf-8 -*-
import logging
import os
from string import Template
from subprocess import PIPE, Popen
from .artifact import Artifact
from .osm_xml import OSM_XML
LOG = logging.getLogger(__name__)
class InvalidOsmXmlException(Exception):
pass
class UnfilteredPBF(object):
name = 'full_pbf'
de... | bsd-3-clause | Python |
451e20818c7fbcc0b45500c71c5c5beee96eb316 | update jaxlib | tensorflow/probability,tensorflow/probability,google/jax,google/jax,google/jax,google/jax | jaxlib/version.py | jaxlib/version.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | apache-2.0 | Python |
1c15d302c2a1df22b4dd89f3215decf141a4c20e | return None if there is an error during scan | abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core | abilian/services/antivirus/__init__.py | abilian/services/antivirus/__init__.py | # coding=utf-8
"""
"""
from __future__ import absolute_import
try:
import clamd
cd = clamd.ClamdUnixSocket()
CLAMD_AVAILABLE = True
except ImportError:
CLAMD_AVAILABLE = False
from abilian.core.models.blob import Blob
from ..base import Service
class AntiVirusService(Service):
"""
Antivirus service
""... | # coding=utf-8
"""
"""
from __future__ import absolute_import
try:
import clamd
cd = clamd.ClamdUnixSocket()
CLAMD_AVAILABLE = True
except ImportError:
CLAMD_AVAILABLE = False
from abilian.core.models.blob import Blob
from ..base import Service
class AntiVirusService(Service):
"""
Antivirus service
""... | lgpl-2.1 | Python |
8e10657f94023a69967345114ee221c8d579c05d | Fix error with new issue while not login. | noracami/track-it,noracami/track-it | trackit/issues/views.py | trackit/issues/views.py | from django.shortcuts import render, get_object_or_404, redirect
from .models import Ticket, Label, User, Comment
import hashlib
# Create your views here.
def home(request):
issue = Ticket.objects.filter().order_by('-id')
readit = []
for i in issue:
issue_get = {}
issue_get['id'] = i.id
... | from django.shortcuts import render, get_object_or_404, redirect
from .models import Ticket, Label, User, Comment
import hashlib
# Create your views here.
def home(request):
issue = Ticket.objects.filter().order_by('-id')
readit = []
for i in issue:
issue_get = {}
issue_get['id'] = i.id
... | mit | Python |
7e4b66fe3df07afa431201de7a5a76d2eeb949a1 | Fix django custom template tag importing | xuru/substrate,xuru/substrate,xuru/substrate | app/main.py | app/main.py | #!/usr/bin/env python
import env_setup; env_setup.setup(); env_setup.setup_django()
from django.template import add_to_builtins
add_to_builtins('agar.django.templatetags')
from webapp2 import RequestHandler, Route, WSGIApplication
from agar.env import on_production_server
from agar.config import Config
from agar.dj... | #!/usr/bin/env python
from env_setup import setup_django
setup_django()
from env_setup import setup
setup()
from webapp2 import RequestHandler, Route, WSGIApplication
from agar.env import on_production_server
from agar.config import Config
from agar.django.templates import render_template
class MainApplicationConf... | mit | Python |
35c52ecbe34611f003d8f647dafdb15c00d70212 | update doc | DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public | python/git_pull_codedir/git_pull_codedir.py | python/git_pull_codedir/git_pull_codedir.py | # -*- coding: utf-8 -*-
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://raw.githubusercontent.com/DennyZhang/devops_public/master/LICENSE
##
## File : git_pull_codedir.py
## Author : Denny <denny@dennyzhang.com>... | # -*- coding: utf-8 -*-
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://raw.githubusercontent.com/DennyZhang/devops_public/master/LICENSE
##
## File : git_pull_codedir.py
## Author : Denny <denny@dennyzhang.com>... | mit | Python |
3ab5586ec4ac9ff3ac3fd7583bc9a71c7b5cd27a | fix lockedNormal, use MItMeshPolygon instead of MItMeshVertex, fix Fix() fucntion | sol-ansano-kim/medic,sol-ansano-kim/medic,sol-ansano-kim/medic | python/medic/plugins/Tester/lockedNormal.py | python/medic/plugins/Tester/lockedNormal.py | from medic.core import testerBase
from maya import OpenMaya
class LockedNormal(testerBase.TesterBase):
Name = "LockedNormal"
Description = "vertex(s) which has locked normal"
Fixable = True
def __init__(self):
super(LockedNormal, self).__init__()
def Match(self, node):
return nod... | from medic.core import testerBase
from maya import OpenMaya
class LockedNormal(testerBase.TesterBase):
Name = "LockedNormal"
Description = "vertex(s) which has locked normal"
Fixable = True
def __init__(self):
super(LockedNormal, self).__init__()
def Match(self, node):
return nod... | mit | Python |
e74b4867f9067e28686aecd19eb6f1d352ee28bf | fix imports | tomviner/dojo-adventure-game | game.py | game.py | import random
from characters import guests as people
from adventurelib import when, start
import rooms
from sys import exit
murder_config_people = list(people)
random.shuffle(murder_config_people)
murder_location = random.choice(list(rooms.rooms))
murderer = random.choice(list(people))
current_config_people = list... | import random
from characters import guests as people
from adventurelib import Item, Bag, when, start
import rooms
import characters
from sys import exit
murder_config_people = list(people)
random.shuffle(murder_config_people)
murder_location = random.choice(list(rooms.rooms))
murderer = random.choice(list(people))
... | mit | Python |
aaba085cd2e97c8c23e6724da3313d42d12798f0 | Make sure request.user is a user | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | app/grandchallenge/annotations/validators.py | app/grandchallenge/annotations/validators.py | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
re... | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
re... | apache-2.0 | Python |
9108f24183b2743647a8ed3ab354673e945d5f2a | Update release number | SpamScope/mail-parser | mailparser_version/__init__.py | mailparser_version/__init__.py | __version__ = "1.1.0"
| __version__ = "1.0.0"
| apache-2.0 | Python |
8128791c5b4cb8d185ceb916df2b6aa896f17453 | add test for custom ylabels | josesho/bootstrap_contrast | test_run.py | test_run.py | #! /usr/bin/env python
# Load Libraries
import matplotlib as mpl
mpl.use('SVG')
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
sns.set(style='ticks',context='talk')
import bootstrap_contrast as bsc
import pandas as pd
import numpy as np
import scipy as sp
# Dummy dataset
dataset=list()
f... | #! /usr/bin/env python
# Load Libraries
import matplotlib as mpl
mpl.use('SVG')
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
sns.set(style='ticks',context='talk')
import bootstrap_contrast as bsc
import pandas as pd
import numpy as np
import scipy as sp
# Dummy dataset
dataset=list()
f... | mit | Python |
0ca45e92a92e71d080af6e2104f4f625e31559f0 | Tweak mysql query string in test. | ContinuumIO/blaze,ContinuumIO/blaze | blaze/compute/tests/test_mysql_compute.py | blaze/compute/tests/test_mysql_compute.py | from __future__ import absolute_import, print_function, division
from getpass import getuser
import pytest
sa = pytest.importorskip('sqlalchemy')
pytest.importorskip('pymysql')
from odo import odo, drop, discover
import pandas as pd
import numpy as np
from blaze import symbol, compute
from blaze.utils import exam... | from __future__ import absolute_import, print_function, division
from getpass import getuser
import pytest
sa = pytest.importorskip('sqlalchemy')
pytest.importorskip('pymysql')
from odo import odo, drop, discover
import pandas as pd
import numpy as np
from blaze import symbol, compute
from blaze.utils import exam... | bsd-3-clause | Python |
a6c4540877e00df93fb5de3ce76e3a7393c1c587 | Change notes. | jgehrcke/timegaps,jgehrcke/timegaps | timegaps.py | timegaps.py | # -*- coding: utf-8 -*-
# Copyright 2014 Jan-Philip Gehrcke. See LICENSE file for details.
"""
Feature brainstorm:
- reference implementation with cmdline interface
- comprehensive API for systematic unit testing and library usage
- remove or move or noop mode
- extensive logging
- parse mtime fro... | # -*- coding: utf-8 -*-
# Copyright 2014 Jan-Philip Gehrcke. See LICENSE file for details.
"""
Feature brainstorm:
- reference implementation with cmdline interface
- comprehensive API for systematic unit testing and library usage
- remove or move or noop mode
- extensive logging
- parse mtime fro... | mit | Python |
4bc436ac4d441987d602b3af10517125c78c56e0 | remove use of BeautifulSoup from parse_paragraph_as_list | StoDevX/course-data-tools,StoDevX/course-data-tools | lib/parse_paragraph_as_list.py | lib/parse_paragraph_as_list.py | def parse_paragraph_as_list(string_with_br):
paragraph = ' '.join(string_with_br.split())
lines = [s.strip() for s in paragraph.split('<br>')]
return [l for l in lines if l]
| from bs4 import BeautifulSoup
def parse_paragraph_as_list(string_with_br):
strings = BeautifulSoup(string_with_br, 'html.parser').strings
splitted = [' '.join(s.split()).strip() for s in strings]
return [s for s in splitted if s]
| mit | Python |
ac6ce056e6b05531d81c550ae3e1e1d688ece4a0 | Make serializer commet more clear | codertx/lightil | jwt_auth/serializers.py | jwt_auth/serializers.py | from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True)
class Meta:
model = User
fields = ('id', 'nickname', 'username', 'email', 'pa... | from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True)
class Meta:
model = User
fields = ('id', 'nickname', 'username', 'email', 'pa... | mit | Python |
b7a84ce7f0049229693fe12bf7a8bb1a7177d3b6 | convert values to float before multiplying with pi | philipkimmey/django-geo | django_geo/distances.py | django_geo/distances.py | import math
class distances:
@staticmethod
def geographic_distance(lat1, lng1, lat2, lng2):
lat1 = float(lat1)
lng1 = float(lng1)
lat2 = float(lat2)
lng2 = float(lng2)
lat1 = (lat1 * math.pi) / 180
lng1 = (lng1 * math.pi) / 180
lat2 = (lat2 * math.pi) / 180
lng2 = (lng2 * math.... | import math
class distances:
@staticmethod
def geographic_distance(lat1, lng1, lat2, lng2):
lat1 = (lat1 * math.pi) / 180
lng1 = (lng1 * math.pi) / 180
lat2 = (lat2 * math.pi) / 180
lng2 = (lng2 * math.pi) / 180
a = (math.sin(lat1)*math.sin(lat2))+(math.cos(lat1)*math.cos(lat2)*math.cos(lng2 - lng1))
retu... | mit | Python |
4259019196c473431d4291f2910ab0164e319ffb | update simu.py for 0.3.0. | ryos36/polyphony-tutorial,ryos36/polyphony-tutorial,ryos36/polyphony-tutorial | bin/simu.py | bin/simu.py | #!/usr/bin/env python3
import sys
import os
import traceback
import subprocess
IVERILOG_PATH = 'iverilog'
ROOT_DIR = '.' + os.path.sep
TEST_DIR = ROOT_DIR + 'tests'
TMP_DIR = ROOT_DIR + '.tmp'
sys.path.append(ROOT_DIR)
from polyphony.compiler.__main__ import compile_main, logging_setting
from polyphony.compiler.env ... | #!/usr/bin/env python3
import sys
import os
import traceback
import logging
import profile
from subprocess import call, check_call, check_output
ROOT_DIR = './'
TEST_DIR = ROOT_DIR+'tests'
TMP_DIR = ROOT_DIR+'.tmp'
sys.path.append(ROOT_DIR)
from polyphony.compiler.__main__ import compile_main, logging_setting
from po... | mit | Python |
fd9a553868ce46ceef2b23e79347dd262b63ebae | fix build instructions on Linux | 0xfeedface/node_raptor,0xfeedface/node_raptor,0xfeedface/node_raptor,0xfeedface/node_raptor | binding.gyp | binding.gyp | { "targets": [ {
"target_name": "bindings",
"include_dirs": [
"<(raptor_prefix)/include/raptor2"
],
"sources": [
"src/bindings.cc",
"src/parser.cc",
"src/parser_wrapper.cc",
"src/serializer.cc",
"src/serializer_wrapper.cc",
"src/statement.cc",
... | { "targets": [ {
"target_name": "bindings",
"variables": {
"raptor_prefix": "/usr/local"
},
"include_dirs": [
"<(raptor_prefix)/include/raptor2"
],
"sources": [
"src/bindings.cc",
"src/parser.cc",
"src/parser_wrapper.cc",
"src/serializer.cc",
... | apache-2.0 | Python |
2f924fc35d0724e7638e741fd466228649077e10 | Update action_after_build destination | elaberge/node-zipfile,elaberge/node-zipfile,elaberge/node-zipfile,elaberge/node-zipfile | binding.gyp | binding.gyp | {
'includes': [ 'deps/common-libzip.gypi' ],
'variables': {
'shared_libzip%':'false',
'shared_libzip_includes%':'/usr/lib',
'shared_libzip_libpath%':'/usr/include'
},
'targets': [
{
'target_name': 'node_zipfile',
'conditions': [
['shared_libzip == "false"', {
... | {
'includes': [ 'deps/common-libzip.gypi' ],
'variables': {
'shared_libzip%':'false',
'shared_libzip_includes%':'/usr/lib',
'shared_libzip_libpath%':'/usr/include'
},
'targets': [
{
'target_name': 'node_zipfile',
'conditions': [
['shared_libzip == "false"', {
... | bsd-3-clause | Python |
db99ecacca94f5c045d8d024dd34c96e23d828df | Adjust binding.gyp for building on Linux too | elafargue/nodhelium,elafargue/nodhelium,elafargue/nodhelium,elafargue/nodhelium | binding.gyp | binding.gyp | {
"targets": [
{
"target_name": "helium",
"sources": [ "helium.cc", "helium_wrapper.cc" ],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
'libraries': [ '-lhelium'],
'conditions':... | {
"targets": [
{
"target_name": "helium",
"sources": [ "helium.cc", "helium_wrapper.cc" ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
'libraries': [ '-lhelium'],
'conditions': [
[ 'OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_C... | mit | Python |
c2f563215fcc62d6e595446f5acbd1969484ddb7 | move end timer command to the correct location | edlongman/thescoop,edlongman/thescoop,edlongman/thescoop | clean_db.py | clean_db.py | import MySQLdb, config, urllib, cgi, datetime, time
sql = MySQLdb.connect(host="localhost",
user=config.username,
passwd=config.passwd,
db=config.db)
sql.query("SELECT `id` FROM `feedurls`")
db_feed_query=sql.store_result()
rss_urls=d... | import MySQLdb, config, urllib, cgi, datetime, time
sql = MySQLdb.connect(host="localhost",
user=config.username,
passwd=config.passwd,
db=config.db)
sql.query("SELECT `id` FROM `feedurls`")
db_feed_query=sql.store_result()
rss_urls=d... | apache-2.0 | Python |
d0b457b5bde040af623b78409f778a1c39a09807 | Hide main | Mause/pytransperth,Mause/pytransperth | transperth/livetimes.py | transperth/livetimes.py | import json
from itertools import chain
from os.path import join, dirname
import requests
from lxml import etree
URL = (
'http://livetimes.transperth.wa.gov.au/LiveTimes.asmx'
'/GetSercoTimesForStation'
)
ASSETS = join(dirname(__file__), 'assets')
with open(join(ASSETS, 'train_stations.json')) as fh:
TRA... | import json
from itertools import chain
from os.path import join, dirname
import requests
from lxml import etree
URL = (
'http://livetimes.transperth.wa.gov.au/LiveTimes.asmx'
'/GetSercoTimesForStation'
)
ASSETS = join(dirname(__file__), 'assets')
with open(join(ASSETS, 'train_stations.json')) as fh:
TRA... | mit | Python |
3ee4d2f80f58cb0068eaeb3b7f5c4407ce8e60d0 | add text information about progress of downloading | Victoria1807/VK-Photos-Downloader | vk-photos-downloader.py | vk-photos-downloader.py | #!/usr/bin/python3.5
#-*- coding: UTF-8 -*-
import vk, os, time
from urllib.request import urlretrieve
token = input("Enter a token: ") # vk token
#Authorization
session = vk.Session(access_token=str(token))
vk_api = vk.API(session)
count = 0 # count of down. photos
perc = 0 # percent of down. photo... | #!/usr/bin/python3.5
#-*- coding: UTF-8 -*-
import vk, os, time
from urllib.request import urlretrieve
token = input("Enter a token: ")
#Authorization
session = vk.Session(access_token=str(token))
vk_api = vk.API(session)
count = 0 # count of down. photos
perc = 0 # percent of down. photos
breaked =... | mit | Python |
cc894ecf36a95d18fc84a4866c5a1902d291ccbe | Use non-lazy `gettext` where sufficient | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | byceps/blueprints/site/ticketing/forms.py | byceps/blueprints/site/ticketing/forms.py | """
byceps.blueprints.site.ticketing.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask import g
from flask_babel import gettext, lazy_gettext
from wtforms import StringField
from wtforms.validators import Input... | """
byceps.blueprints.site.ticketing.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask import g
from flask_babel import lazy_gettext
from wtforms import StringField
from wtforms.validators import InputRequired,... | bsd-3-clause | Python |
862885b5ea2b4d04c8980c257d3cdf644dd60f0c | Set the version to 0.1.6 final | xujun10110/king-phisher,drptbl/king-phisher,drptbl/king-phisher,securestate/king-phisher,hdemeyer/king-phisher,0x0mar/king-phisher,securestate/king-phisher,wolfthefallen/king-phisher,drptbl/king-phisher,securestate/king-phisher,securestate/king-phisher,securestate/king-phisher,wolfthefallen/king-phisher,zigitax/king-ph... | king_phisher/version.py | king_phisher/version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/version.py
#
# 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 lis... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/version.py
#
# 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 lis... | bsd-3-clause | Python |
7c8d7a456634d15f8c13548e2cfd6be9440f7c65 | Add handler for 403 forbidden (User does not have Atmosphere access, but was correctly authenticated) | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend | troposphere/__init__.py | troposphere/__init__.py | import logging
from flask import Flask
from flask import render_template, redirect, url_for, request, abort
import requests
from troposphere import settings
from troposphere.cas import (cas_logoutRedirect, cas_loginRedirect,
cas_validateTicket)
from troposphere.oauth import generate_acces... | import logging
from flask import Flask
from flask import render_template, redirect, url_for, request
import requests
from troposphere import settings
from troposphere.cas import (cas_logoutRedirect, cas_loginRedirect,
cas_validateTicket)
from troposphere.oauth import generate_access_token... | apache-2.0 | Python |
b7be60eff8e0c82741dda674824aa748e33e7fdd | convert pui.py to pywiki framework | legoktm/legobot-old,legoktm/legobot-old | trunk/toolserver/pui.py | trunk/toolserver/pui.py | #!usr/bin/python
# -*- coding: utf-8 -*
#
# (C) Legoktm 2008-2009, MIT License
#
import re
sys.path.append(os.environ['HOME'] + '/pywiki')
import wiki
page = wiki.Page('Wikipedia:Possibly unfree images')
wikitext = state0 = page.get()
wikitext = re.compile(r'\n==New listings==', re.IGNORECASE).sub(r'\n*[[/{{subst... | #!usr/bin/python
# -*- coding: utf-8 -*
#
# (C) Legoktm 2008-2009, MIT License
#
import re, sys, os
sys.path.append(os.environ['HOME'] + '/pyenwiki')
import wikipedia
site = wikipedia.getSite()
page = wikipedia.Page(site, 'Wikipedia:Possibly unfree images')
wikitext = state0 = page.get()
wikitext = re.compile(r'\... | mit | Python |
d6029a7b2e39ff6222ca3d6788d649b14bbf35e3 | add smoother to denominator as well | datamade/sunspots | trending.py | trending.py | import googleanalytics as ga
import collections
import numpy
import datetime
SMOOTHER = 20
WINDOW = 8
GROWTH_THRESHOLD = 0.02
def trend(counts) :
X, Y = zip(*counts)
X = numpy.array([x.toordinal() for x in X])
X -= datetime.date.today().toordinal()
A = numpy.array([numpy.ones(len(X)), X])
Y = nu... | import googleanalytics as ga
import collections
import numpy
import datetime
SMOOTHER = 20
WINDOW = 8
GROWTH_THRESHOLD = 0.03
def trend(counts) :
X, Y = zip(*counts)
X = numpy.array([x.toordinal() for x in X])
X -= datetime.date.today().toordinal()
A = numpy.array([numpy.ones(len(X)), X])
Y = nu... | mit | Python |
656c0f44c27f64d14dde7cbbfdec31906dab4c51 | Add params to request docs. | habnabit/treq,hawkowl/treq,cyli/treq,FxIII/treq,hawkowl/treq,glyph/treq,alex/treq,alex/treq,ldanielburr/treq,mithrandi/treq,inspectlabs/treq | treq/api.py | treq/api.py | from treq.client import HTTPClient
def head(url, **kwargs):
"""
Make a ``HEAD`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).head(url, **kwargs)
def get(url, headers=None, **kwargs):
"""
Make a ``GET`` request.
See :py:func:`treq.request`
"""
return _cl... | from treq.client import HTTPClient
def head(url, **kwargs):
"""
Make a ``HEAD`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).head(url, **kwargs)
def get(url, headers=None, **kwargs):
"""
Make a ``GET`` request.
See :py:func:`treq.request`
"""
return _cl... | mit | Python |
0ba512b0e8eb6b5055261afb2962d3bfc5e2fda5 | Add some playback stream headers | katajakasa/koel-ampache-bridge | src/playback.py | src/playback.py | # -*- coding: utf-8 -*-
import mimetypes
import os
from flask import Response, request
from werkzeug.datastructures import Headers
import audiotranscode
from utils import generate_random_key
from tables import Song
import config
def stream_audio():
song = Song.get_one(id=request.args.get('id'))
# A hack t... | # -*- coding: utf-8 -*-
import mimetypes
import os
from flask import Response, request
import audiotranscode
from tables import Song
import config
def stream_audio():
song = Song.get_one(id=request.args.get('id'))
# A hack to get my local dev env working
path = song.path
if config.DEBUG:
c... | mit | Python |
e6487a2c623638b540b707c895a97eac1fc31979 | Update connection_test.py to work with Python3.7 | channable/icepeak,channable/icepeak,channable/icepeak | server/integration-tests/connection_test.py | server/integration-tests/connection_test.py | #!/usr/bin/env python3.7
"""
Test PUTing some data into Icepeak and getting it back over a websocket.
Requires a running Icepeak instance.
Requirements can be installed with: pip install requests websockets
"""
import asyncio
import json
import requests
import websockets
# 1. Put some data into icepeak over HTTP
ne... | #!/usr/bin/env python2.7
from __future__ import absolute_import, division, unicode_literals
import json
import requests
import websocket
# 1. Put some data into icepeak over HTTP
new_data = {'status': 'freezing'}
requests.put('http://localhost:3000/so/cool',
json.dumps(new_data))
# 2. Get the data back over a we... | bsd-3-clause | Python |
69b9c641f144633b94aca47212af446971286454 | add tests | ISISComputingGroup/EPICS-inst_servers,ISISComputingGroup/EPICS-inst_servers | server_common/test_modules/test_autosave.py | server_common/test_modules/test_autosave.py | from __future__ import unicode_literals, absolute_import, print_function, division
import unittest
import shutil
import os
from server_common.autosave import AutosaveFile
TEMP_FOLDER = os.path.join("C:\\", "instrument", "var", "tmp", "autosave_tests")
class TestAutosave(unittest.TestCase):
def setUp(self):
... | import unittest
class TestAutosave(unittest.TestCase):
def setUp(self):
pass
| bsd-3-clause | Python |
6a4f4031b0aac1c8859424703088df903746a6c8 | change command doc string | efiop/dvc,efiop/dvc,dmpetrov/dataversioncontrol,dmpetrov/dataversioncontrol | dvc/command/get.py | dvc/command/get.py | import argparse
import logging
from .base import append_doc_link
from .base import CmdBaseNoRepo
from dvc.exceptions import DvcException
logger = logging.getLogger(__name__)
class CmdGet(CmdBaseNoRepo):
def run(self):
from dvc.repo import Repo
try:
Repo.get(
self.ar... | import argparse
import logging
from .base import append_doc_link
from .base import CmdBaseNoRepo
from dvc.exceptions import DvcException
logger = logging.getLogger(__name__)
class CmdGet(CmdBaseNoRepo):
def run(self):
from dvc.repo import Repo
try:
Repo.get(
self.ar... | apache-2.0 | Python |
4a6846b969746b79f1acd0e0615232d97ed54b1f | replace import-time cluster dependencies (#1544) | vishnu2kmohan/dcos-commons,mesosphere/dcos-commons,mesosphere/dcos-commons,vishnu2kmohan/dcos-commons,vishnu2kmohan/dcos-commons,vishnu2kmohan/dcos-commons,vishnu2kmohan/dcos-commons,mesosphere/dcos-commons,mesosphere/dcos-commons,mesosphere/dcos-commons | frameworks/template/tests/test_sanity.py | frameworks/template/tests/test_sanity.py | import pytest
import sdk_install
import sdk_utils
from tests import config
@pytest.fixture(scope='module', autouse=True)
def configure_package(configure_security):
try:
sdk_install.uninstall(config.PACKAGE_NAME, sdk_utils.get_foldered_name(config.SERVICE_NAME))
# note: this package isn't released... | import pytest
import sdk_install
import sdk_utils
from tests import config
FOLDERED_SERVICE_NAME = sdk_utils.get_foldered_name(config.SERVICE_NAME)
@pytest.fixture(scope='module', autouse=True)
def configure_package(configure_security):
try:
sdk_install.uninstall(config.PACKAGE_NAME, FOLDERED_SERVICE_NAME... | apache-2.0 | Python |
0eef0efbe716feb3dc02fb45a756496d5517966c | Update docs. | faneshion/MatchZoo,faneshion/MatchZoo | matchzoo/models/naive_model.py | matchzoo/models/naive_model.py | """Naive model with a simplest structure for testing purposes."""
import keras
from matchzoo import engine
class NaiveModel(engine.BaseModel):
"""
Naive model with a simplest structure for testing purposes.
Bare minimum functioning model. The best choice to get things rolling.
The worst choice to f... | """Naive model with a simplest structure for testing purposes."""
import keras
from matchzoo import engine
class NaiveModel(engine.BaseModel):
"""Naive model with a simplest structure for testing purposes."""
def build(self):
"""Build."""
x_in = self._make_inputs()
x = keras.layers.... | apache-2.0 | Python |
0859bb58a4fa24f5e278e95da491a2b4409f0b2b | Tag 0.5.3 | koordinates/python-client,koordinates/python-client | koordinates/__init__.py | koordinates/__init__.py | # -*- coding: utf-8 -*-
"""
Koordinates Python API Client Library
:copyright: (c) Koordinates Limited.
:license: BSD, see LICENSE for more details.
"""
__version__ = "0.5.3"
from .exceptions import (
KoordinatesException,
ClientError,
ClientValidationError,
InvalidAPIVersion,
ServerError,
Bad... | # -*- coding: utf-8 -*-
"""
Koordinates Python API Client Library
:copyright: (c) Koordinates Limited.
:license: BSD, see LICENSE for more details.
"""
__version__ = "0.5.0"
from .exceptions import (
KoordinatesException,
ClientError,
ClientValidationError,
InvalidAPIVersion,
ServerError,
Bad... | bsd-3-clause | Python |
b6554b00fdb0387a27671eeb39589dc7e7109f6e | Add collecter function | LeoIsaac/piccolle-v2,LeoIsaac/piccolle-v2 | app/main.py | app/main.py | from flask import Flask, request, jsonify
from urllib.request import urlopen
from bs4 import BeautifulSoup
app = Flask(__name__)
app.config.update(
DEBUG=True
)
@app.route("/")
def index():
url = request.args.get('url', '')
res = collecter(url)
return jsonify(res)
if __name__ == "__main__":
app.r... | from flask import Flask
app = Flask(__name__)
app.config.update(
DEBUG=True
)
@app.route("/")
def index():
return "Hello python"
if __name__ == "__main__":
app.run()
| apache-2.0 | Python |
7b58f59ec288dd055cf931dd47c4e8e59bb9ad1d | update atx-agent version | openatx/uiautomator2,openatx/uiautomator2,openatx/uiautomator2 | uiautomator2/version.py | uiautomator2/version.py | # coding: utf-8
#
__apk_version__ = '1.1.5'
# 1.1.5 waitForExists use UiObject2 method first then fallback to UiObject.waitForExists
# 1.1.4 add ADB_EDITOR_CODE broadcast support, fix bug (toast捕获导致app闪退)
# 1.1.3 use thread to make watchers.watched faster, try to fix input method type multi
# 1.1.2 fix count error whe... | # coding: utf-8
#
__apk_version__ = '1.1.5'
# 1.1.5 waitForExists use UiObject2 method first then fallback to UiObject.waitForExists
# 1.1.4 add ADB_EDITOR_CODE broadcast support, fix bug (toast捕获导致app闪退)
# 1.1.3 use thread to make watchers.watched faster, try to fix input method type multi
# 1.1.2 fix count error whe... | mit | Python |
0c9accce7b3df8889ecf57b6df89a36628cb908c | add timeout for running scheduler | randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting | sbin/run_scheduler.py | sbin/run_scheduler.py | import subprocess
import tempfile
import time, os
import re
import sys
# cd ~/.config/sublime-text-3/Packages/UnitTesting
# python sbin/run_scheduler.py PACKAGE
# script directory
__dir__ = os.path.dirname(os.path.abspath(__file__))
version = int(subprocess.check_output(["subl","--version"]).decode('utf8').strip()[-... | import subprocess
import tempfile
import time, os
import re
import sys
# cd ~/.config/sublime-text-3/Packages/UnitTesting
# python sbin/run_scheduler.py PACKAGE
# script directory
__dir__ = os.path.dirname(os.path.abspath(__file__))
version = int(subprocess.check_output(["subl","--version"]).decode('utf8').strip()[-... | mit | Python |
42f4ed206a9c79799b9bb0b13b829c8cf9c979e4 | write to file | pedsm/deepHack,pedsm/deepHack,pedsm/deepHack | scraper/parse_dump.py | scraper/parse_dump.py | #!/usr/bin/python
# Simple script to parse the devpost dump and place results in a json
import os
import json
from multiprocessing import Pool
from bs4 import BeautifulSoup
OUTPUT_FNAME="devpostdump.json"
DUMP_DIR = "output/"
projects = [os.path.join(DUMP_DIR, f) for f in os.listdir(DUMP_DIR)]
# projects = projects[... | #!/usr/bin/python
# Simple script to parse the devpost dump and place results in a json
import os
import json
from multiprocessing import Pool
from bs4 import BeautifulSoup
OUTPUT_FNAME="devpostdump.json"
DUMP_DIR = "output/"
projects = [os.path.join(DUMP_DIR, f) for f in os.listdir(DUMP_DIR)]
# projects = projects[... | mit | Python |
c8a010e6e9a917c50843dd10303f8f9497b4687c | Bump version | cosenal/waterbutler,hmoco/waterbutler,Ghalko/waterbutler,felliott/waterbutler,TomBaxter/waterbutler,chrisseto/waterbutler,rafaeldelucena/waterbutler,Johnetordoff/waterbutler,CenterForOpenScience/waterbutler,RCOSDP/waterbutler,icereval/waterbutler,kwierman/waterbutler,rdhyee/waterbutler | waterbutler/__init__.py | waterbutler/__init__.py | __version__ = '0.2.3'
__import__("pkg_resources").declare_namespace(__name__)
| __version__ = '0.2.2'
__import__("pkg_resources").declare_namespace(__name__)
| apache-2.0 | Python |
b0e3886ee24689f1eb249e0ed3c66d887b317f60 | Delete table test | cioc/grpc-rocksdb,cioc/grpc-rocksdb,cioc/grpc-rocksdb | tst/test.py | tst/test.py | #!/usr/bin/python
import grpc
import keyvalue_pb2
import os
import sys
if __name__ == '__main__':
conn_str = os.environ['GRPCROCKSDB_PORT'].split("/")[2]
print "Connecting on: " + conn_str
channel = grpc.insecure_channel(conn_str)
stub = keyvalue_pb2.KeyValueStub(channel)
create_table_res = stub.... | #!/usr/bin/python
import grpc
import keyvalue_pb2
import os
import sys
if __name__ == '__main__':
conn_str = os.environ['GRPCROCKSDB_PORT'].split("/")[2]
print "Connecting on: " + conn_str
channel = grpc.insecure_channel(conn_str)
stub = keyvalue_pb2.KeyValueStub(channel)
create_table_res = stub.... | mit | Python |
96340529a8d5702ce8c880aa66966b2971b96449 | change method | MadsJensen/malthe_alpha_project,MadsJensen/malthe_alpha_project | calc_cov.py | calc_cov.py | import mne
import sys
from mne import compute_covariance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from my_settings import *
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=180e-6 #
)
subject = sys.ar... | import mne
import sys
from mne import compute_covariance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from my_settings import *
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=180e-6 #
)
subject = sys.ar... | mit | Python |
4be984747a41e5ab966b12afe9074a0e611faee2 | Add license text to resampling.py | talhaHavadar/RobotLocalization | resampling.py | resampling.py | """
MIT License
Copyright (c) 2017 Talha Can Havadar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publ... | """
@author Talha Can Havadar (talhaHavadar)
"""
import random
from collections import Counter
class ResamplingWheel(object):
"""
A Class implementation for resampling wheel
Creates an imaginary wheel that consist of weighted portions.
According to these weights, you can pick an index value.
Index ... | mit | Python |
5fa9e88e9402a4ca12f2f54298d397bc7b54728b | Revert "deactivated test for non-existent 'references'" | codethesaurus/codethesaur.us,codethesaurus/codethesaur.us | web/tests/test_views.py | web/tests/test_views.py | from django.test import TestCase, Client
from django.urls import reverse
from web.views import index, about, compare, reference
class TestViews(TestCase):
def test_index_view_GET(self):
url = reverse('index')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplate... | from django.test import TestCase, Client
from django.urls import reverse
from web.views import index, about, compare, reference
class TestViews(TestCase):
def test_index_view_GET(self):
url = reverse('index')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplate... | agpl-3.0 | Python |
a5fddaefdedef18b0b6b7d3b2ec65f64eaaaad65 | fix date time bug | edlongman/thescoop,edlongman/thescoop,edlongman/thescoop | clean_db.py | clean_db.py | import MySQLdb, config, urllib, cgi, datetime
from datetime import datetime
sql = MySQLdb.connect(host="localhost",
user=config.username,
passwd=config.passwd,
db=config.test_db)
sql.query("SELECT `id` FROM `feedurls`")
db_feed_query=... | import MySQLdb, config, urllib, cgi, datetime
from datetime import datetime
sql = MySQLdb.connect(host="localhost",
user=config.username,
passwd=config.passwd,
db=config.test_db)
sql.query("SELECT `id` FROM `feedurls`")
db_feed_query=... | apache-2.0 | Python |
d64460c8bbbe045dcdf9f737562a31d84044acce | Change package name to 'cirm' to avoid confusion. | informatics-isi-edu/microscopy,informatics-isi-edu/microscopy,informatics-isi-edu/microscopy,informatics-isi-edu/microscopy | rest/setup.py | rest/setup.py | #
# Copyright 2012 University of Southern California
#
# 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... | #
# Copyright 2012 University of Southern California
#
# 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... | apache-2.0 | Python |
7484c8d4ab699ee16bc867cdff1e7ec699dbb142 | Add profiling support to Melange. By assigning profile_main_as_logs or profile_main_as_html to main variable you can turn on profiling. profile_main_as_logs will log profile data to App Engine console logs, profile_main_as_html will show profile data as html at the bottom of the page. If you want to profile app on depl... | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | app/main.py | app/main.py | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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... | apache-2.0 | Python |
fc05512b3ad40f6571ee3d942e4829a19e2a465e | Add core.models.Sensor | HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site | sensor/core/models.py | sensor/core/models.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
class GenericSensor(models.Model):
"""Represents a sensor abstracting away the spe... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
class GenericSensor(models.Model):
"""Represents a sensor abstracting away the spe... | mpl-2.0 | Python |
d9d9b993edc8baebf69b446d40f0a05260a041d5 | Remove prints | martinlunde/RealBack,martinlunde/RealBack,martinlunde/RealBack | emailauth/tests.py | emailauth/tests.py | from django.test import Client, TestCase
from emailauth import forms
c = Client()
class FormTests(TestCase):
def test_creation_form(self):
form_data = {'email': 'test@test.com', 'password1': 'test1234', 'password2': 'test1234'}
form = forms.UserCreationForm(form_data)
# Testing if form ... | from django.test import Client, TestCase
from emailauth import forms
c = Client()
class FormTests(TestCase):
def test_creation_form(self):
form_data = {'email': 'test@test.com', 'password1': 'test1234', 'password2': 'test1234'}
form = forms.UserCreationForm(form_data)
# Testing if form ... | mit | Python |
265e9added53d1eee1291b9e0b5a10bc7dfe19c8 | Make sure we don't have section A before doing the extra round of manipulation | uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw | myuw_mobile/test/dao/canvas.py | myuw_mobile/test/dao/canvas.py | from django.test import TestCase
from django.test.client import RequestFactory
from myuw_mobile.dao.canvas import get_indexed_data_for_regid
from myuw_mobile.dao.canvas import get_indexed_by_decrosslisted
from myuw_mobile.dao.schedule import _get_schedule
from myuw_mobile.dao.term import get_current_quarter
class Test... | from django.test import TestCase
from django.test.client import RequestFactory
from myuw_mobile.dao.canvas import get_indexed_data_for_regid
from myuw_mobile.dao.canvas import get_indexed_by_decrosslisted
from myuw_mobile.dao.schedule import _get_schedule
from myuw_mobile.dao.term import get_current_quarter
class Test... | apache-2.0 | Python |
ae948a2dfdd62af2ba98a0ee506ddd48504ee64b | bump version to 0.6-dev | msabramo/validictory,ahassany/validictory,mgrandi/validictory,MeilleursAgents/validictory,stxnext/validictory,soulrebel/validictory,nicolaiarocci/validictory,enotodden/validictory,brotchie/validictory,travelbird/validictory,trigger-corp/validictory,alonho/validictory,dokai/validictory,fvieira/validictory,rhettg/validic... | validictory/__init__.py | validictory/__init__.py | #!/usr/bin/env python
from validictory.validator import SchemaValidator
__all__ = [ 'validate', 'SchemaValidator' ]
__version__ = '0.6.0-dev'
def validate(data, schema, validator_cls=SchemaValidator):
'''
Validates a parsed json document against the provided schema. If an
error is found a ValueError is r... | #!/usr/bin/env python
from validictory.validator import SchemaValidator
__all__ = [ 'validate', 'SchemaValidator' ]
__version__ = '0.5.0'
def validate(data, schema, validator_cls=SchemaValidator):
'''
Validates a parsed json document against the provided schema. If an
error is found a ValueError is raise... | mit | Python |
db033a9560ee97b5281adbf05f3f452943d592d7 | Add test_get_on_call and test_weekly | wking/django-on-call | django_on_call/tests.py | django_on_call/tests.py | import datetime
from django.test import TestCase
from .models import OnCall
class SimpleTest(TestCase):
def test_get_on_call(self):
"""Test the basic OnCall.get_on_call functionality
"""
on_call = OnCall(slug='test', rule='on_call = "Alice"')
self.assertEqual(on_call.get_on_call(... | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | bsd-2-clause | Python |
781e20bc3f465bdaac50f0f2a637b037d892c054 | Remove premature optimisation | Rypac/sublime-format | src/registry.py | src/registry.py | from .formatters import *
class FormatRegistry():
def __init__(self):
self.__formatters = [
ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(),
PythonFormat(), RustFormat(), TerraformFormat()
]
@property
def all(self):
return self.__formatters
... | from .formatters import *
class FormatRegistry():
def __init__(self):
self.__registered_formatters = [
ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(),
PythonFormat(), RustFormat(), TerraformFormat()
]
self.__source_formatter_lookup_table = {}
for... | mit | Python |
945e7d1ef165054891a0ac574d52f6a1c3b7a162 | Add long help | goodwinxp/ATFGenerator,goodwinxp/ATFGenerator,goodwinxp/ATFGenerator | code_gen.py | code_gen.py | import sys
import getopt
from config import CONFIG
from ida_code_gen import IdaCodeGen
from ida_parser import IdaInfoParser
def print_help():
print 'Options:'
print ' -d, --database Path to database from arguments. Default = ' + CONFIG['database']
print ' -o, --out_dir Path to output directory for c... | import sys
import getopt
from config import CONFIG
from ida_code_gen import IdaCodeGen
from ida_parser import IdaInfoParser
def print_help():
print 'Options:'
print ' -d, --database Path to database from arguments. Default = ' + CONFIG['database']
print ' -o, --out_dir Path to output directory for c... | mit | Python |
2ad94140360f893ad46b1b972e753f2a78b5f779 | print function | konomae/lastpass-python,dhercher/lastpass-python | example/example.py | example/example.py | # coding: utf-8
import json
import os
import lastpass
with open(os.path.join(os.path.dirname(__file__), 'credentials.json')) as f:
credentials = json.load(f)
username = str(credentials['username'])
password = str(credentials['password'])
try:
# First try without a multifactor password
vault = last... | # coding: utf-8
import json
import os
import lastpass
with open(os.path.join(os.path.dirname(__file__), 'credentials.json')) as f:
credentials = json.load(f)
username = str(credentials['username'])
password = str(credentials['password'])
try:
# First try without a multifactor password
vault = last... | mit | Python |
cefa0a94582e40f92c48d6c91cf393c9b0310713 | fix geojson in sources dir | OpenBounds/Processing | validate.py | validate.py |
import json
import re
import click
import jsonschema
import utils
@click.command()
@click.argument('schema', type=click.File('r'), required=True)
@click.argument('jsonfiles', type=click.Path(exists=True), required=True)
def validate(schema, jsonfiles):
"""Validate a JSON files against a JSON schema.
\b
... |
import json
import re
import click
import jsonschema
import utils
@click.command()
@click.argument('schema', type=click.File('r'), required=True)
@click.argument('jsonfiles', type=click.Path(exists=True), required=True)
def validate(schema, jsonfiles):
"""Validate a JSON files against a JSON schema.
\b
... | mit | Python |
7e16a9feb88023a03363aee5be552a2f15b825fc | 修复 waiting 状态下颜色错误的问题 | wangmingjob/OnlineJudge,Timeship/OnlineJudge-QDU,uestcxl/OnlineJudge,wangmingjob/OnlineJudge,wwj718/OnlineJudge,wangmingjob/OnlineJudge,hxsf/OnlineJudge,Timeship/OnlineJudge-1,hxsf/OnlineJudge,hxsf/OnlineJudge,Timeship/OnlineJudge-1,Timeship/OnlineJudge-1,wangmingjob/OnlineJudge,uestcxl/OnlineJudge,hxsf/OnlineJudge,Tim... | utils/templatetags/submission.py | utils/templatetags/submission.py | # coding=utf-8
def translate_result(value):
results = {
0: "Accepted",
1: "Runtime Error",
2: "Time Limit Exceeded",
3: "Memory Limit Exceeded",
4: "Compile Error",
5: "Format Error",
6: "Wrong Answer",
7: "System Error",
8: "Waiting"
}
... | # coding=utf-8
def translate_result(value):
results = {
0: "Accepted",
1: "Runtime Error",
2: "Time Limit Exceeded",
3: "Memory Limit Exceeded",
4: "Compile Error",
5: "Format Error",
6: "Wrong Answer",
7: "System Error",
8: "Waiting"
}
... | mit | Python |
d17a88ac9ef8e3806c7ac60d31df62a1041939cb | Add sum_of_spreads | skearnes/muv | muv/spatial.py | muv/spatial.py | """
Spatial statistics.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "3-clause BSD"
import numpy as np
def spread(d, t):
"""
Calculate the spread between two sets of compounds.
Given a matrix containing distances between two sets of compounds, A
... | """
Spatial statistics.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "3-clause BSD"
import numpy as np
def spread(d, t):
"""
Calculate the spread between two sets of compounds.
Given a matrix containing distances between two sets of compounds, A
... | bsd-3-clause | Python |
e05736cd36bc595070dda78e91bcb1b4bcfd983c | Remove deprecated usage of `reflect` constructor param | globality-corp/microcosm-postgres,globality-corp/microcosm-postgres | microcosm_postgres/operations.py | microcosm_postgres/operations.py | """
Common database operations.
"""
from sqlalchemy import MetaData
from sqlalchemy.exc import ProgrammingError
from microcosm_postgres.migrate import main
from microcosm_postgres.models import Model
def stamp_head(graph):
"""
Stamp the database with the current head revision.
"""
main(graph, "stam... | """
Common database operations.
"""
from sqlalchemy import MetaData
from sqlalchemy.exc import ProgrammingError
from microcosm_postgres.migrate import main
from microcosm_postgres.models import Model
def stamp_head(graph):
"""
Stamp the database with the current head revision.
"""
main(graph, "stam... | apache-2.0 | Python |
c7f8fd75dd5b41a059b65e9cea54d875d1f57655 | Change self to PortStatCollector. | ramjothikumar/Diamond,jaingaurav/Diamond,timchenxiaoyu/Diamond,TAKEALOT/Diamond,MichaelDoyle/Diamond,acquia/Diamond,rtoma/Diamond,Clever/Diamond,russss/Diamond,zoidbergwill/Diamond,socialwareinc/Diamond,actmd/Diamond,anandbhoraskar/Diamond,Ssawa/Diamond,zoidbergwill/Diamond,stuartbfox/Diamond,Netuitive/netuitive-diamon... | src/collectors/portstat/portstat.py | src/collectors/portstat/portstat.py | """
The PortStatCollector collects metrics about ports listed in config file.
##### Dependencies
* psutil
"""
from collections import Counter
import psutil
import diamond.collector
class PortStatCollector(diamond.collector.Collector):
def __init__(self, *args, **kwargs):
super(PortStatCollector, sel... | """
The PortStatCollector collects metrics about ports listed in config file.
##### Dependencies
* psutil
"""
from collections import Counter
import psutil
import diamond.collector
class PortStatCollector(diamond.collector.Collector):
def __init__(self, *args, **kwargs):
super(PortStatCollector, sel... | mit | Python |
0744dba6a52c42dbe6f9ba360e5311a1f90c3550 | Fix python 3 compatibility issue in DNSimple driver. | Kami/libcloud,Kami/libcloud,curoverse/libcloud,carletes/libcloud,t-tran/libcloud,jimbobhickville/libcloud,mgogoulos/libcloud,ZuluPro/libcloud,sahildua2305/libcloud,ByteInternet/libcloud,pquentin/libcloud,mistio/libcloud,samuelchong/libcloud,vongazman/libcloud,pquentin/libcloud,mistio/libcloud,t-tran/libcloud,wrigri/lib... | libcloud/common/dnsimple.py | libcloud/common/dnsimple.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 use ... | # 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 use ... | apache-2.0 | Python |
725b246a0bbb437a5a0efeb16b58d3942f3b14cc | Update the example client. | flowroute/txjason | examples/client.py | examples/client.py | from twisted.internet import defer, endpoints, task
from txjason.netstring import JSONRPCClientFactory
from txjason.client import JSONRPCClientError
client = JSONRPCClientFactory('127.0.0.1', 7080)
@defer.inlineCallbacks
def main(reactor, description):
endpoint = endpoints.clientFromString(reactor, description)... | from twisted.internet import reactor, defer
from txjason.netstring import JSONRPCClientFactory
from txjason.client import JSONRPCClientError
client = JSONRPCClientFactory('127.0.0.1', 7080)
@defer.inlineCallbacks
def stuff():
try:
r = yield client.callRemote('bar.foo')
except JSONRPCClientError as e... | mit | Python |
5dddadb98340fec6afda80fd1a8ee1eda907b60a | print exports to terminal | willmcgugan/rich | examples/export.py | examples/export.py | """
Demonstrates export console output
"""
from rich.console import Console
from rich.table import Table
console = Console(record=True)
def print_table():
table = Table(title="Star Wars Movies")
table.add_column("Released", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
tabl... | """
Demonstrates export console output
"""
from rich.console import Console
from rich.table import Table
console = Console(record=True)
def print_table():
table = Table(title="Star Wars Movies")
table.add_column("Released", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
tabl... | mit | Python |
1741c7258ebdcef412442cebab33409290496df0 | Add network example | ktkirk/HSSI,ktkirk/HSSI,ktkirk/HSSI | IoT/iot_utils.py | IoT/iot_utils.py | from __future__ import print_function
import sys, signal, atexit
import json
__author__ = 'KT Kirk'
__all__ = ['keys', 'atexit', 'signal']
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you... | from __future__ import print_function
import sys, signal, atexit
import json
__author__ = 'KT Kirk'
__all__ = ['keys', 'atexit', 'signal']
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you... | bsd-2-clause | Python |
b07243a6fb11dbbd487ba37620f7c8f4fc89449a | bump version to v1.10.5 | simomarsili/ndd | ndd/package.py | ndd/package.py | # -*- coding: utf-8 -*-
"""Template package file"""
__title__ = 'ndd'
__version__ = '1.10.5'
__author__ = 'Simone Marsili'
__summary__ = ''
__url__ = 'https://github.com/simomarsili/ndd'
__email__ = 'simo.marsili@gmail.com'
__license__ = 'BSD 3-Clause'
__copyright__ = 'Copyright (c) 2020, Simone Marsili'
__classifiers_... | # -*- coding: utf-8 -*-
"""Template package file"""
__title__ = 'ndd'
__version__ = '1.10.4'
__author__ = 'Simone Marsili'
__summary__ = ''
__url__ = 'https://github.com/simomarsili/ndd'
__email__ = 'simo.marsili@gmail.com'
__license__ = 'BSD 3-Clause'
__copyright__ = 'Copyright (c) 2020, Simone Marsili'
__classifiers_... | bsd-3-clause | Python |
5848a9c64744eacf8d90a86335e948ed17ef8346 | Correct path to workflows | ASaiM/framework,ASaiM/framework | src/prepare_asaim/import_workflows.py | src/prepare_asaim/import_workflows.py | #!/usr/bin/env python
import os
from bioblend import galaxy
admin_email = os.environ.get('GALAXY_DEFAULT_ADMIN_USER', 'admin@galaxy.org')
admin_pass = os.environ.get('GALAXY_DEFAULT_ADMIN_PASSWORD', 'admin')
url = "http://localhost:8080"
gi = galaxy.GalaxyInstance(url=url, email=admin_email, password=admin_pass)
wf... | #!/usr/bin/env python
import os
from bioblend import galaxy
admin_email = os.environ.get('GALAXY_DEFAULT_ADMIN_USER', 'admin@galaxy.org')
admin_pass = os.environ.get('GALAXY_DEFAULT_ADMIN_PASSWORD', 'admin')
url = "http://localhost:8080"
gi = galaxy.GalaxyInstance(url=url, email=admin_email, password=admin_pass)
wf... | apache-2.0 | Python |
0d31cbfd3042a1e7255ed833715112504fe608ae | Revert types | daeyun/dshinpy,daeyun/dshinpy | dshin/nn/types.py | dshin/nn/types.py | """
TensorFlow type annotation aliases.
"""
import typing
import tensorflow as tf
Value = typing.Union[tf.Variable, tf.Tensor]
Values = typing.Sequence[Value]
Named = typing.Union[tf.Variable, tf.Tensor, tf.Operation]
NamedSeq = typing.Sequence[Named]
Tensors = typing.Sequence[tf.Tensor]
Variables = typing.Sequence[t... | """
TensorFlow type annotation aliases.
"""
import typing
import tensorflow as tf
Value = (tf.Variable, tf.Tensor)
Values = typing.Sequence[Value]
Named = (tf.Variable, tf.Tensor, tf.Operation)
NamedSeq = typing.Sequence[Named]
Tensors = typing.Sequence[tf.Tensor]
Variables = typing.Sequence[tf.Variable]
Operations =... | mpl-2.0 | Python |
8a3ae1b809d886f647f13574cc9b416b17c27b7c | Remove VERSION variable from api.py | ivankliuk/duckduckpy | duckduckpy/api.py | duckduckpy/api.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __init__ import __version__
from collections import namedtuple
from duckduckpy.utils import camel_to_snake_case
SERVER_HOST = 'api.duckduckgo.com'
USER_AGENT = 'duckduckpy {0}'.format(__version__)
ICON_KEYS = set(['URL', 'Width', 'Height'])
RESULT_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import namedtuple
from utils import camel_to_snake_case
SERVER_HOST = 'api.duckduckgo.com'
VERSION = '0.1-alpha'
USER_AGENT = 'duckduckpy {0}'.format(VERSION)
ICON_KEYS = set(['URL', 'Width', 'Height'])
RESULT_KEYS = set(['FirstURL', 'I... | mit | Python |
70f588282e1777945e113e73dbca83f77355f0f9 | Test git permission | IEEERobotics/bot,IEEERobotics/bot,deepakiam/bot,deepakiam/bot,IEEERobotics/bot,deepakiam/bot | driver/omni_driver.py | driver/omni_driver.py | import driver
import lib.lib as lib
from hardware.dmcc_motor import DMCCMotorSet
class OmniDriver(driver.Driver):
#Vijay was here
#Chad was here | import driver
import lib.lib as lib
from hardware.dmcc_motor import DMCCMotorSet
class OmniDriver(driver.Driver):
#Vijay was here
| bsd-2-clause | Python |
a3f12245163a9165f45f4ee97b6e4e67cdd29783 | Update decipher.py | khemritolya/decipher.py | decipher.py | decipher.py | #
# decipher.py (c) Luis Hoderlein
#
# BUILT: Apr 21, 2016
#
# This program can brute force Cesarian ciphers
# It gives you all possible outputs, meaning you still have to chose the output you want
#
# imports
import string
# adds padding to make output inline
def pad(num):
if num < 10:
return "0"+str(num)
else:... | #
# decipher.py (c) Luis Hoderlein
#
# BUILT: Apr 21, 2016
#
# This program can brute force Cesarian ciphers
# It gives you all possible outputs, meaning you still have to chose the output you want
#
import string
def pad(num):
if num < 10:
return "0"+str(num)
else:
return str(num)
raw_txt = raw_input("Enter ... | apache-2.0 | Python |
f421b2997494ca546c6479e4246456e56b816e60 | Add Robert EVT ID too | pebble/libpebble2 | libpebble2/util/hardware.py | libpebble2/util/hardware.py | __author__ = 'katharine'
class PebbleHardware(object):
UNKNOWN = 0
TINTIN_EV1 = 1
TINTIN_EV2 = 2
TINTIN_EV2_3 = 3
TINTIN_EV2_4 = 4
TINTIN_V1_5 = 5
BIANCA = 6
SNOWY_EVT2 = 7
SNOWY_DVT = 8
SPALDING_EVT = 9
BOBBY_SMILES = 10
SPALDING = 11
SILK_EVT = 12
ROBERT_EVT =... | __author__ = 'katharine'
class PebbleHardware(object):
UNKNOWN = 0
TINTIN_EV1 = 1
TINTIN_EV2 = 2
TINTIN_EV2_3 = 3
TINTIN_EV2_4 = 4
TINTIN_V1_5 = 5
BIANCA = 6
SNOWY_EVT2 = 7
SNOWY_DVT = 8
SPALDING_EVT = 9
BOBBY_SMILES = 10
SPALDING = 11
SILK_EVT = 12
SILK = 14
... | mit | Python |
d9af336506fcca40cbc5ebf337268cfd16459c4f | Use iter_log in example. | jelmer/subvertpy,jelmer/subvertpy | examples/ra_log.py | examples/ra_log.py | #!/usr/bin/python
# Demonstrates how to iterate over the log of a Subversion repository.
from subvertpy.ra import RemoteAccess
conn = RemoteAccess("svn://svn.samba.org/subvertpy/trunk")
for (changed_paths, rev, revprops, has_children) in conn.iter_log(paths=None,
start=0, end=conn.get_latest_revnum(), discov... | #!/usr/bin/python
# Demonstrates how to iterate over the log of a Subversion repository.
from subvertpy.ra import RemoteAccess
conn = RemoteAccess("svn://svn.gnome.org/svn/gnome-specimen/trunk")
def cb(changed_paths, rev, revprops, has_children=None):
print "=" * 79
print "%d:" % rev
print "Revision prop... | lgpl-2.1 | Python |
1d0d28ebdda25a7dc579857063d47c5042e6c02b | Enable south for the docs site. | alawnchen/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoproject.com,khkaminska/djangoproject.com,rmoorman/djangoproject.com,relekang/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,alawnchen/djangoproject.com,xavierdutreilh/djangoproject.com,rmoorman/djangoproject.com,relekang... | django_docs/settings.py | django_docs/settings.py | # Settings for docs.djangoproject.com
from django_www.common_settings import *
### Django settings
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
INSTALLED_APPS = [
'django.contrib.sitemaps',
'django.contrib.sites',
'django.contrib.staticfiles',
'djangosecure',
'haystack',
'south',
'docs'... | # Settings for docs.djangoproject.com
from django_www.common_settings import *
### Django settings
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'
INSTALLED_APPS = [
'django.contrib.sitemaps',
'django.contrib.sites',
'django.contrib.staticfiles',
'djangosecure',
'haystack',
'docs',
]
MIDDLEWA... | bsd-3-clause | Python |
3434c404d8ab3d42bed4756338f1b8dba3a10255 | split debug_plot into debug and plot | zutshi/S3CAMR,zutshi/S3CAMR,zutshi/S3CAMR | src/settings.py | src/settings.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
debug = False
debug_plot = False
plot = False
# CE hack is ON
CE = True
def plt_show():
from matplotlib import pyplot as plt
if debug_plot or (debug and plot)... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
debug = False
debug_plot = False
plot = False
# CE hack is ON
CE = True
def plt_show():
from matplotlib import pyplot as plt
if debug_plot:
plt.show()... | bsd-2-clause | Python |
00c14e981807668b09a5d6a2e71fe8872291acad | Add admin support for attachments | leifurhauks/django-mailbox,Shekharrajak/django-mailbox,coddingtonbear/django-mailbox,ad-m/django-mailbox | django_mailbox/admin.py | django_mailbox/admin.py | from django.conf import settings
from django.contrib import admin
from django_mailbox.models import MessageAttachment, Message, Mailbox
def get_new_mail(mailbox_admin, request, queryset):
for mailbox in queryset.all():
mailbox.get_new_mail()
get_new_mail.short_description = 'Get new mail'
class MailboxAd... | from django.conf import settings
from django.contrib import admin
from django_mailbox.models import Message, Mailbox
def get_new_mail(mailbox_admin, request, queryset):
for mailbox in queryset.all():
mailbox.get_new_mail()
get_new_mail.short_description = 'Get new mail'
class MailboxAdmin(admin.ModelAdmi... | mit | Python |
48c880a35c899929da33f20e9cd4ee7e4fd8bc7e | Set a custom name template including the replica set | hudl/Tyr | servers/mongo/data.py | servers/mongo/data.py | from .. import Server
import logging
class MongoDataNode(Server):
log = logging.getLogger('Servers.MongoDataNode')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s [%(name)s] %(levelname)s: %(message)s',
... | from .. import Server
import logging
class MongoDataNode(Server):
log = logging.getLogger('Servers.MongoDataNode')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s [%(name)s] %(levelname)s: %(message)s',
... | unlicense | Python |
71289d3a22476001421454ff736ea03742e43158 | Add basic parser | praekelt/vumi-twilio-api | vumi_twilio_api/twilml_parser.py | vumi_twilio_api/twilml_parser.py | import xml.etree.ElementTree as ET
class Verb(object):
"""Represents a single verb in TwilML. """
def __init__(self, verb, attributes={}, nouns={}):
self.verb = verb
self.attributes = attributes
self.nouns = nouns
class TwilMLParseError(Exception):
"""Raised when trying to parse... | class Verb(object):
"""Represents a single verb in TwilML. """
def __init__(self, verb, attributes={}, nouns={}):
self.verb = verb
self.attributes = attributes
self.nouns = nouns
| bsd-3-clause | Python |
a49095bf078603e046288629aa8497f031ed6bd3 | Add transpose_join, joins 2 infinite lists by transposing the next elements | muddyfish/PYKE,muddyfish/PYKE | node/divide.py | node/divide.py | #!/usr/bin/env python
from nodes import Node
from type.type_infinite_list import DummyList
class Divide(Node):
char = "/"
args = 2
results = 1
@Node.test_func([4, 2], [2])
@Node.test_func([2, 4], [0.5])
def func(self, a: Node.number, b: Node.number):
"""a/b. floating point division.
... | #!/usr/bin/env python
from nodes import Node
class Divide(Node):
"""
Takes two items from the stack and divides them
"""
char = "/"
args = 2
results = 1
@Node.test_func([4,2], [2])
@Node.test_func([2,4], [0.5])
def func(self, a: Node.number, b: Node.number):
"""a/b... | mit | Python |
87d792fda8763f49d83ce274015f3a436a0c89cc | send message after stuff is started | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty | dusty/commands/run.py | dusty/commands/run.py |
from ..compiler import (compose as compose_compiler, nginx as nginx_compiler,
port_spec as port_spec_compiler, spec_assembler)
from ..systems import compose, hosts, nginx, virtualbox
def start_local_env():
""" This command will use the compilers to get compose specs
will pass those spe... |
from ..compiler import (compose as compose_compiler, nginx as nginx_compiler,
port_spec as port_spec_compiler, spec_assembler)
from ..systems import compose, hosts, nginx, virtualbox
def start_local_env():
""" This command will use the compilers to get compose specs
will pass those spe... | mit | Python |
7f2ac925b2343e57ad7f4a6d79ee24e14c8f4d78 | Add a Bazel rule assignment_notebook(). | google/prog-edu-assistant,google/prog-edu-assistant,google/prog-edu-assistant,google/prog-edu-assistant | exercises/defs.bzl | exercises/defs.bzl | # TODO(salikh): Implement the automatic tar rules too
def assignment_notebook_macro(
name,
srcs,
language = None,
visibility = ["//visibility:private"]):
"""
Defines a rule for student notebook and autograder
generation from a master notebook.
Arguments:
name:
srcs: the file name of the inp... | # TODO(salikh): Implement the automatic tar rules too
def assignment_notebook_macro(
name,
srcs,
language = None,
visibility = ["//visibility:private"]):
"""
Defines a rule for student notebook and autograder
generation from a master notebook.
Arguments:
name:
srcs: the file name of the inp... | apache-2.0 | Python |
f274f927d600989db1d485212d116166695e6edd | Use keyword arguments for readability | eugene-eeo/scell | scell/core.py | scell/core.py | """
scell.core
~~~~~~~~~~
Provides abstractions over lower level APIs and
file objects and their interests.
"""
from select import select as _select
from collections import namedtuple
def select(rl, wl, timeout=None):
"""
Returns the file objects ready for reading/writing
from the read-... | """
scell.core
~~~~~~~~~~
Provides abstractions over lower level APIs and
file objects and their interests.
"""
from select import select as _select
from collections import namedtuple
def select(rl, wl, timeout=None):
"""
Returns the file objects ready for reading/writing
from the read-... | mit | Python |
e7cce08f32516bc8b15df7eee0c285eebe795cab | Make it easier to filter on multiple field values | alphagov/govuk-content-explorer,alphagov/govuk-content-explorer | explorer/search.py | explorer/search.py | from . import config
from .document import Document
import requests
from time import time
def perform_search(**params):
response = requests.get(
config.GOVUK_SEARCH_API,
params=params,
auth=config.AUTH,
)
return response.json()
def fetch_documents(scope):
documents = perform_... | from . import config
from .document import Document
import requests
from time import time
def perform_search(**params):
response = requests.get(
config.GOVUK_SEARCH_API,
params=params,
auth=config.AUTH,
)
return response.json()
def fetch_documents(scope):
documents = perform_... | mit | Python |
10d0b7c452c8d9d5893cfe612e0beaa738f61628 | Add to template builtins only if add_to_buitlins is available (Django <= 1.8) | nigma/django-easy-pjax,nigma/django-easy-pjax,nigma/django-easy-pjax | easy_pjax/__init__.py | easy_pjax/__init__.py | #-*- coding: utf-8 -*-
"""
Register filter so it is available for use in the `extends` template tag
(The `extends` tag must come first in a template, so regular `load` is not
an option).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__version__ = "1.2.0"
has_add_to_builtins ... | #-*- coding: utf-8 -*-
"""
Register filter so it is available for use in the `extends` template tag
(The `extends` tag must come first in a template, so regular `load` is not
an option).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__version__ = "1.2.0"
try:
from djang... | bsd-3-clause | Python |
e145ef6ca54c9615f038601da17daf16550196d6 | Use environment variables to locate Windows GStreamer includes | dturing/node-gstreamer-superficial,dturing/node-gstreamer-superficial | binding.gyp | binding.gyp | {
"targets": [
{
"target_name": "gstreamer-superficial",
"sources": [ "gstreamer.cpp", "GLibHelpers.cpp", "GObjectWrap.cpp", "Pipeline.cpp" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"cflags": [
"-Wno-cast-function-type"
],
"conditions" : [
["OS=='linux'", {
"in... | {
"targets": [
{
"target_name": "gstreamer-superficial",
"sources": [ "gstreamer.cpp", "GLibHelpers.cpp", "GObjectWrap.cpp", "Pipeline.cpp" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"cflags": [
"-Wno-cast-function-type"
],
"conditions" : [
["OS=='linux'", {
"in... | mit | Python |
043a0ad774964d2608ee1c8bd8ba1abc5b2ed0b4 | Tweak binding.gyp so it doesn't error out on Windows | enlight/node-unix-pty,enlight/node-unix-pty,enlight/node-unix-pty | binding.gyp | binding.gyp | {
'targets': [{
'target_name': 'pty',
'conditions': [
['OS!="win"', {
'include_dirs' : [
'<!(node -e "require(\'nan\')")'
],
'sources': [
'src/unix/pty.cc'
],
'libraries': [
'-lutil',
'-L/usr/lib',
'-L/usr/local/li... | {
'conditions': [
['OS!="win"', {
'targets': [{
'target_name': 'pty',
'include_dirs' : [
'<!(node -e "require(\'nan\')")'
],
'sources': [
'src/unix/pty.cc'
],
'libraries': [
'-lutil',
'-L/usr/lib',
'-L/usr/loca... | mit | Python |
5a6f748981554cb4d4aa0b5500a9b86bd09eb1b5 | Add Linux static bindings | lgeiger/zmq-prebuilt,lgeiger/zmq-prebuilt,interpretor/zeromq.js,lgeiger/zmq-prebuilt,interpretor/zeromq.js,lgeiger/zmq-prebuilt,interpretor/zeromq.js,interpretor/zeromq.js,interpretor/zeromq.js,lgeiger/zmq-prebuilt | binding.gyp | binding.gyp | {
'targets': [
{
'target_name': 'zmq',
'sources': [ 'binding.cc' ],
'include_dirs' : [
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'win_delay_load_hook': 'true',
'include_dirs': ['windows/include'],
'link_settings'... | {
'targets': [
{
'target_name': 'zmq',
'sources': [ 'binding.cc' ],
'include_dirs' : [
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'win_delay_load_hook': 'true',
'include_dirs': ['windows/include'],
'link_settings'... | mit | Python |
777bb37f9ac4457dca79a07953356ce46b941a30 | change '-std=c++11' to '-std=c++0x' for linux | rick68/eigenjs,rick68/eigenjs,rick68/eigenjs | binding.gyp | binding.gyp | {
'targets': [
{
'target_name': 'eigen',
'sources': [
'src/EigenJS.cpp'
],
'include_dirs': [
'deps',
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
... | {
'targets': [
{
'target_name': 'eigen',
'sources': [
'src/EigenJS.cpp'
],
'include_dirs': [
'deps',
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
... | mpl-2.0 | Python |
786e7d83672ad5ff2718c9a440dbd180f8e7b24a | make addon buildable as static library (#119) | christkv/kerberos,christkv/kerberos,christkv/kerberos,christkv/kerberos | binding.gyp | binding.gyp | {
'targets': [
{
'target_name': 'kerberos',
'type': 'loadable_module',
'include_dirs': [ '<!(node -e "require(\'nan\')")' ],
'sources': [
'src/kerberos.cc'
],
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.12',
'OTHER_CFLAGS': [
"-std=c++1... | {
'targets': [
{
'target_name': 'kerberos',
'include_dirs': [ '<!(node -e "require(\'nan\')")' ],
'sources': [
'src/kerberos.cc'
],
'xcode_settings': {
'MACOSX_DEPLOYMENT_TARGET': '10.12',
'OTHER_CFLAGS': [
"-std=c++11",
"-stdlib=libc++"
... | apache-2.0 | Python |
b6208c1f9b6f0afca1dff40a66d2c915594b1946 | Add exception hook to help diagnose server test errors in python3 gui mode | caseyclements/blaze,dwillmer/blaze,jcrist/blaze,mrocklin/blaze,cowlicks/blaze,ContinuumIO/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,aterrel/blaze,nkhuyu/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,FrancescAlted/blaze,ChinaQuants/blaze,markflorisson/blaze-core,alexmojaki/blaze,alexmojaki/bl... | blaze/io/server/tests/start_simple_server.py | blaze/io/server/tests/start_simple_server.py | """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
... | """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
| bsd-3-clause | Python |
826698c9894ce94c625718eb041ce817eb6ab5ef | Update config.dist.py | projectshift/shift-boiler,projectshift/shift-boiler,projectshift/shift-boiler | boiler/boiler_template/config/config.dist.py | boiler/boiler_template/config/config.dist.py | from project.backend import config
class DefaultConfig(config.DefaultConfig):
""" Local development config """
# set this for offline mode
SERVER_NAME = None
SECRET_KEY = None
class DevConfig(config.DevConfig, DefaultConfig):
""" Local development config """
pass
class TestingConfig(config... | from project.backend import config
class DefaultConfig(config.DefaultConfig):
""" Local development config """
# set this for offline mode
SERVER_NAME = None
SECRET_KEY = None
class DevConfig(config.DevConfig, DefaultConfig):
""" Local development config """
pass
class TestingConfig(config... | mit | Python |
4c4b1e6a4bde5edb9e11942245a21437e73fe6df | fix link creation | pirate/bookmark-archiver,pirate/bookmark-archiver,pirate/bookmark-archiver | archivebox/index/sql.py | archivebox/index/sql.py | __package__ = 'archivebox.index'
from io import StringIO
from typing import List, Tuple, Iterator
from .schema import Link
from ..util import enforce_types
from ..config import setup_django, OUTPUT_DIR
### Main Links Index
@enforce_types
def parse_sql_main_index(out_dir: str=OUTPUT_DIR) -> Iterator[Link]:
setu... | __package__ = 'archivebox.index'
from io import StringIO
from typing import List, Tuple, Iterator
from .schema import Link
from ..util import enforce_types
from ..config import setup_django, OUTPUT_DIR
### Main Links Index
@enforce_types
def parse_sql_main_index(out_dir: str=OUTPUT_DIR) -> Iterator[Link]:
setu... | mit | Python |
efdf4a4898cc3b5217ac5e45e75a74e19eee95d4 | bump version | google/evojax | evojax/version.py | evojax/version.py | __version__ = "0.1.0-14"
| __version__ = "0.1.0-13"
| apache-2.0 | Python |
155c953f7bf8590b4a11547369bee29baa5ea5f6 | Fix typo. | jsharkey13/isaac-selenium-testing,jsharkey13/isaac-selenium-testing | isaactest/tests/numeric_q_all_correct.py | isaactest/tests/numeric_q_all_correct.py | import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.isaac import answer_numeric_q
from ..utils.i_selenium import assert_tab, image_div
from ..utils.i_selenium import wait_for_xpath_element
from ..tests import TestWithDependency
from selenium.common.exceptions import TimeoutException, NoSuchElementEx... | import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.isaac import answer_numeric_q
from ..utils.i_selenium import assert_tab, image_div
from ..utils.i_selenium import wait_for_xpath_element
from ..tests import TestWithDependency
from selenium.common.exceptions import TimeoutException, NoSuchElementEx... | mit | Python |
aabc4bc60f0c8b6db21453dd6fad387773b18e55 | Fix a print | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine | openquake/commands/__main__.py | openquake/commands/__main__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2015-2018 GEM Foundation
#
# OpenQuake 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 ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2015-2018 GEM Foundation
#
# OpenQuake 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 ... | agpl-3.0 | Python |
2a13f4d21085228a1ef615eec8a3e42110c315d3 | Make test pass | undertherain/benchmarker,undertherain/benchmarker,undertherain/benchmarker,undertherain/benchmarker | benchmarker/modules/problems/cnn2d_toy/pytorch.py | benchmarker/modules/problems/cnn2d_toy/pytorch.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from benchmarker.modules.problems.helpers_torch import Net4Inference, Net4Train
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=2)
self.conv2 ... | import torch
import torch.nn as nn
import torch.nn.functional as F
from benchmarker.modules.problems.helpers_torch import Net4Inference, Net4Train
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=2)
self.conv2 =... | mpl-2.0 | Python |
f6e93144a2471ef22883f4db935a499463a76824 | fix sytanx errors | Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python,Show-Me-the-Code/python | will/0003/into_redis.py | will/0003/into_redis.py | # 第 0003 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
import random, string, time, math, uuid, redis
chars = string.ascii_letters + string.digits
def gen1():
key = ''.join(random.sample(chars, 10))
#key2 = ''.join(random.choice(chars) for i in range(10))
return key
def gen2():
key = math.modf(ti... | # 第 0003 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
import random, string, time, math, uuid, redis
chars = string.ascii_letters + string.digits
def gen1():
key = ''.join(random.sample(chars, 10))
#key2 = ''.join(random.choice(chars) for i in range(10))
return key
def gen2():
key = math.modf(ti... | mit | Python |
3b564cdd4adbf3185d2f18ec6eedbf4b87057cf5 | Add virus fixture to conftest | igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool | conftest.py | conftest.py | from virtool.tests.fixtures.db import *
from virtool.tests.fixtures.documents import *
from virtool.tests.fixtures.client import *
from virtool.tests.fixtures.core import *
from virtool.tests.fixtures.hmm import *
from virtool.tests.fixtures.users import *
from virtool.tests.fixtures.viruses import *
def pytest_addop... | from virtool.tests.fixtures.db import *
from virtool.tests.fixtures.documents import *
from virtool.tests.fixtures.client import *
from virtool.tests.fixtures.core import *
from virtool.tests.fixtures.hmm import *
from virtool.tests.fixtures.users import *
def pytest_addoption(parser):
parser.addoption("--quick",... | mit | Python |
900de7c14607fbe2936fa682d03747916337f075 | Fix the reactor_pytest fixture. | eLRuLL/scrapy,eLRuLL/scrapy,pablohoffman/scrapy,scrapy/scrapy,pawelmhm/scrapy,elacuesta/scrapy,scrapy/scrapy,pablohoffman/scrapy,pablohoffman/scrapy,dangra/scrapy,starrify/scrapy,eLRuLL/scrapy,pawelmhm/scrapy,dangra/scrapy,starrify/scrapy,starrify/scrapy,pawelmhm/scrapy,scrapy/scrapy,elacuesta/scrapy,elacuesta/scrapy,d... | conftest.py | conftest.py | from pathlib import Path
import pytest
def _py_files(folder):
return (str(p) for p in Path(folder).rglob('*.py'))
collect_ignore = [
# not a test, but looks like a test
"scrapy/utils/testsite.py",
# contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess
*_py_files("tests/... | from pathlib import Path
import pytest
def _py_files(folder):
return (str(p) for p in Path(folder).rglob('*.py'))
collect_ignore = [
# not a test, but looks like a test
"scrapy/utils/testsite.py",
# contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess
*_py_files("tests/... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.