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 os
from carton.cart import Cart
from django.contrib import messages
from django.shortcuts import render, redirect
from django.template.response import TemplateResponse
from django.views.generic import View
from authentication.views import LoginRequiredMixin
from deals.models import Deal
from .models import Us... | andela/troupon | troupon/cart/views.py | Python | mit | 6,304 |
from django.views.generic import ListView
from django.http import HttpResponse
from .models import Job
from geoq.maps.models import FeatureType
from django.shortcuts import get_object_or_404
from datetime import datetime
from pytz import timezone
from webcolors import name_to_hex, normalize_hex
from xml.sax.saxutils i... | ngageoint/geoq | geoq/core/kml_view.py | Python | mit | 12,540 |
try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... | pterk/django-tcc | tcc/templatetags/autopaginator.py | Python | mit | 9,909 |
"""
General descrition of your module here.
"""
from functools import partial
from maya import OpenMaya
from maya import OpenMayaUI
from maya import cmds
from PySide import QtCore
from PySide import QtGui
from shiboken import wrapInstance
from shiboken import getCppPointer
class RbfSettings(o... | cedricB/circeCharacterWorksTools | rbfTool.py | Python | mit | 9,899 |
# nvprof --print-gpu-trace python examples/stream/thrust.py
import cupy
x = cupy.array([1, 3, 2])
expected = x.sort()
cupy.cuda.Device().synchronize()
stream = cupy.cuda.stream.Stream()
with stream:
y = x.sort()
stream.synchronize()
cupy.testing.assert_array_equal(y, expected)
stream = cupy.cuda.stream.Stream()
... | cupy/cupy | examples/stream/thrust.py | Python | mit | 412 |
# -*- coding: utf-8 -*-
__author__ = 'glow'
import requests
import json
server = "http://fhir.careevolution.com/apitest/fhir"
client = requests.Session()
response = client.get(server + "/Patient?_id=23&_format=application/json+fhir")
print(response)
print(response.json())
| glow-mdsol/fhirton | servers.py | Python | mit | 278 |
from __future__ import with_statement
import sys
from xml.sax import saxutils
from keyword import kwlist as PYTHON_KWORD_LIST
is_py2 = sys.version[0] == '2'
if is_py2:
from StringIO import StringIO
else:
from io import StringIO
__all__ = ['Builder', 'Element']
__license__ = 'BSD'
__version__ = ... | PeteCrighton/Praesence | praesence/xmlwitch.py | Python | mit | 3,819 |
# This script demonstrates that font effects specified in your pdftex.map
# are now supported in pdf usetex.
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex=True)
def setfont(font):
return r'\font\a %s at 14pt\a ' % font
for y, font, text in zip(range(5),
... | bundgus/python-playground | matplotlib-playground/examples/pylab_examples/usetex_fonteffects.py | Python | mit | 789 |
from typing import Optional
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.bend_euler import bend_euler
from gdsfactory.components.coupler90 import coupler90 as coupler90function
from gdsfactory.components.coupler_straight import (
coupler_straight as coupler_straight... | gdsfactory/gdsfactory | gdsfactory/components/coupler_ring.py | Python | mit | 2,846 |
import logging
import os
import sys
import tkinter
from tkinter import ttk
sys.path.append('../..')
import cv2
from src.image.imnp import ImageNP
from src.support.tkconvert import TkConverter
from src.view.template import TkViewer
from src.view.tkfonts import TkFonts
from src.view.tkframe import TkFrame, TkLabelFrame
... | afunTW/moth-graphcut | src/view/graphcut_app.py | Python | mit | 11,346 |
from utils.api_factory import ApiFactory
api = ApiFactory.get_instance()
if __name__ == '__main__':
api.run(host='0.0.0.0', port=8000)
| istinspring/imscrape-template | api.py | Python | mit | 143 |
import json, io, re, requests
from bs4 import BeautifulSoup
from datetime import datetime
def get_datasets(url):
r = requests.get(url.format(0))
soup = BeautifulSoup(r.text)
href = soup.select('#block-system-main a')[-1]['href']
last_page = int(re.match(r'.*page=(.*)', href).group(1))
for page in... | nbi-opendata/metadaten-scraper | get-metadata.py | Python | mit | 3,412 |
# models.py
import os
import socket
import datetime
import random
import re
from django import forms
from django import urls
from django.db import models
from django.db.models.signals import pre_save
from .unique_slugify import unique_slugify
from .titlecase import titlecase
from functools import reduce
def time2s(... | CarlFK/veyepar | dj/main/models.py | Python | mit | 22,252 |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 12:14:03 2015
@author: ktritz
"""
from __future__ import print_function
from builtins import str, range
import inspect
import types
#import numpy as np
from collections.abc import MutableMapping
from .container import containerClassFactory
class Shot(MutableMapping)... | drsmith48/fdp | fdp/lib/shot.py | Python | mit | 4,629 |
# -*- coding: utf-8 -*-
import unittest
from pyparsing import ParseException
from cwr.grammar.field import basic
"""
Tests for Table/List Lookup (L) fields.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class TestLookupName(unittest.TestCase):
def test_name_defaul... | weso/CWR-DataApi | tests/grammar/field/test_lookup.py | Python | mit | 2,301 |
import numpy as np
from numba import njit as jit
@jit
def _kepler_equation(E, M, ecc):
return E_to_M(E, ecc) - M
@jit
def _kepler_equation_prime(E, M, ecc):
return 1 - ecc * np.cos(E)
@jit
def _kepler_equation_hyper(F, M, ecc):
return F_to_M(F, ecc) - M
@jit
def _kepler_equation_prime_hyper(F, M, ec... | poliastro/poliastro | src/poliastro/core/angles.py | Python | mit | 9,195 |
import numpy as np
def e_greedy(estimates, epsilon):
numBandits, numArms = estimates.shape
explore = np.zeros(numBandits)
explore[np.random.random(numBandits) <= epsilon] = 1
arm = np.argmax(estimates, axis=1)
arm[explore == 1] = np.random.randint(0, numArms, np.count_nonzero(explore))
return... | clarson469/reinforcementLearning | solutions/solution_util.py | Python | mit | 819 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 acrazing <joking.young@gmail.com>. All rights reserved.
# @since 2018-12-03 00:03:40
import time
from dbapi.DoubanAPI import DoubanAPI
class GroupAPI:
def __init__(self):
self.api = DoubanAPI(flush=False)
self._applied = {}
s... | acrazing/dbapi | scripts/join_group.py | Python | mit | 1,512 |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2016-2017 Peter Williams <peter@newton.cx> and collaborators
# Licensed under the MIT License
"""Various helpers for X-ray analysis that rely on CIAO tools.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = str('''
get_r... | pkgw/pwkit | pwkit/environments/ciao/analysis.py | Python | mit | 6,635 |
from checkpy.assertlib.basic import *
| Jelleas/CheckPy | checkpy/assertlib/__init__.py | Python | mit | 38 |
#!/usr/bin/python
import json, math, sys, string, random, subprocess, serial
from time import localtime, strftime, clock, time # for timestamping packets
import time
import hashlib #for checksum purposes
import mysql.connector # mysql database
import getpass
import urllib2
import requests
sys.path.append('/usr/lib/pyt... | cjordog/NRLWebsite | demo/uw1.py | Python | mit | 14,884 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "anigma1.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | aniruddhasanyal/idea_pot | manage.py | Python | mit | 805 |
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty
from .node import Node
from math import sqrt
class HexCanvas(FloatLayout):
last_node = ObjectProperty(None, allownone=True)
grid = ObjectProperty([])
row_count = ... | tls-dna/k-router | app_ui/hexcanvas.py | Python | mit | 1,599 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2015 Slack
#
# 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
... | Slack06/yadg | manage.py | Python | mit | 1,359 |
from mnist import MNIST
import numpy as np
from thirdparty import log_mvnpdf, log_mvnpdf_diag
data = MNIST('./data/mnist')
data.load_training()
data.load_testing()
train = np.array(data.train_images)/255.0
test = np.array(np.array(data.test_images)/255.0)
dataset = {i: [] for i in range(10) }
for it, x in enumerate(d... | m87/pyEM | lda.py | Python | mit | 696 |
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from provider import StackExchangeProvider
urlpatterns = default_urlpatterns(StackExchangeProvider)
| HackerEarth/django-allauth | allauth/socialaccount/providers/stackexchange/urls.py | Python | mit | 178 |
from __future__ import print_function
from __future__ import unicode_literals
import time
from netmiko.ssh_connection import BaseSSHConnection
from netmiko.netmiko_globals import MAX_BUFFER
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
import paramiko
import socket
class Ci... | enzzzy/netmiko | netmiko/cisco/cisco_wlc_ssh.py | Python | mit | 3,082 |
# coding:utf-8
# 测试多线程
import threading
import time
from utils import fn_timer
from multiprocessing.dummy import Pool
import requests
from utils import urls
# 耗时任务:听音乐
def music(name):
print 'I am listening to music {0}'.format(name)
time.sleep(1)
# 耗时任务:看电影
def movie(name):
print 'I am wa... | dnxbjyj/python-basic | concurrence/multi_threading.py | Python | mit | 4,446 |
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plot
import matplotlib.pylab
from matplotlib.backends.backend_pdf import PdfPages
import re
def drawPlots(data,plotObj,name,yLabel,position):
drawing = plotObj.add_subplot(position,1,position)
drawing.set_ylabel(yLabel, font... | nachiketkarmarkar/XtremPerfProbe | generatePlots.py | Python | mit | 6,181 |
import argparse
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFECV
from sklearn.ensemble import RandomForestClassifier
from beveridge.models import ModelStorage
import pickle
parser = argparse.ArgumentParser(description="Create model from CSV stats data.... | bairdj/beveridge | src/create_model.py | Python | mit | 3,408 |
import numpy as np
from scipy.io import netcdf_file
import bz2
import os
from fnmatch import fnmatch
from numba import jit
@jit
def binsum2D(data, i, j, Nx, Ny):
data_binned = np.zeros((Ny,Nx), dtype=data.dtype)
N = len(data)
for n in range(N):
data_binned[j[n],i[n]] += data[n]
return data_binn... | rabernat/satdatatools | satdatatools/aggregator.py | Python | mit | 1,349 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Stardust Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test spending coinbase transactions.
# The coinbase transaction in block N can appear in block
# N+1... | ctwiz/stardust | qa/rpc-tests/mempool_spendcoinbase.py | Python | mit | 2,474 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 16:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | rodrigocnascimento/django-teste | product/migrations/0010_auto_20170324_1304.py | Python | mit | 1,504 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
from elftools.elf.segments import NoteSegment
class ReadELF(object):
def __init__(self, file):
self.elffile = ELFFile(file)
def get_build(self):
f... | somat/samber | elf.py | Python | mit | 861 |
from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | urfonline/api | api/applications/views.py | Python | mit | 1,609 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# The MIT License (MIT)
# Copyright (c) 2018 Kevin Walchko
# see LICENSE for full details
##############################################
from pygecko.multiprocessing import geckopy
from pygecko.multiprocessing import GeckoSim... | walchko/pygecko | dev/cpp-simple/subpub.py | Python | mit | 1,370 |
from shinymud.lib.world import World
import json
world = World.get_world()
def to_bool(val):
"""Take a string representation of true or false and convert it to a boolean
value. Returns a boolean value or None, if no corresponding boolean value
exists.
"""
bool_states = {'true': True, 'false': False... | shinymud/ShinyMUD | src/shinymud/models/shiny_types.py | Python | mit | 2,852 |
GPIO_HUB_RST_N = 30
GPIO_UBLOX_RST_N = 32
GPIO_UBLOX_SAFEBOOT_N = 33
GPIO_UBLOX_PWR_EN = 34
GPIO_STM_RST_N = 124
GPIO_STM_BOOT0 = 134
def gpio_init(pin, output):
try:
with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f:
f.write(b"out" if output else b"in")
except Exception as e:
print(f"Fai... | vntarasov/openpilot | common/gpio.py | Python | mit | 568 |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... | raghavsub/gtkpass | gtkpass/main.py | Python | mit | 3,474 |
#!/usr/bin/env python
import re
from operator import itemgetter
ref_file = open('../../../data/RNA-seq_miR-124_miR-155_transfected_HeLa/gene_exp_miR-155_overexpression_RefSeq_Rep_isoforms.diff','r')
input_file = open('../../../result/mirage_output_rev_seed_miR-155_vs_RefSeq_NM_2015-07-30.txt','r')
output_file ... | Naoto-Imamachi/MIRAGE | scripts/module/preparation/AA2_add_miRNA_infor_miR-155_rev_seed.py | Python | mit | 1,046 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 20:47:53 2017
@author: fernando
"""
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.read_csv("/home/fernando/CoursePythonDS/DAT210x/Module3/Datasets/wheat.data")
print df.describe()
df[df... | FernanOrtega/DAT210x | Module3/notes/histogram_example.py | Python | mit | 446 |
import numpy as np
from tfs.core.util import run_once_for_each_obj
from tfs.core.initializer import DefaultInit
from tfs.core.loss import DefaultLoss
from tfs.core.regularizers import DefaultRegularizer
from tfs.core.monitor import DefaultMonitor
from tfs.core.optimizer import DefaultOptimizer
from tfs.core.layer impor... | crackhopper/TFS-toolbox | tfs/network/base.py | Python | mit | 15,008 |
"""
"""
import unittest
import arcpy
from gsfarc.test import config
class TestDataTypeStringArray(unittest.TestCase):
"""Tests the string array task datatype"""
@classmethod
def setUpClass(cls):
config.setup_idl_toolbox('test_datatype_stringarray','qa_idltaskengine_datatype_stringarray')
@... | geospatial-services-framework/gsfpyarc | gsfarc/test/test_datatype_stringarray.py | Python | mit | 803 |
# Import 'datasets' from 'sklearn'
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA, RandomizedPCA
import matplotlib.pyplot as plt
# Load in the 'digits' data
digits = datasets.load_digits()
# Print the 'digits' data
print(digits)
# Print the keys
print(digits.keys)
# Print out ... | monal94/digits-scikit-learn | main.py | Python | mit | 2,459 |
import os
import datetime
import logging
ORDER = 999
POSTS_PATH = 'posts/'
POSTS = []
from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode
def getNode(template, context=Context(), name='subject'):
"""
Get django block con... | Knownly/webcrafters.knownly.net | plugins/blog.py | Python | mit | 2,349 |
from __future__ import print_function
import os
import sys
import json
if __name__=='__main__':
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(SRC_ROOT)
from datetime import datetime
import requests
from jinja2 import Template
from jinja2 import Environment, PackageLoa... | jperelli/redmine2github | src/github_issues/github_issue_maker.py | Python | mit | 17,531 |
import pile
import matplotlib.pyplot as plt
import time
import random
x,y = [],[]
for i in range(0,10):
p = 10 ** i
print(i)
start = time.time()
pile.pile(p)
final = time.time()
delta = final - start
x.append(p)
y.append(delta)
plt.plot(x,y)
plt.ylabel("The time taken to compute the pile... | victor-cortez/Heimdall | pile/timer.py | Python | mit | 914 |
import os, sys
PATH = os.path.join(os.path.dirname(__file__), '..')
sys.path += [
os.path.join(PATH, 'project/apps'),
os.path.join(PATH, 'project'),
os.path.join(PATH, '..'),
PATH]
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.production'
import django.core.handlers.wsgi
application = django.core.hand... | claudiob/pypeton | pypeton/files/django/deploy/django_wsgi_production.py | Python | mit | 344 |
from django.core.urlresolvers import reverse
from django.test import TestCase as DjangoTestCase
from blognajd.models import Story, SiteSettings
from blognajd.sitemaps import StaticSitemap, StoriesSitemap
class StaticSitemap1TestCase(DjangoTestCase):
fixtures = ['sitesettings_tests.json']
def test_staticsite... | danirus/blognajd | blognajd/tests/test_sitemaps.py | Python | mit | 1,817 |
#!/usr/bin/python
import subprocess
import os
import time
import platform
import glob
import shutil
import csbuild
from csbuild import log
csbuild.Toolchain("gcc").Compiler().SetCppStandard("c++11")
csbuild.Toolchain("gcc").SetCxxCommand("clang++")
csbuild.Toolchain("gcc").Compiler().AddWarnFlags("all", "extra", "c... | 3Jade/Sprawl | make.py | Python | mit | 9,814 |
#
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... | geertj/gruvi | tests/perf_http.py | Python | mit | 2,074 |
#randNNIWalks.py
#writes random SPR walks to files
#calls GTP on each NNI random walk file to get
#the ditances between each tree and the first tree of the sequence
#the results are written to csv files with lines delimited by \t
import tree_utils as tu
import w_tree_utils as wtu
import os
import sys
import numpy as np... | alejandro-mc/trees | randNNIWalks.py | Python | mit | 4,063 |
# -*- coding: utf-8 -*-
import cv2
# device number "0"
cap = cv2.VideoCapture(0)
while(True):
# Capture a frame
ret, frame = cap.read()
# show on display
cv2.imshow('frame',frame)
# waiting for keyboard input
key = cv2.waitKey(1) & 0xFF
# Exit if "q" pressed
if key == ord('q'):
break
# Save if "s" pres... | tomoyuki-nakabayashi/ICS-IoT-hackathon | sample/python-camera/python-camera.py | Python | mit | 475 |
import importlib
from django.conf import settings
from django.views import View
class BaseView(View):
"""后台管理基类"""
def __init__(self):
self.context = {}
self.context["path"] = {}
def dispatch(self,request,*args,**kwargs):
_path = request.path_info.split("/")[1:]
self.contex... | wdcxc/blog | admin/views/base.py | Python | mit | 789 |
import _plotly_utils.basevalidators
class SymmetricValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="symmetric", parent_name="scatter3d.error_y", **kwargs
):
super(SymmetricValidator, self).__init__(
plotly_name=plotly_name,
pare... | plotly/python-api | packages/python/plotly/plotly/validators/scatter3d/error_y/_symmetric.py | Python | mit | 472 |
from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def oauthreturn():
code = request.args.get('code', '')
if code:
client = ... | liyigerry/caixiang | mysite/views/weibo/oauthreturn.py | Python | mit | 941 |
"""
WSGI config for billboards project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION... | serefimov/billboards | billboards/billboards/wsgi.py | Python | mit | 1,568 |
# !/usr/bin/env python
# coding: utf-8
__author__ = 'Moch'
import tornado.ioloop
import tornado.options
import tornado.httpserver
from application import application
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
def main():
tornado.options.pars... | snownothing/Python | web/server.py | Python | mit | 651 |
from stard.services import BaseService
class Service(BaseService):
def init_service(self):
self.add_parent('multiuser')
self.add_parent('dhcpcd')
self.add_parent('getty', terminal=1)
| DexterLB/stard | src/etc/stard/init.py | Python | mit | 212 |
import json
import enum
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib import request
class APINonSingle:
def __init__(self, api_key, agent = "webnews-python", webnews_base = "https://webnews.csh.rit.edu/"):
self.agent = agent
self.api_key = api_key
self.... | AndrewHanes/Python-Webnews | webnews/api.py | Python | mit | 2,609 |
from django.contrib import admin
from .models import User
from application.models import (Contact, Personal, Wife, Occupation, Children,
Hod, Committee, UserCommittee, Legal)
# Register your models here.
class ContactInline(admin.StackedInline):
model = Contact
class PersonalInli... | dhosterman/hebrew_order_david | accounts/admin.py | Python | mit | 1,111 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2022_01_02_preview/aio/operations/_agent_pools_operations.py | Python | mit | 30,148 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os
import sys
import uuid
import logging
import simplejson as json
import paho.mqtt.client as mqtt
from time import sleep
try:
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../')
from sanji.connect... | imZack/sanji | sanji/connection/mqtt.py | Python | mit | 4,240 |
# -*- coding: utf-8 -*-
from rest_framework import viewsets
from . import serializers, models
class FileViewSet(viewsets.ModelViewSet):
queryset = models.File.objects.all()
serializer_class = serializers.FileSerializer
| nathanhi/deepserve | deepserve/fileupload/views.py | Python | mit | 231 |
import json
f = open('stations.json')
dict = json.load(f)
f.close()
tables = ["|station_id|group_id|name|type|", "|---:|---:|:--:|:--:|"]
row = "|%s|%s|%s|%s|"
stations = dict['stations']
for s in stations:
r = row % (s['station_id'], s['group_id'], s['station_name'], s['station_type'])
tables.append(r)
md ... | upamune/weatherhist | tools/gen_table.py | Python | mit | 422 |
#!/usr/bin/env python
from nodes import Node
class Input(Node):
char = "z"
args = 0
results = 1
contents = ""
def func(self):
"""input() or Input.contents"""
return input() or Input.contents | muddyfish/PYKE | node/input.py | Python | mit | 228 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.conf import settings
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"""Set site domain and name."""
Site = orm['sites.Site']
site = Site.ob... | somethingnew2-0/distadmin | distadmin/users/migrations/0002_set_site_domain_and_name.py | Python | mit | 4,351 |
from django.db import models
from cms.models import CMSPlugin
from community.models import Clan, Member, Game
from django.utils.translation import ugettext as _
class Match(models.Model):
datetime = models.DateTimeField(_("Date"))
game = models.ForeignKey(Game, verbose_name=_("Game"))
clanA = models.ForeignKey(Clan... | Zundrium/djangocms-gamegroup | matches/models.py | Python | mit | 967 |
from....import a
from...import b
from..import c
from.import d
from : keyword.control.import.python, source.python
.... : punctuation.separator.period.python, source.python
import : keyword.control.import.python, source.python
: source.python
a : source.python
from ... | MagicStack/MagicPython | test/statements/import3.py | Python | mit | 1,061 |
"""
WSGI config for Courseware 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Courseware.settings")
from django.... | shayan72/Courseware | Courseware/wsgi.py | Python | mit | 395 |
import numpy as np
import six
import tensorflow as tf
from tensorflow_probability.python.bijectors.masked_autoregressive import (
AutoregressiveNetwork, _create_degrees, _create_input_order,
_make_dense_autoregressive_masks, _make_masked_constraint,
_make_masked_initializer)
from tensorflow_probability.pyth... | imito/odin | odin/bay/layers/autoregressive_layers.py | Python | mit | 6,507 |
import os
from pyelliptic.openssl import OpenSSL
def randomBytes(n):
try:
return os.urandom(n)
except NotImplementedError:
return OpenSSL.rand(n)
| hb9kns/PyBitmessage | src/helper_random.py | Python | mit | 172 |
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple
from limits.storage.registry import StorageRegistry
from limits.util import LazyDependency
class Storage(LazyDependency, metaclass=StorageRegistry):
"""
Base class to extend when implementing an async storage backend.
.. ... | alisaifee/limits | limits/aio/storage/base.py | Python | mit | 2,931 |
def DataToTreat(Catalogue = 'WHT_observations'):
Catalogue_Dictionary = {}
if Catalogue == 'WHT_observations':
Catalogue_Dictionary['Folder'] = '/home/vital/Dropbox/Astrophysics/Data/WHT_observations/'
Catalogue_Dictionary['Datatype'] = 'WHT'
Catalogue_Dictionary['Obj_F... | Delosari/dazer | bin/user_conf/ManageFlow.py | Python | mit | 2,633 |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2-beta/sample_get_operations.py | Python | mit | 3,206 |
import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... | fegonda/icon_demo | code/web/server.py | Python | mit | 3,926 |
import numpy as np
import cPickle
import math
import string
import re
import subprocess
from datetime import datetime
from cwsm.performance import Performance
def cafferun(params):
# load general and optimization parameters
with open('../tmp/optparams.pkl', 'rb') as f:
paramdescr = cPickle.load(f)
... | mylxiaoyi/caffe-with-spearmint | cwsm/cafferun.py | Python | mit | 3,964 |
import curses
from curses.textpad import Textbox, rectangle
import asyncio
import readline
import rlcompleter
# import readline # optional, will allow Up/Down/History in the console
# import code
# vars = globals().copy()
# vars.update(locals())
# shell = code.InteractiveConsole(vars)
# shell.interact()
class Curs... | manly-man/moodle-destroyer-tools | frontend/interactive.py | Python | mit | 1,271 |
import _plotly_utils.basevalidators
class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="minexponent",
parent_name="histogram.marker.colorbar",
**kwargs
):
super(MinexponentValidator, self).__init__(
plot... | plotly/plotly.py | packages/python/plotly/plotly/validators/histogram/marker/colorbar/_minexponent.py | Python | mit | 507 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/ip_configuration_py3.py | Python | mit | 2,962 |
"""
Liana REST API client
Copyright Liana Technologies Ltd 2018
"""
import json
import hashlib
import hmac
import requests
import time
class APIException(Exception):
pass
class RestClient:
def __init__(self, user_id, api_secret, api_url, api_version, api_realm):
self._response = None
self.... | LianaTech/rest-client | python/RestClient.py | Python | mit | 3,505 |
from datetime import datetime
from email.mime import text as mime_text
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch
import cauldron as cd
from cauldron.session import reloading
from cauldron.test import support
from cauldron.test.support import scaffolds
from cauld... | sernst/cauldron | cauldron/test/session/test_session_reloading.py | Python | mit | 4,115 |
import logging
from ..report.individual import IndividualReport
class IndividualGenerator(object):
logger = logging.getLogger("ddvt.rep_gen.ind")
def __init__(self, test):
self.test = test
async def generate(self, parent):
test_group = None
try:
test_group = self.test(parent.filename)
ex... | HEP-DL/dl_data_validation_toolset | dl_data_validation_toolset/framework/report_gen/individual.py | Python | mit | 1,048 |
#
# YetAnotherPythonSnake 0.94
# Author: Simone Cingano (simonecingano@gmail.com)
# Web: http://simonecingano.it
# Licence: MIT
#
import pygame
import os
# YASP common imports
import data
if pygame.mixer:
pygame.mixer.init()
class dummysound:
def play(self): pass
class SoundPlayer:
def __init__(... | yupswing/yaps | lib/sound_engine.py | Python | mit | 1,288 |
from sacred import Experiment
ex = Experiment('my_commands')
@ex.config
def cfg():
name = 'kyle'
@ex.command
def greet(name):
print('Hello {}! Nice to greet you!'.format(name))
@ex.command
def shout():
print('WHAZZZUUUUUUUUUUP!!!????')
@ex.automain
def main():
print('This is just the main comma... | zzsza/TIL | python/sacred/my_command.py | Python | mit | 345 |
from OpenGLCffi.GLES3 import params
@params(api='gles3', prms=['first', 'count', 'v'])
def glViewportArrayvNV(first, count, v):
pass
@params(api='gles3', prms=['index', 'x', 'y', 'w', 'h'])
def glViewportIndexedfNV(index, x, y, w, h):
pass
@params(api='gles3', prms=['index', 'v'])
def glViewportIndexedfvNV(index,... | cydenix/OpenGLCffi | OpenGLCffi/GLES3/EXT/NV/viewport_array.py | Python | mit | 1,222 |
import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = False
parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot
self.set... | tommai78101/IRCBot | UserInput.py | Python | mit | 2,759 |
# Configuration file for ipython.
c = get_config() # noqa: F821
c.Completer.use_jedi = False
# ------------------------------------------------------------------------------
# InteractiveShellApp configuration
# ------------------------------------------------------------------------------
# A Mixin for application... | kbase/narrative | kbase-extension/ipython/profile_default/ipython_config.py | Python | mit | 20,674 |
import string
from operator import ge as greater_than_or_equal, gt as greater_than
from collections import deque
OPERATOR_PRECEDENCE = {
'(':0,
'+':1,
'-':1,
'*':2,
'/':2,
'^':3,
}
RIGHT_ASSOCIATIVE_OPERATORS = '^'
LEFT_ASSOCIATIVE_OPERATORS = '+-/*'
def pop_operator_queue(operators, output,... | julzhk/codekata | InfixtoPostfixConverter.py | Python | mit | 2,483 |
#!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
... | robert-impey/tree-sorter | randomtrees.py | Python | mit | 2,051 |
# coding: utf-8
from .common import CommonTestCase
class SuggestionsTest(CommonTestCase):
def test_suggestion_url(self):
client = self.client
# self.assertEqual(client.suggestions.address.url, "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address")
self.assertEqual(client.s... | tigrus/dadata-python | tests/test_suggestions.py | Python | mit | 674 |
# Copyright (c) 2011, Found IT A/S and Piped Project Contributors.
# See LICENSE for details.
import json
from StringIO import StringIO
from twisted.application import service
from twisted.internet import defer, address
from twisted.python import filepath, failure
from twisted.trial import unittest
from twisted.web im... | foundit/Piped | piped/providers/test/test_web_provider.py | Python | mit | 19,532 |
#!/usr/bin/env python3
# sequence = []
defence = 0.4
for x in range(1):
print(x)
for x in range(10):
if x == 0:
defence = defence
else:
defence = defence + (1 - defence) * (1 / 2)
print(defence)
# print(defence)
# print(sequence)
# print(sum(sequence))
# x = input()
# print(x) | mishka28/NYU-Python | advance_python_class_3/Homework1/temptest.py | Python | mit | 307 |
def pig_it(text):
return ' '.join([x[1:]+x[0]+'ay' if x.isalpha() else x for x in text.split()])
# 其实就是2个字符串过滤拼接,比移动方便多了,思路巧妙
# a if xx else b, 单行判断处理异常字符,xx为判断,标准套路
for x in text.split()
if x.isalpha()
... | lluxury/codewars | Simple Pig Latin.py | Python | mit | 564 |
import tkinter as tk
from tkinter import *
import spotipy
import webbrowser
from PIL import Image, ImageTk
import os
from twitter import *
from io import BytesIO
import urllib.request
import urllib.parse
import PIL.Image
from PIL import ImageTk
import simplejson
song1 = "spotify:artist:58lV9VcRSjABbAbfWS6skp"
song2 = ... | AndrewKLeech/Pip-Boy | Game.py | Python | mit | 42,161 |
# encoding: utf-8
"""
Plot-related objects. A plot is known as a chart group in the MS API. A chart
can have more than one plot overlayed on each other, such as a line plot
layered over a bar plot.
"""
from __future__ import absolute_import, print_function, unicode_literals
from .category import Categories
from .dat... | scanny/python-pptx | pptx/chart/plot.py | Python | mit | 13,213 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
from setuptools import setup
root_dir = os.path.abspath(os.path.dirname(__file__))
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.spl... | rrauenza/factory_boy | setup.py | Python | mit | 2,431 |
from tornado.httpclient import HTTPRequest, HTTPError
import ujson
import abc
import socket
from urllib import parse
from .. import admin as a
from .. social import SocialNetworkAPI, APIError, SocialPrivateKey
class XsollaAPI(SocialNetworkAPI, metaclass=abc.ABCMeta):
XSOLLA_API = "https://api.xsolla.com"
... | anthill-services/anthill-common | anthill/common/social/xsolla.py | Python | mit | 4,007 |
"""Constants for Sonarr."""
DOMAIN = "sonarr"
# Config Keys
CONF_BASE_PATH = "base_path"
CONF_DAYS = "days"
CONF_INCLUDED = "include_paths"
CONF_UNIT = "unit"
CONF_UPCOMING_DAYS = "upcoming_days"
CONF_WANTED_MAX_ITEMS = "wanted_max_items"
# Data
DATA_HOST_CONFIG = "host_config"
DATA_SONARR = "sonarr"
DATA_SYSTEM_STAT... | rohitranjan1991/home-assistant | homeassistant/components/sonarr/const.py | Python | mit | 436 |
import sys
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input dataset
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
# output dataset
y = np.array([[0,0,1,1]]).T
#... | jatinmistry13/BasicNeuralNetwork | two_layer_neural_network.py | Python | mit | 877 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.