code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
import unittest
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from scipy.sparse import csr_matrix
from graphs.base import Graph
PAIRS = np.array([[0,1],[0,2],[1,1],[2,1],[3,3]])
ADJ = [[0,1,1,0],
[0,1,0,0],
[0,1,0,0],
[0,0,0,1]]
class TestStaticConst... | all-umass/graphs | graphs/base/tests/test_static.py | Python | mit | 2,529 |
# This was pulled from one of the python/opencv sites appearing
# in a Google search. Need to find site and add attribution!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# USAGE: You need to specify a filter and "only one" image source
#
# (python) range-detector --filter RGB --image /path/to/image.png
# or
# (pytho... | jgerschler/ESL-Games | Camera Pistol/range-detector.py | Python | mit | 1,679 |
import gevent
from cloudly.pubsub import RedisWebSocket
from cloudly.tweets import Tweets, StreamManager, keep
from cloudly import logger
from webapp import config
log = logger.init(__name__)
pubsub = RedisWebSocket(config.pubsub_channel)
pubsub.spawn()
running = False
def processor(tweets):
pubsub.publish(kee... | hdemers/webapp-template | webapp/publish.py | Python | mit | 1,031 |
# -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem416.py
#
# A frog's trip
# =============
# Published on Saturday, 23rd February 2013, 01:00 pm
#
# A row of n squares contains a frog in the leftmost square. By successive
# jumps the frog goes to the rightmost square and then back to the leftmost
# square. On t... | olduvaihand/ProjectEuler | src/python/problem416.py | Python | mit | 878 |
import logging
from six import wraps
from settings import Settings
logger = logging.getLogger(__name__)
settings = Settings()
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
list_of_admins = settings.get_value('LIST_OF_ADMINS')
user_id = update.effective_user.... | peleccom/rpi_telegram_bot | utils.py | Python | mit | 536 |
#
# Message for spark-python-sdk
# Started on 19/04/2017 by Antoine
#
class Message:
def __init__(self):
self.id = None
self.roomId = None
self.toPersonId = None
self.toPersonEmail = None
self.personId = None
self.personEmail = None
self.text = None
... | Bassintag551/spark-python-sdk | sparkpy/Message.py | Python | mit | 513 |
# -*- coding: utf-8 -*-
from .input import Input
class ListInput(Input):
"""
ListInput represents an input provided as an array.
Usage:
>>> input_ = ListInput([('name', 'foo'), ('--bar', 'foobar')])
"""
def __init__(self, parameters, definition=None):
"""
Constructor
... | Romibuzi/cleo | cleo/inputs/list_input.py | Python | mit | 4,973 |
# -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
pytestmark = pytest.mark.django_db
global_footer_links = [
'About',
'Developers',
'Privacy',
'Report an issue',
]
def assert_title_and_links_on_page(browser, url, title, links_text):
browser.visit(url)
assert... | vipul-sharma20/fossevents.in | tests/frontend/test_page_contents.py | Python | mit | 869 |
#collection of stuff to make postgres easier
import psycopg2
import os
pgConnectionString = "dbname=" + os.environ['PGNAME'] + " user=" + os.environ['PGUSER'] + " password=" + os.environ['PGPASS']
pg = psycopg2.connect(pgConnectionString)
pgCursor = pg.cursor()
def close():
pg.commit()
pgCursor.close()
pg... | nthitz/dreamlastnight | pgutils.py | Python | mit | 1,920 |
# -*- coding: utf-8 -*-
#
# hdfs documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 6 16:04:56 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | laserson/hdfs | doc/conf.py | Python | mit | 10,413 |
# -*- coding: utf-8 -*-
"""UnitTests for airwaveapiclient."""
import os
import unittest
from airwaveapiclient import APDetail
from airwaveapiclient.tests import test_utils
class APDetailUnitTests(unittest.TestCase):
"""Class APDetailUnitTests.
Unit test for APDetail.
"""
def setUp(self):
... | mtoshi/airwaveapiclient | airwaveapiclient/tests/test_apdetail.py | Python | mit | 1,068 |
"""nest_webapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | babsey/nest-webapp | tryouts/django/nest_webapp/urls.py | Python | mit | 1,044 |
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.forms.models import model_to_dict
from django.forms.util import ErrorList
from django.template import RequestContext
from django.db import IntegrityError
from django.core.exceptions import Objec... | vault/bugit | user_manage/views.py | Python | mit | 4,105 |
import numpy as np
import pypolyagamma as pypolyagamma
def calculate_D(S):
N = S.shape[1]
D = np.empty((N, N))
for i in range(N):
for j in range(N):
D[i, j] = np.dot(S[1:, i].T, S[:-1, j])
return D * 0.5
def calculate_C_w(S, w_i):
w_mat = np.diag(w_i)
return np.dot(S.... | noashin/Ising_model_gibbs_sampler | sampler_no_sparsity.py | Python | mit | 2,260 |
import _plotly_utils.basevalidators
class MetasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="metasrc", parent_name="scattercarpet", **kwargs):
super(MetasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/scattercarpet/_metasrc.py | Python | mit | 444 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from struct import *
import hashlib
if len(sys.argv) != 2:
print("Usage " + sys.argv[0] + " input_file")
sys.exit(1)
in_name = sys.argv[1]
def dumpHeader(f):
# check for signature
sig = f.read(3)
if sig != b'FLV':
... | r0ro/tools | flv_dissector.py | Python | mit | 6,068 |
'''
Mac OS X file chooser
---------------------
'''
from plyer.facades import FileChooser
from pyobjus import autoclass, objc_arr, objc_str
from pyobjus.dylib_manager import load_framework, INCLUDE
load_framework(INCLUDE.AppKit)
NSURL = autoclass('NSURL')
NSOpenPanel = autoclass('NSOpenPanel')
NSSavePanel = autoclass... | KeyWeeUsr/plyer | plyer/platforms/macosx/filechooser.py | Python | mit | 3,427 |
"""Tools for working with Gensim models."""
| jamesmishra/nlp-playground | nlp_playground/lib/gensim/__init__.py | Python | mit | 44 |
import datetime
from urlparse import urlparse
from utils import log as logging
from django.shortcuts import get_object_or_404, render_to_response
from django.views.decorators.http import condition
from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponse, Http404
from django.conf import settings... | nriley/NewsBlur | apps/rss_feeds/views.py | Python | mit | 21,500 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2017-2019 4k1
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... | 4k1/wufuzzer | src/util.py | Python | mit | 2,921 |
from __future__ import unicode_literals
from django.db import models
class Attendance(models.Model):
pass
| cloudartisan/dojomaster | apps/attendance/models.py | Python | mit | 113 |
#!/bin/python
import math
def SumOfFactors(f_1, f_2):
for key in f_2.keys():
if (key in f_1):
f_1[key] += f_2[key]
else:
f_1[key] = f_2[key]
return f_1;
def PrimeFactorsOfNumber(n):
sqrt_n = int(math.sqrt(n))
if (n == sqrt_n * sqrt_n):
# Perfect square
return SumOfFactors(
P... | aawc/ProjectEuler | 05/evenlyDivisible.py | Python | mit | 1,404 |
from twilio.twiml.voice_response import Connect, VoiceResponse, Say, VirtualAgent
response = VoiceResponse()
response.say('Hello! You will be now be connected to a virtual agent.')
connect = Connect(action='https://myactionurl.com/virtualagent_ended')
connect.virtual_agent(
connector_name='project', status_callbac... | TwilioDevEd/api-snippets | twiml/voice/connect/virtualagent-2/virtualagent-2.6.x.py | Python | mit | 394 |
"""
Synthesise a QA module into the B100 FPGA.
"""
import os
import shutil
import subprocess
from jinja2 import Environment, FileSystemLoader
from fpga_sdrlib import config
from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn
b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100')
custom_src_dir = o... | benreynwar/fpga-sdrlib | python/fpga_sdrlib/b100.py | Python | mit | 3,118 |
import re
class Directions(object):
DIRECTIONAL = {
"north":"N",
"northeast":"NE",
"east":"E",
"southeast":"SE",
"south":"S",
"southwest":"SW",
"west":"W",
"northwest":"NW"}
DIRECTIONAL_CODES = dict((v,k) for k,v in DIRECTIONAL.iteritems())
class Streets(object):
STREET_TYPES = {
"allee":"aly",
... | fgregg/streetaddress-us | addressconf.py | Python | mit | 10,198 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import enum
import logging
import os
import sys
from collections import defaultdict
import configargparse
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.a... | compbiol/CAMSA | camsa/utils/agp/agp2camsa_points.py | Python | mit | 10,726 |
__author__ = 'sam'
import webargs
from .string import lowercase, strip
def not_null(value):
"""A validation function that checks that a value isn't None."""
return True if value is not None else False
def not_empty(value):
"""
Check if a value is not empty.
This is a simple check that blocks n... | marcellarius/webargscontrib.utils | webargscontrib/utils/validate.py | Python | mit | 2,307 |
from sense_hat import SenseHat
sense = SenseHat()
X = [255, 0, 0] # Red
O = [255, 255, 255] # White
up_arrow = [
O, O, O, X, X, O, O, O,
O, O, X, X, X, X, O, O,
O, X, X, X, X, X, X, O,
O, O, O, X, X, O, O, O,
O, O, O, X, X, O, O, O,
O, O, O, X, X, O, O, O,
O, O, O, X, X, O, O, O,
O, O, O, X, X, O, O, O
]
sense.set_... | seattleacademy/fall27 | arrowup.py | Python | mit | 336 |
from typing import Callable, List, Optional, TypeVar
from reactivex import Observable, abc, compose
from reactivex import operators as ops
from reactivex import typing
_T = TypeVar("_T")
def buffer_with_time_(
timespan: typing.RelativeTime,
timeshift: Optional[typing.RelativeTime] = None,
scheduler: Opt... | ReactiveX/RxPY | reactivex/operators/_bufferwithtime.py | Python | mit | 619 |
import os
import sys
from setuptools import setup
version = '1.6.2.dev0'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel upload')
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
print(" git push --tags")... | jaap3/django-richtextfield | setup.py | Python | mit | 1,486 |
#!/usr/bin/env python3
#
# Copyright 2021 Andrey Izman <izmanw@gmail.com>
#
# 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 requir... | mervick/material-design-icons | scripts/download_fonts.py | Python | mit | 4,860 |
#!/usr/bin/env python3
import argparse
import dataclasses
from array import array
from .edr import (EDRHeader, EDRDisplayDataHeader, EDRSpectralDataHeader)
def parse_args():
parser = argparse.ArgumentParser(description='Print .edr file')
parser.add_argument('edr',
type=argparse.FileTy... | illicium/ccss2edr | ccss2edr/dumpedr.py | Python | mit | 1,581 |
#!/usr/bin/env python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import os
import scipy.io
from PyTrilinos import Epetra, EpetraExt, AztecOO, ML, Amesos
from scipy2Trilinos import ... | wathen/PhD | MHD/FEniCS/FieldSplit/NSpicard.py | Python | mit | 8,721 |
import numpy, sys, os, pylab, astropy, astropy.io.fits as pyfits, ldac, math
def open_and_get_shearcat(filename, tablename):
#
# for opening and retrieving shear cat.
#
return ldac.openObjectFile(filename, tablename)
#class ello
def avg_shear(g1array, g2array):
avg1 = numpy.mean(g1array)... | deapplegate/wtgpipeline | quality_studies_psf.py | Python | mit | 15,321 |
import os, random
import numpy as np
import pandas as pd
def pctrank(data):
return pd.Series(data).rank(pct=True).iloc[-1]
def get_csv_file(days=252, datadir="", filename=""):
try_random = 10
name = None
data = None
while try_random:
if not datadir or not os.path.isdir(datadir):
... | TheGU/deep_trading_notebook | omstang_lib/market_data.py | Python | mit | 3,626 |
import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def __init__(self):
self.mean = [(self.max_x-se... | drakipovic/deep-learning | 1. labos/data.py | Python | mit | 2,378 |
from milk.plugin import Plugin
class testplugin3(Plugin):
def __init__(self, config):
for key, value in config.items():
print("%s: %s" % (key, value))
| hk4n/milk | tests/resources/test_plugins/testplugin3.py | Python | mit | 177 |
from kafka import KafkaProducer
#oducer = KafkaProducer(bootstrap_servers='kafka-kf.kafka.svc.cluster.local:9092')
producer = KafkaProducer(bootstrap_servers='localhost:9092')
producer.send('test', 'hello')
| madcore-ai/containers | kfn/examples/producer.py | Python | mit | 207 |
# -*- coding: utf-8 -*-
"""A manager for looking up nodes."""
from typing import List, Optional
from sqlalchemy import and_
from .base_manager import BaseManager
from .models import Author, Citation, Edge, Evidence, Node
from ..constants import CITATION_TYPE_PUBMED
from ..dsl import BaseEntity
class LookupManager... | pybel/pybel | src/pybel/manager/lookup_manager.py | Python | mit | 3,569 |
"""
Updated on 19.12.2009
@author: alen, pinda
"""
from django.conf import settings
from django.conf.urls.defaults import *
from socialregistration.utils import OpenID, OAuthClient, OAuthTwitter, OAuthLinkedin
urlpatterns = patterns('',
url('^setup/$', 'socialregistration.views.setup',
name='socialregi... | nvbn/django-socialregistration | socialregistration/urls.py | Python | mit | 4,237 |
"""
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
Input: root = [1,null,2]
Ou... | franklingu/leetcode-solutions | questions/binary-tree-inorder-traversal/Solution.py | Python | mit | 1,084 |
"""Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input:
["eat", "tea", "tan", "ate", "nat", "bat"]
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of y... | aiden0z/snippets | leetcode/049_group_anagrams.py | Python | mit | 1,315 |
u"""
This is the daemon that must be launched in order to detect motion
and launch signals.
"""
from __future__ import unicode_literals
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from detection import PirDetector
from busy_processor import RoomBusyStatus
import settings
# Importing motion listeners
... | gleseur/room-status | detector/daemon.py | Python | mit | 1,629 |
import os
import sys
import RTIMU
import schedule
import GeneralSettings
from Utility.abstract_process import processAbstract
import time
class imuHandler(processAbstract):
#SETTINGS_FILE = GeneralSettings.IMU_SETTINGS_FILE
def __init__(self, antenna_data):
processAbstract.__init__(self)
self... | Dronolab/antenna-tracking | Sensors/imuAbstract.py | Python | mit | 1,320 |
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnu... | tuxar-uk/Merlyn | x/slave.py | Python | mit | 3,181 |
import os
from unittest import mock
import pytest
@pytest.fixture(autouse=True, scope='function')
def clean_environment():
"""Ensure all tests start with a clean environment.
Even if tests properly clean up after themselves, we still need this in
case the user runs tests with an already-polluted environ... | Yelp/dumb-init | tests/conftest.py | Python | mit | 1,129 |
"""Add Brief.is_a_copy boolean, default False, nullable False
Revision ID: 890
Revises: 880
Create Date: 2017-06-01 11:24:53.346954
"""
# revision identifiers, used by Alembic.
revision = '900'
down_revision = '890'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('briefs', sa.Colum... | alphagov/digitalmarketplace-api | migrations/versions/900_add_brief_is_a_copy.py | Python | mit | 461 |
#!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 The Electrum developers
#
# 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... | argentumproject/electrum-arg | plugins/hw_wallet/hw_wallet.py | Python | mit | 3,347 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .dos_plotter import DOSPlotter
__author__ = "Yuji Ikeda"
class TotalDOSPlotter(DOSPlotter):
def load_data(self, data_file='total_dos.dat'):
supe... | yuzie007/ph_plotter | ph_plotter/total_dos_plotter.py | Python | mit | 1,815 |
class Stock():
def __init__(self, name, symbol, prices=[]):
self.name = name
self.symbol = symbol
self.prices = prices
def high_price(self):
if len(self.prices) == 0:
return 'MISSING PRICES'
return max(self.prices)
apple = Stock('Apple', 'APPL', [500.43, 570... | schmit/intro-python-course | lectures/code/classes_stocks.py | Python | mit | 351 |
# Import the necessary modules.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.optimize
import glob
import skimage.io
import skimage.morphology
import scipy.constants
# Define functions from Justin Bois
# Fit symmetric Gaussian to x, y, z data
def fit_gaussian(x, y, z):
"""
... | RPGroup-PBoC/gist_pboc_2017 | code/gaussian_trap_stiffness.py | Python | mit | 3,972 |
from .utils import AtlanticBase
from .image import AtlanticImage
from .plan import AtlanticPlan
from .server import AtlanticServer
from .sshkey import AtlanticSSHKey
class Atlantic(AtlanticBase):
def __init__(self, access_key, private_key):
AtlanticBase.__init__(self, access_key, private_key)
self.... | kbrebanov/atlantic-python | atlantic/atlantic.py | Python | mit | 549 |
"""Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... | carloscadena/django-imager | imagersite/imager_api/tests.py | Python | mit | 2,994 |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.exceptions import CloseSpider
from scrapy import Request, FormRequest, Selector
from datetime import date
from collections import OrderedDict
from json import loads
from random import randint
import json, re, collections
import datetime, time
import logging
# Remove... | hanjihun/Car | compreseguros_com/compreseguros_com/spiders/compreseguros_com_spider.py | Python | mit | 8,164 |
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from core.models import Organization, Note, CrawlScope
class OrganizationInline(admin.TabularInline):
model = Organization
class NoteInline(GenericStackedInline):
model = Note
fields = ('when_created', '... | CobwebOrg/cobweb-django | core/admin_inlines.py | Python | mit | 489 |
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
from unittest import TestCase
from tests import utils
from yawast import main
from yawast._version ... | adamcaudill/yawast | tests/test_print_header.py | Python | mit | 640 |
#!/usr/bin/env python
from commands import getoutput
import os
import multiprocessing
import rospy
from std_msgs.msg import Int16
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
from ros_homebot_msgs import msg as msgs
from ros_homebot_python import constants as c
OK = DiagnosticStatus.O... | chrisspen/homebot | src/ros/src/ros_homebot/nodes/system_node.py | Python | mit | 12,231 |
"""Multiple Factor Analysis (MFA)"""
import itertools
from matplotlib import markers
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import utils
from . import mca
from . import one_hot
from . import pca
from . import plot
class MFA(pca.PCA):
def __init__(self, groups=None, ... | MaxHalford/Prince | prince/mfa.py | Python | mit | 8,572 |
import json
import logging
import re
logger = logging.getLogger(__name__)
csRegStr4Hash = '\B(?P<Type>[\@\#\$\%\&])(?P<Text>\S+)'
def FindHashes(srcStr, RegStr):
#\B(?P<Type>[\@\#\$\%\&])(?P<Text>\S+)
regex = r'' +RegStr
matches = re.finditer(regex, srcStr, re.IGNORECASE | re.UNICODE) #
plain = []
for matc... | SpyDeX/BeepMiBot | bot/event_handler.py | Python | mit | 3,806 |
# standard
import datetime
def now():
return int(datetime.datetime.now().strftime("%s"))
def load(timestamp):
return datetime.datetime.fromtimestamp(timestamp)
| MattCCS/PyVault | pyvault/crypto/datetime_utils.py | Python | mit | 173 |
#!/usr/bin/env python
# Copyright(C) 2011-2016 Thomas Voegtlin
#
# 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, m... | bauerj/electrum-server | src/processor.py | Python | mit | 9,045 |
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello world")
def home(request):
datetime.datetime.now()
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
def hours_ahead(request, offset... | arventwei/django_test | mysite/mysite/view.py | Python | mit | 589 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-15 04:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('asserts', '0006_auto_20170515_1227'),
]
operations =... | larry16898/oms | asserts/migrations/0007_auto_20170515_1241.py | Python | mit | 996 |
#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-
"""
This module defines the TableGenerator class.
Part of the pydbcollector package.
by @f03lipe, 2011-2012
"""
from queryassembler import QueryAssembler
from dataparser import DataParser
import sys
# year ranges to iterate through
ANOS_FHC = range(1995, 2003)
ANOS_L... | f03lipe/eMec-db-retriever | src/tablegenerator.py | Python | mit | 22,135 |
def get_numbers_between(set_a, set_b):
numbers_between = 0
for candidate in range(1, 101):
found = True
for item in set_a:
if candidate % item:
found = False
break
if not found:
continue
for item in set_b:
if... | avenet/hackerrank | algorithms/implementation/between_two_sets.py | Python | mit | 723 |
from utils import *
from server import app
def db_get_collaborators_for_list(list_id):
''' Returns a list of all collaborators for a list from the database '''
query = '''
SELECT user_id
FROM Collaborators
WHERE list_id = ?;
'''
with app.app_context():
db = get_db()
... | FroeMic/CDTM-Backend-Workshop-WT2016 | solutions/server/server-15-crud-collaborator/server/database/collaborator.py | Python | mit | 1,155 |
from autosar.base import splitRef
from autosar.element import Element
import sys
class SystemSignal(Element):
def __init__(self,name,dataTypeRef,initValueRef,length,desc=None,parent=None):
super().__init__(name,parent)
self.dataTypeRef=dataTypeRef
self.initValueRef=initValueRef
... | cogu/autosar | autosar/signal.py | Python | mit | 1,012 |
import rethinkdb as r
from remodel.connection import pool
class Remodel(object):
def __init__(self, app=None, db=None):
self.app = app
self.db = db
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('REMODEL_POOL_SIZE', 5)
... | linkyndy/flask-remodel | flask_remodel/__init__.py | Python | mit | 854 |
from future import standard_library
standard_library.install_aliases()
from builtins import str
from bson import ObjectId
import urllib.request, urllib.error, urllib.parse
import json
import time
def test_general_simple_task_one(worker):
result = worker.send_task(
"tests.tasks.general.Add", {"a": 41, "b"... | Serenytics/mrq | tests/test_general.py | Python | mit | 5,482 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import urllib
import urllib2
import httplib
import lxml.etree as et
def check_pdb_status(pdbids):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
pdbids = [p.upper() for p in pdbids]
pdbids = ','.join(pdbids)
... | lituan/tools | pdb_download.py | Python | cc0-1.0 | 4,472 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
import unittest
test_dependencies = ["Product Bundle"]
class TestQuotation(unittest.TestCase):
def test_ma... | Aptitudetech/ERPNext | erpnext/selling/doctype/quotation/test_quotation.py | Python | cc0-1.0 | 2,733 |
#!/usr/bin/env python2
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from os.path import expanduser
import scipy
def treegrass_frac(ndvi, day_rs):
"""
Process based on Donohue et al. (2009) to separate out tree and grass cov... | rhyswhitley/savanna_iav | src/figures/modchecks/test_phenology.py | Python | cc0-1.0 | 3,041 |
import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... | JohanComparat/nbody-npt-functions | bin/bin_SMHMr/MD10-pie-plot.py | Python | cc0-1.0 | 5,119 |
###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | sadanandb/pmt | src/pyasm/prod/biz/prod_setting.py | Python | epl-1.0 | 5,082 |
#
# The OpenDiamond Platform for Interactive Search
#
# Copyright (c) 2009-2019 Carnegie Mellon University
# All rights reserved.
#
# This software is distributed under the terms of the Eclipse Public
# License, Version 1.0 which can be found in the file named LICENSE.
# ANY USE, REPRODUCTION OR DISTRIBUTION OF T... | cmusatyalab/opendiamond | opendiamond/scopeserver/gigapan/views.py | Python | epl-1.0 | 4,425 |
from django.contrib import admin
from rawParser.models import flightSearch
# Register your models here.
admin.site.register(flightSearch)
| anantag/flightsearch | backend/flightsearch/rawParser/admin.py | Python | gpl-2.0 | 139 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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... | lehmannro/translate | storage/csvl10n.py | Python | gpl-2.0 | 7,279 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Datetools provide a method of manipulating and working dates and times.
# Copyright (C) 2013-2018 Chris Caron <lead2gold@gmail.com>
#
# This file is part of Datetools. Datetools is free software; you can
# redistribute it and/or modify it under the terms of the GNU Gener... | caronc/datetools | src/pytest.py | Python | gpl-2.0 | 2,031 |
__author__ = 'bromix'
import xbmcgui
from ..abstract_progress_dialog import AbstractProgressDialog
class XbmcProgressDialog(AbstractProgressDialog):
def __init__(self, heading, text):
AbstractProgressDialog.__init__(self, 100)
self._dialog = xbmcgui.DialogProgress()
self._dialog.create(he... | repotvsupertuga/tvsupertuga.repository | plugin.video.youtube/resources/lib/youtube_plugin/kodion/impl/xbmc/xbmc_progress_dialog.py | Python | gpl-2.0 | 911 |
"""
Generate archetypes from the DESI ELG basis spectra.
"""
from __future__ import division, print_function
import os
import sys
import numpy as np
import argparse
import pdb
from astropy.io import fits
from astropy.table import Table
from SetCoverPy.mathutils import quick_amplitude
from desispec.log import get... | moustakas/impy | projects/desi-archetypes/elg-archetypes.py | Python | gpl-2.0 | 1,011 |
"""
Django settings for ldap_manager project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build... | mdaif/LDAP-Manager | ldap_manager/settings.py | Python | gpl-2.0 | 2,724 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
script.skin.helper.service
Helper service and scripts for Kodi skins
plugin_content.py
Hidden plugin entry point providing some helper features
'''
import xbmc
import xbmcplugin
import xbmcgui
import xbmcaddon
from simplecache import SimpleCache
from utils... | skyfsza/Logos | resources/lib/plugin_content.py | Python | gpl-2.0 | 15,952 |
# Copyright (C) 2007-2018 David Aguilar and contributors
"""Miscellaneous Qt utility functions."""
from __future__ import division, absolute_import, unicode_literals
import os
from qtpy import compat
from qtpy import QtGui
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore i... | antoniodemora/git-cola | cola/qtutils.py | Python | gpl-2.0 | 30,765 |
print "Loading USBDriver : Logitech Cordless RumblePad 2"
class USBDriver :
def __init__(self):
self.componentNextThrottleFrame = "Hat Switch" # Component for throttle frames browsing
self.valueNextThrottleFrame = 0.5
self.componentPreviousThrottleFrame = "Hat Switch"
self.v... | ctag/cpe453 | JMRI/jython/Jynstruments/ThrottleWindowToolBar/USBThrottle.jyn/LogitechCordlessRumblePad2.py | Python | gpl-2.0 | 5,884 |
from untwisted.network import spawn
from untwisted.event import get_event
from untwisted.splits import Terminator
from re import *
GENERAL_STR = '[^ ]+'
GENERAL_REG = compile(GENERAL_STR)
SESSION_STR = '\*\*\*\* Starting FICS session as (?P<username>.+) \*\*\*\*'
SESSION_REG = compile(SESSION_STR)
TELL_STR = '(?P<... | iogf/steinitz | steinitz/fics.py | Python | gpl-2.0 | 1,786 |
"""
Programmer : EOF
E-mail : jasonleaster@163.com
File : svm.py
Date : 2015.12.13
You know ... It's hard time but it's not too bad to say give up.
"""
import numpy
class SVM:
def __init__(self, Mat, Tag, C = 2, MAXITER = 200):
self._Mat = numpy.array(Mat)
self._Tag =... | jasonleaster/Machine_Learning | SVM/svm.py | Python | gpl-2.0 | 9,610 |
import threading,signal ,traceback
import random,ctypes,math,time,copy,Queue
import numpy
from dsp import common
from GlobalData import *
from common import Rx,Tx
_funclist = {}
def reg_func(func,param_types,param_defaults):
ret = False
try:
_funclist[func.__name__]=(func,param_types,param_defaults)
... | wzyy2/HackRFWebtools | func.py | Python | gpl-2.0 | 6,028 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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 2, or (at your option)
any later version.
This Program is distributed in the hope th... | gezb/osmc | package/a2dp-app-osmc/files/usr/share/kodi/addons/service.osmc.btplayer/service.py | Python | gpl-2.0 | 8,958 |
"""
WSGI config for lolcomp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lolcomp.settings")
from django.core.w... | code-wukong/lolcomp | lolcomp/wsgi.py | Python | gpl-2.0 | 702 |
import sys
import multiprocessing
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from scripts_EM import mrc2mrc as m
# class test_files_operations(unittest.TestCase):
#
# def setUp(self):
# self.files = ['1.mrc', '2.mrc', '3.mrc']
# self.tempdir = te... | AGMMGA/EM_scripts | EM_scripts/tests/mrc2mrc_tests.py | Python | gpl-2.0 | 8,856 |
# coding : utf-8
#file: Reduce.py
import os,os.path,re
def Reduce(sourceFoler,targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #判断是reduce文件
sFile = open(o... | FannyCheung/python_Machine-Learning | MapReduce处理日志文件/Reduce.py | Python | gpl-2.0 | 1,172 |
# -*- coding: utf-8 -*-
import pyodbc
cs = {
'server':'ahwsqlinind019.ind1.stvincent.org',
'database':'st2cpr1.tst_153',
#'database':'st1bprvb.st1',
'user':'scmis',
'pw':'year04',
}
conn = pyodbc.connect(
driver='{SQL Server}',
server=cs['server'],
uid=cs['user'],
pwd=cs['pw'],
)
... | whichwit/scm-stv | mlms/_get-mlms.py | Python | gpl-2.0 | 725 |
#!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... | BackupTheBerlios/honeyspy-svn | junk/sshsimpleserver.py | Python | gpl-2.0 | 4,759 |
# -*- coding: utf-8 -*-
import pytest
from cfme import login
from cfme import test_requirements
from cfme.configure.settings import visual
from cfme.cloud.availability_zone import AvailabilityZone
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.openstack import OpenStackProvider
from cfme.cloud.... | rananda/cfme_tests | cfme/tests/configure/test_visual_cloud.py | Python | gpl-2.0 | 5,512 |
register(GRAMPLET,
id="Python Gramplet",
name=_("Python Shell"),
description = _("Interactive Python interpreter"),
status = STABLE,
fname="PythonGramplet.py",
height=250,
gramplet = 'PythonGramplet',
gramplet_title=_("Python Shell"),
vers... | gramps-project/addons-source | PythonGramplet/PythonGramplet.gpr.py | Python | gpl-2.0 | 423 |
## system-config-printer
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Red Hat, Inc.
## Authors:
## Florian Festi <ffesti@redhat.com>
## Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as ... | hamonikr-root/system-config-printer-gnome | cupshelpers/cupshelpers.py | Python | gpl-2.0 | 29,800 |
#!/usr/bin/env python
"""
filegen.py
File generation utility.
Copyright (C) 2013 William Kettler <william.p.kettler@gmail.com>
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 ... | wkettler/pyio | filegen.py | Python | gpl-2.0 | 4,738 |
#!/usr/bin/env python
# Copyright (C) 2011 Aaron Lindsay <aaron@aclindsay.com>
#
# 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 2 of the License, or
# (at your op... | aclindsa/asink-python | src/shared/daemon.py | Python | gpl-2.0 | 3,138 |
from __future__ import print_function
from scipy.ndimage import gaussian_filter
import numpy as np
from PIL import Image
img = np.asarray(Image.open('../Klimt/Klimt.ppm'))
img_gray = np.asarray(Image.open('../Klimt/Klimt.pgm'))
print('img:', img.shape)
sigmas = [0.5, 2, 5, 7]
for sigma in sigmas:
print('sigma:', ... | lagadic/ViSP-images | Gaussian-filter/Gaussian_filter.py | Python | gpl-2.0 | 838 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_default_data(apps, schema_editor):
#removed_duplicated(apps, schema_editor)
FileLog = apps.get_model("core", "FileLog")
for it in FileLog.objects.exclude(path=""):
it.url=it.path
... | BlackSmith/GreenTea | apps/core/migrations/0015_auto_20160509_1446.py | Python | gpl-2.0 | 1,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.