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 database as db
import vocab as v
import conversation
import random
import time
import json
import datetime
import os
import math
import union_find
from twitter.status import Status
from twitter.user import User
from evidence import data_manager
from util import *
import threading
import tiara_ddl
impor... | jvictor0/TiaraBoom | tiara/data_gatherer.py | Python | mit | 46,191 |
from .registry import ( # noqa
register_network, network_for_netcode, network_codes, network_prefixes,
network_name_for_netcode, subnet_name_for_netcode, full_network_name_for_netcode,
wif_prefix_for_netcode, address_prefix_for_netcode, pay_to_script_prefix_for_netcode,
prv32_prefix_for_netcode, pub32... | shivaenigma/pycoin | pycoin/networks/__init__.py | Python | mit | 426 |
#!/usr/bin/env python3
import json
import os
SERIAL_DIRECTORY = "/dev/serial/by-id/"
class BaseCommand(object):
def execute(self, gcon, data):
return {"error" : "Not yet implemented"}
class CommandListSerial(BaseCommand):
def execute(self, gcon, data):
if os.path.exists(SERIAL_DIRECTORY):
... | laubed/gcon | gconlib/commands.py | Python | mit | 1,967 |
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import re
import six
from echomesh.expression import ConstantExpression
from echomesh.expression import Expression
from echomesh.expression.LiteralExpression import LiteralExpression
from echomesh.pattern.Registry import ma... | rec/echomesh | code/python/echomesh/pattern/Pattern.py | Python | mit | 4,272 |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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 res... | Fendoe/open-hackathon-o | open-hackathon-client/src/client/views/route_user.py | Python | mit | 1,510 |
from django.db.models import Field
from s3direct.widgets import S3DirectWidget
class S3DirectField(Field):
def __init__(self, *args, **kwargs):
dest = kwargs.pop('dest', None)
self.widget = S3DirectWidget(dest=dest)
super(S3DirectField, self).__init__(*args, **kwargs)
def get_internal... | bradleyg/django-s3direct | s3direct/fields.py | Python | mit | 511 |
# -*- coding: utf-8 -*-
from browser_interface.field.FieldFactory import FieldFactory
from browser_interface.queue.QueueFactory import QueueFactory
from browser_interface.browser.BrowserFactory import BrowserFactory
from browser_interface.log.Logging import Logging
from common import config
import urllib
import json
... | xtuyaowu/jtyd_python_spider | feng_huang_net/fh_comment.py | Python | mit | 2,274 |
from sqlalchemy import (
Column,
Index,
Integer,
Text,
LargeBinary,
Unicode,
ForeignKey,
Table
)
from sqlalchemy.orm import relationship
from .meta import Base
class User(Base):
"""This class defines a User model."""
__tablename__ = 'users'
id = Column(Integer, primary_key... | PyListener/CF401-Project-1---PyListener | pylistener/models/mymodel.py | Python | mit | 1,872 |
import _plotly_utils.basevalidators
class IdsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="ids", parent_name="treemap", **kwargs):
super(IdsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
anim=kw... | plotly/plotly.py | packages/python/plotly/plotly/validators/treemap/_ids.py | Python | mit | 430 |
# 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 ... | AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/cluster_manifest.py | Python | mit | 848 |
from flask import render_template, send_from_directory
from passgen import app, static_dir
@app.route('/assets/<path:path>')
def send_assets(path):
return send_from_directory(static_dir, path)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
| odedlaz/passgen | passgen/api.py | Python | mit | 289 |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from ragendja.auth.urls import urlpatterns as auth_patterns
from blog.forms import UserRegistrationForm
from django.contrib import admin
admin.autodiscover()
handler500 = 'ragendja.views.server_error'
urlpatterns = auth_patterns + patterns('',
(r'^a... | directeur/socnode | urls.py | Python | mit | 648 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from gaeforms.ndb.form import ModelForm
from gaegraph.model import Node
class Criatura(Node):
name=ndb.StringProperty(required=True)
image=ndb.StringProperty()
type=ndb.StringProperty()
... | marcelosandoval/tekton | backend/appengine/routes/criatura/modelo.py | Python | mit | 761 |
"""
Django settings for systematic_review project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DI... | iliawnek/SystematicReview | systematic_review/settings.py | Python | mit | 2,999 |
import dbus.service
from gi.repository import GObject as gobject
from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager
from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE
EVENT_IFACE = 'org.openaps.Service.Instance.Triggers'
class Emitter (GPropS... | openaps/oacids | oacids/exported/triggers.py | Python | mit | 3,924 |
# -*- coding: utf-8 -*-
"""
vollib.helper.numerical_greeks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A library for option pricing, implied volatility, and
greek calculation. vollib is based on lets_be_rational,
a Python wrapper for LetsBeRational by Peter Jaeckel as
described below.
... | vollib/vollib | vollib/helper/numerical_greeks.py | Python | mit | 7,763 |
#!/bin/python
import sys
def main(files):
for file_name in files:
game = 0
white_wins = 0
black_wins = 0
draws = 0
number_of_moves = 0
time = 0
white_time_left = 0
black_time_left = 0
with open(file_name) as f, open(file_name + '_plots.txt', ... | MarkZH/Genetic_Chess | analysis/win_lose_draw_plots.py | Python | mit | 4,298 |
import enum
import gzip
import pickle
from .base import Player
from .map import Map
class ActionType(enum.Enum):
target = 0
clear_target = 1
stop = 2
class Command(object):
'''a command received from a player
{'id': '<uuid>', 'action': '<action-type>.name', 'target': '<uuid>' | {'posx': X, 'pos... | eguven/mobai | mobai/engine/game.py | Python | mit | 7,171 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from actionlib import SimpleActionClient
from pnp_plugin_server.pnp_simple_plugin_server import PNPSimplePluginServer
from pepper_move_base.msg import QualitativeMovePepperAction, QualitativeMovePepperResult
from pnp_msgs.msg import ActionResult
from nao_inte... | cdondrup/pepper_planning | pepper_move_base/scripts/qualitative_move_base.py | Python | mit | 3,768 |
"""
File: instrument_class.py
Purpose: Defines a major category of instruments in the instrument category. In this case,
is used to identity broad instrument types, e.g. stringw, woodwinds, bass, percussion, keyboards.
"""
from instruments.instrument_base import InstrumentBase
class InstrumentClass(Inst... | dpazel/music_rep | instruments/instrument_class.py | Python | mit | 963 |
"""
Provides ValueMeta metaclass - which allows its descendants to override
__instancecheck__ and __subclasscheck__ to be used as *classmethods*
"""
from __future__ import absolute_import
__all__ = [
'ValueMeta',
'ValueABC',
'InterfaceType',
'ExistingDirectory',
'ExistingFile'
]
from .existing_dir... | OaklandPeters/pyinterfaces | pyinterfaces/valueabc/__init__.py | Python | mit | 498 |
import socket
from PIL import Image
import io
import os
def string_to_byte(hex_input):
return bytearray.fromhex(hex_input)
def serve():
host = ""
port = 5001
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((host, port))
my_socket.listen(1)
conn, address = ... | kiwicampus/kiwix | server.py | Python | mit | 2,463 |
from django.apps import AppConfig
HAML_EXTENSIONS = ("haml", "hamlpy")
class Config(AppConfig):
name = "hamlpy"
def ready(self):
# patch Django's templatize method
from .template import templatize # noqa
default_app_config = "hamlpy.Config"
| nyaruka/django-hamlpy | hamlpy/__init__.py | Python | mit | 272 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
from sphinx_explorer import package_main
if __name__ == "__main__":
package_main()
| pashango2/sphinx-explorer | sphinx-explorer_debug.py | Python | mit | 217 |
# -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | AliOsm/arabic-text-diacritization | helpers/transliteration.py | Python | mit | 2,223 |
"""
Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updatedautomatically.
"""
import abc
class Subject:
"""
Know its observers. Any number of Observer objects may observe a
subject.
Send a notification to its observers when it... | zitryss/Design-Patterns-in-Python | behavioral/observer.py | Python | mit | 1,753 |
from datetime import datetime
from pymongo import MongoClient
import pytest
from mongoframes import *
__all__ = [
# Frames
'Dragon',
'Inventory',
'Lair',
'ComplexDragon',
'MonitoredDragon',
# Fixtures
'mongo_client',
'example_dataset_one',
'example_dataset_many'
]
# Cla... | GetmeUK/MongoFrames | tests/fixtures.py | Python | mit | 3,565 |
import os
import time
import json
import struct
import logging
import platform
import subprocess
from fcntl import ioctl
from pyroute2.common import map_namespace
from pyroute2.common import ANCIENT
# from pyroute2.netlink import NLMSG_ERROR
from pyroute2.netlink import nla
from pyroute2.netlink import nlmsg
from pyrou... | alexliyu/CDMSYSTEM | pyroute2/netlink/rtnl/ifinfmsg.py | Python | mit | 36,186 |
# Lec 3, Problem 9
# bisection search
print('Please think of a number between 0 and 100!')
low = 0
high = 100
x = '0'
while x != 'c':
guess = (low + high) / 2
print('Is your secret number ' + str(guess) + '?')
x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indi... | medifle/python_6.00.1x | L3_P9_bisection_search.py | Python | mit | 654 |
"""
sphinx.domains.c
~~~~~~~~~~~~~~~~
The C language domain.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import string
from docutils import nodes
from sphinx import addnodes
from sphinx.directives import ObjectDescriptio... | lmregus/Portfolio | python/design_patterns/env/lib/python3.7/site-packages/sphinx/domains/c.py | Python | mit | 12,525 |
#!/usr/bin/env python
# encoding: utf-8
"""
read_config.py
The main point with this package is how to retreive the corect entry from
a vcf file.
In the best case one should be able to specify any kind of entry in the
config file and how it is extracted.
ConfigParser will read these files and check if they are on the ... | moonso/extract_vcf | extract_vcf/config_parser.py | Python | mit | 10,637 |
from scipy import *
from Reference import *
################################################################################
# DATA
################################################################################
# EARTH FACTS
R = 287.058 # ideal gas constant for earth air, in J/kg*K
r = 6356766 # radius of the eart... | Conflagrationator/AAE251 | Atmosphere.py | Python | mit | 4,278 |
import asyncio
from collections import namedtuple
import contextlib
import os
import subprocess
import tempfile
import yaml
from .async_helpers import create_subprocess_with_handle
from . import cache
from . import compat
from .compat import makedirs
from .error import PrintableError
DEFAULT_PARALLEL_FETCH_LIMIT = 1... | oconnor663/peru | peru/plugin.py | Python | mit | 12,866 |
#! /usr/bin/python
# https://github.com/jackchi/interview-prep
import random
# Bubble Sort
# randomly generate 10 integers from (-100, 100)
arr = [random.randrange(-100,100) for i in range(10)]
print('original %s' % arr)
def bubbleSort(array):
n = len(array)
# traverse thru all elements
for i in range(n):
s... | jackchi/interview-prep | sorting/bubbleSort.py | Python | mit | 738 |
import sublime
import sublime_plugin
from datetime import datetime
import io
import os
import re
import subprocess
import sys
def get_setting(key, default=None):
settings = sublime.load_settings('tmux.sublime-settings')
os_specific_settings = {}
if sys.platform == 'darwin':
os_specific_settings = ... | huntie/sublime-tmux | tmux.py | Python | mit | 4,727 |
# Dungeon.py
# builds a random dungeon of size MxN
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))+'/../')
from bearlibterminal import terminal as term
from copy import deepcopy
from random import choice, randint, shuffle
from collections import namedtuple
from tools import bresenhams... | whitegreyblack/Spaceship | spaceship/classes/dungeon.py | Python | mit | 25,031 |
# -*- coding: utf-8 -*-
"""Utilities for configuration versioning."""
from verta._internal_utils import documentation
from ._configuration import _Configuration
from ._hyperparameters import Hyperparameters
documentation.reassign_module(
[Hyperparameters],
module_name=__name__,
)
| mitdbg/modeldb | client/verta/verta/configuration/__init__.py | Python | mit | 293 |
from xmcam import *
from xmconst import *
from time import sleep
CAM_IP = '192.168.1.10'
CAM_PORT = 34567
if __name__ == '__main__':
xm = XMCam(CAM_IP, CAM_PORT, 'admin', 'admin')
login = xm.cmd_login()
print(login)
print(xm.cmd_system_function())
print(xm.cmd_system_info())
print(xm.cmd_chan... | janglapuk/xiongmai-cam-api | example.py | Python | mit | 660 |
#!/usr/bin/env python
import os
import sys
import argparse
def build_arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument("filename",
metavar="filename",
help="mock source file to \"compile\"")
return parser
def parse_instructions(filename):
actions = {'exit': 0}
... | bulatb/yuno | dev/mock_compiler.py | Python | mit | 1,190 |
from algorithms.structures.disjoint_set import DisjointSet
def test_disjoint_set():
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ds = DisjointSet(a)
assert ds.find_set(1) != ds.find_set(2)
ds.union(1, 2)
assert ds.find_set(1) == ds.find_set(2)
assert ds.find_set(1) != ds.find_set(3)
ds.union(2, 3)
... | vadimadr/python-algorithms | tests/test_disjoint_set.py | Python | mit | 407 |
from __future__ import print_function
from collections import deque
import numpy as np
import gym
env_name = 'CartPole-v0'
env = gym.make(env_name)
def observation_to_action(ob, theta):
# define policy neural network
W1 = theta[:-1]
b1 = theta[-1]
return int((ob.dot(W1) + b1) < 0)
def theta_rollout(env, thet... | yukezhu/tensorflow-reinforce | run_cem_cartpole.py | Python | mit | 2,013 |
import csv
from gff3 import Gff3
import gff3
gff3.gff3.logger.setLevel(100)
import io, re
from urllib import parse
SNPEFF_REGEX = re.compile(r"(\w+)\((.+)\)")
def parse_genes(gff3_file, go_terms_file):
"""parses the genes from gff3 and enriches it with additional information"""
go_map = _get_go_map(go_terms_f... | 1001genomes/AraGWAS | aragwas_server/gwasdb/parsers.py | Python | mit | 6,179 |
# -*- coding: utf-8 -*-
"""Test cases for messages"""
from __future__ import absolute_import
from builtins import str
import json
import sys
import pytest
from datetime import datetime
from mock import Mock
import logging
import purkinje_messages.message as sut
logging.basicConfig(level=logging.DEBUG, stream=sys.stdo... | bbiskup/purkinje-messages | tests/message_test.py | Python | mit | 7,537 |
# Determine whether an integer is a palindrome. Do this without extra space.
class Solution:
# @return a boolean
def isPalindrome1(self, x):
if x < 0 or x % 10 == 0 and x:
return False
xhalf = 0
while x > xhalf:
xhalf = xhalf * 10 + x % 10
x... | ammzen/SolveLeetCode | 9PalindromeNumber.py | Python | mit | 727 |
def add_vimode_segment(powerline):
vimode_prompt = ' \n${VIMODE}'
powerline.append(vimode_prompt, Color.NEWLINE_FG, Color.NEWLINE_BG)
| paulhybryant/powerline-shell | segments/vimode.py | Python | mit | 143 |
from unittest import mock
from bgmi.downloader.aria2_rpc import Aria2DownloadRPC
_token = "token:2333"
@mock.patch("bgmi.config.ARIA2_RPC_URL", "https://uuu")
@mock.patch("bgmi.config.ARIA2_RPC_TOKEN", "token:t")
def test_use_config():
with mock.patch("xmlrpc.client.ServerProxy") as m1:
m1.return_value.... | BGmi/BGmi | tests/downloader/test_aria2.py | Python | mit | 609 |
# -*- coding: utf-8 -*-
from io import BytesIO
import pytest
from phi.request.form import FormRequest
class TestFormRequest(object):
@pytest.fixture
def form_req(self):
fr = FormRequest()
fr.charset = "utf-8"
return fr
@pytest.mark.parametrize("body, content", [
(
... | RafaelSzefler/phi | tests/unit/request/test_form.py | Python | mit | 834 |
""" Agador Metaservice
Usage:
agador [options]
Options:
-c --config URI # Service config URI
-d --debug # Run in debug mode
-h --host HOST # Host IP [default: 0.0.0.0]
-p --port PORT # Port no [default: 8500]
"""
import furi
from envopt import envopt
from f... | amancevice/agador | agador/microservice.py | Python | mit | 1,138 |
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective
from docutils import nodes
import os
import importlib.util
class K3D_Plot(SphinxDirective):
""" Sphinx class for execute_code directive
"""
has_content = False
required_arguments = 0
optional_arguments = 2... | K3D-tools/K3D-jupyter | docs/source/k3d_directives/plot.py | Python | mit | 1,492 |
from rest_framework import serializers
from callback_schedule.models import CallbackManager, CallbackManagerSchedule, CallbackManagerPhone
class CMScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = CallbackManagerSchedule
fields = 'weekday', 'available_from', 'available_till'
... | steppenwolf-sro/callback-schedule | callback_schedule/serializers.py | Python | mit | 675 |
from flask import jsonify, request
from application import app, db
from application.dto.link import LinkDTO
from application.models.link import Link
@app.route('/api/links',methods=['GET'])
def get_links():
#sql
_links = Link.query.all()
#dto
links = LinkDTO.create_list(_links)
return jsonify... | cayman/decision | server/application/requests/link.py | Python | mit | 1,054 |
#!/usr/bin/python3
import sys
import os
def printUsage():
sys.exit('Usage: %s server|client' % sys.argv[0])
if ((len(sys.argv)!=2) or (sys.argv[1] != 'client') and (sys.argv[1] != 'server')):
printUsage()
print("Generating daemon script\n")
fileContents = open('dyndns.sh').read( os.path.getsize('dyndns.sh') )
fi... | MilkyWeb/dyndns | install.py | Python | mit | 881 |
# -*- coding: utf-8 -*-
import pytest
from irc3.plugins import slack
pytestmark = pytest.mark.asyncio
async def test_simple_matches(irc3_bot_factory):
bot = irc3_bot_factory(includes=['irc3.plugins.slack'])
plugin = bot.get_plugin(slack.Slack)
setattr(plugin, 'config', {'token': 'xoxp-faketoken'})
as... | gawel/irc3 | tests/test_slack.py | Python | mit | 2,123 |
def validate_cross_validation(rounds,train_to_test_ratio):
# the number of turns must be exactly equal to the number
# of "parts" you'll split your data into
res = rounds * (1 - train_to_test_ratio)
# comparando floats na marra.
assert ( abs(res - 1) < 0.0001 )
| queirozfcom/spam-filter | lib/validation.py | Python | mit | 269 |
#!/usr/bin/env python
import syslog
from subprocess import call
import urllib2
import json
import re
import docker_login
from user_data import get_user_data
# Starts a docker run for a given repo
# This will effectively call `docker run <flags> <repo>:<tag>`
# This service is monitored by Upstart
# User Data
# docker.... | hayesgm/cerberus | scripts/cerberus_run.py | Python | mit | 1,413 |
import numpy as np
from pyglet.window import key
# individual agent policy
class Policy(object):
def __init__(self):
pass
def action(self, obs):
raise NotImplementedError()
# interactive policy based on keyboard input
# hard-coded to deal only with movement, not communication
class Interactive... | openai/multiagent-particle-envs | multiagent/policy.py | Python | mit | 1,935 |
import web
from web import form
import socket
print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080")
urls = (
'/','Login',
'/page_one','Page_one',
'/left', 'Left',
'/right', 'Right',
'/forward', 'Forward',
'/start', 'Start',
'/stop', ... | martin31242/rccar | draft3/main.py | Python | mit | 2,043 |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 01 10:45:09 2014
Training models remotely in cloud
@author: pacif_000
"""
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
import os
import platform
if platform.system() == 'Windows':
import win32api
else:
import signal
import thread
... | xumiao/pymonk | tests/kafka_tester.py | Python | mit | 1,929 |
# -*- coding: utf-8 -*-
from odoo import http
class Worker(http.Controller):
@http.route('/worker')
def Main(self, **kwargs):
return http.request.render(
'worker_app.index_template')
| batazor/MyExampleAndExperiments | Python/odoo_worker_tracking/test/odoo_worker_tracking/controllers/main.py | Python | mit | 213 |
import utils
import re
import subprocess
#regexes
duration_regex = re.compile('Duration:\s*(?P<time>\d{2}:\d{2}:\d{2}.\d{2})')
stream_regex = re.compile('Stream #(?P<stream_id>\d+:\d+)(\((?P<language>\w+)\))?: (?P<type>\w+): (?P<format>[\w\d]+)')
crop_regex = re.compile('crop=(?P<width>\d+):(?P<height>\d+):(?P<x>\d+)... | choffmeister/transcode | lib/ffmpeg.py | Python | mit | 1,356 |
#coding=utf-8
'''
Created on 2015年5月18日
python traceback parser
@author: hzwangzhiwei
'''
import json
import re
def str_is_empty(s):
if s == None or s == '' or s.strip().lstrip().rstrip('') == '':
return True
return False
class TracebackParser(object):
'''
parser
'''
tb_is_trace = Tru... | sdgdsffdsfff/py-trace-parser | traceback_parser.py | Python | mit | 7,757 |
"""
Django settings for todolist project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | leonardoo/to-do-list | todolist/settings.py | Python | mit | 1,990 |
from __future__ import division
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import pandas as pd
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob... | danjamker/DiffusionSimulation | LinearRegression.py | Python | mit | 12,302 |
#!/usr/bin/python
import time, sys
if(len(sys.argv) > 0):
video = sys.argv[1]
else:
video = "REjj1ruFQww"
try:
import pychromecast
pychromecast.play_youtube_video(video, pychromecast.PyChromecast().host)
except:
pass
| probonopd/video2smarttv | yt2chromecast.py/usr/bin/video2chromecast.py | Python | mit | 240 |
"""
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import credentials as apns2_c... | shigmas/django-push-notifications | push_notifications/apns.py | Python | mit | 5,297 |
from ctypes import POINTER, c_double, c_int, c_uint
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import (
GEOSException, last_arg_byref,
)
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# ## Error-checking routines spec... | diego-d5000/MisValesMd | env/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py | Python | mit | 3,266 |
from __future__ import absolute_import
from __future__ import with_statement
import os.path
import re
from datetime import datetime
import logging
import pickle
import copy
import subprocess
import zipfile
import functools
import traceback
import dropbox.auth
import dropbox.client
from oauth import oauth
import dropb... | Japanuspus/Site-in-a-Dropbox | app/test/dbtools.py | Python | mit | 7,523 |
# -*- coding: utf-8 -*-
class Ledger(object):
def __init__(self, db):
self.db = db
def balance(self, token):
cursor = self.db.cursor()
cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token])
row = cursor.fetchone()
return 0 if row is None else row[2]
... | Storj/accounts | accounts/ledger.py | Python | mit | 1,481 |
import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... | Disassem/urllib3 | test/socketpair_helper.py | Python | mit | 2,414 |
from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... | materials-commons/materialscommons.org | backend/tests/python_api_mulltiuser_check/DB.py | Python | mit | 1,380 |
import _plotly_utils.basevalidators
class CmaxValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="cmax", parent_name="scatter.marker", **kwargs):
super(CmaxValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/marker/_cmax.py | Python | mit | 467 |
from __future__ import absolute_import
import os
DEBUG = True
BASE_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTH_PASSW... | akalipetis/djoser | testproject/settings.py | Python | mit | 2,123 |
from numpy import *
from sigmoid import sigmoid
def predict(Theta, X):
# Takes as input a number of instances and the network learned variables
# Returns a vector of the predicted labels
# Useful values
m = X.shape[0]
num_labels = Theta[-1].shape[0]
num_layers = len(Theta) + 1
# You need ... | marioyc/Hand-written-Digit-Recognition | Assignment 1 - Neural networks/predict.py | Python | mit | 628 |
#pylint: disable-msg=R0903
from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Length, Email
class LoginForm(Form):
email = StringField('Email',
validators=[Required(), Length(1, 64), Email()... | finnurtorfa/aflafrettir.is | app/auth/forms.py | Python | mit | 484 |
from datetime import datetime
import logging
import decimal
import base64
import json
import time
from lib import config, util
decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
D = decimal.Decimal
def calculate_price(base_quantity, quote_quantity, base_divisibility, quote_divisibility, o... | metronotes-beta/metroblockd | lib/components/dex.py | Python | mit | 24,335 |
'''
US Amendments - tweets proposed ammendments to us constitution
from: http://www.archives.gov/open/dataset-amendments.html
'''
if __name__ == "__main__":
import sys
sys.path.append("..")
import credentials
from robot_core import Robot
from funcs.ql import QuickList
import os
import time
class ... | inkleby/inklebyrobots | robots/amendments.py | Python | mit | 4,057 |
#VERSION: 2.1
# AUTHORS: Douman (custparasite@gmx.se)
# CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es)
from novaprinter import prettyPrinter
from helpers import retrieve_url, download_file
from re import compile as re_compile
from HTMLParser import HTMLParser
class torlock(object):
url = "https://www.torl... | PowerKiKi/mqueue | library/searchengine/nova/engines/torlock.py | Python | mit | 4,152 |
from logger import Logger
from docker import Client
import signal
import sys
import yaml
def signal_term_handler(signal, frame):
print 'terminating...'
sys.exit(0)
signal.signal(signal.SIGTERM, signal_term_handler)
with open("agent.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
client = Client(base_url='... | pfe-asr-2014/tsp-mooc-agent | app/agent.py | Python | mit | 390 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Numerical differentiation."""
import numpy as np
from jpy.maths.matrix import tridiag
def make_stencil(n, i, i_, _i):
"""Create a tridiagonal stencil matrix of size n.
Creates a matrix to dot with a vector for performing discrete spatial computations.
i, i... | jamesp/jpy | jpy/maths/derive.py | Python | mit | 2,080 |
issues=[
dict(name='Habit',number=5,season='Winter 2012',
description='commit to a change, experience it, and record'),
dict(name='Interview', number=4, season='Autumn 2011',
description="this is your opportunity to inhabit another's mind"),
dict(name= 'Digital Presence', number= 3, season= ... | adamgreenhall/openreviewquarterly | builder/config.py | Python | mit | 879 |
""" Surface image content gap. """
__version__ = '1.3-dev'
| Commonists/SurfaceImageContentGap | surfaceimagecontentgap/__init__.py | Python | mit | 59 |
import time
project = 'Cambion'
copyright = str(time.localtime().tm_year) + ', Whitestone.'
author = 'Whitestone'
source_suffix = ['.rst']
master_doc = 'index'
highlight_language = 'csharp'
html_favicon = 'favicon.ico'
# html_logo = 'images/logoTiny.png'
html_scaled_image_link = False
html_theme = 'sphinx_rtd_theme... | whitestone-no/Cambion | docs/conf.py | Python | mit | 511 |
"""
stringjumble.py
Author: Eric
Credit: Me!
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, but... | anoushkaalavilli/String-Jumble | stringjumble.py | Python | mit | 1,639 |
import bb
import oe.path
import glob
import hashlib
import os.path
import shutil
import string
import subprocess
class OSTreeUpdate(string.Formatter):
"""
Create an OSTree-enabled version of an image rootfs, using an intermediate
per-image OSTree bare-user repository. Optionally export the content
of ... | jairglez/intel-iot-refkit | meta-refkit-core/lib/ostree/ostreeupdate.py | Python | mit | 12,419 |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | docusign/docusign-python-client | docusign_esign/models/payment_gateway_accounts_info.py | Python | mit | 3,706 |
#! /usr/bin/env python
# AceWiki data converter
# Author: Kaarel Kaljurand
# Version: 2012-02-23
#
# This script provides the conversion of a given AceWiki data file
# into other formats, e.g. JSON and GF.
#
# Examples:
#
# python convert_acewiki.py --in geo.acewikidata > Geo.json
# python convert_acewiki.py --in geo.... | TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/ace_in_gf/tools/convert_acewiki.py | Python | mit | 6,414 |
import os
root_dir = os.path.dirname(os.path.realpath(__file__))
f = open(".modulerc", "w")
f.write("#%Module\n")
sub_dirs = os.walk(root_dir)
next(sub_dirs)
for dir_name, _, file_list in sub_dirs:
for file_name in file_list:
module_version = file_name.rstrip(".lua")
module_name = os.path.relpath... | ntuhpc/modulefiles | all/hide.py | Python | mit | 413 |
from datetime import datetime
from src.textgenerator import TextGenerator
from src.utils import extract_project_gutenberg_novel, remove_titles
# The source files to use
# NOTE: Ulysses makes the generated text just a little too weird.
files = [
'./data/life_and_amours.txt',
'./data/memoirs_of_fanny_hill.txt',... | Agrajag-Petunia/existential-romantic-novel | run.py | Python | mit | 1,939 |
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import ro... | tapomayukh/projects_in_python | classification/Classification_with_kNN/Single_Contact_Classification/Scaled_Features/best_kNN_PCA/2_categories/test11_cross_validate_categories_mov_fixed_1200ms_scaled_method_iii.py | Python | mit | 5,012 |
#!/usr/bin/python3
"""This file is part of asyncoro; see http://asyncoro.sourceforge.net for
details.
This program can be used to start discoro server processes so discoro scheduler
(see 'discoro.py') can send computations to these server processes for executing
distributed communicating proceses (coroutines). All co... | pgiri/asyncoro | py3/asyncoro/discoronode.py | Python | mit | 55,226 |
from verbose import *
from card_value import *
import pycurl
from io import BytesIO
class Trick:
def __init__(self, trump, playerlst):
# The trick pile
self.tpile = []
# 0 = Clubs, 1 = Diamonds, 2 = Hearts, 3 = Spades, 4 = No Trump
self.trump = trump
self.playerlst = playerl... | ACBL-Bridge/Bridge-Application | Logic/trick_handle.py | Python | mit | 8,305 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitConnectCAG_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitConnectCAG_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_compiled... | levilucio/SyVOLT | RSS2ATOM/contracts/unit/HUnitConnectCAG_ConnectedLHS.py | Python | mit | 1,301 |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
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 righ... | alexforencich/python-ivi | ivi/anritsu/anritsuMN9610B.py | Python | mit | 7,432 |
# -*- coding: utf-8 -*-
import pytest
from lupin.validators import Equal
from lupin.errors import ValidationError
@pytest.fixture
def invalid():
return Equal("sernine")
@pytest.fixture
def valid():
return Equal("lupin")
class TestAnd(object):
def test_returns_an_and_combination(self, valid, invalid):
... | holinnn/lupin | tests/lupin/validators/test_validator.py | Python | mit | 601 |
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
from squeezemail.tasks import run_steps
run_steps.delay()
| rorito/django-squeezemail | squeezemail/management/commands/run_steps_task.py | Python | mit | 197 |
import unittest
import bayesnet as bn
class TestTanh(unittest.TestCase):
def test_tanh(self):
self.assertEqual(bn.tanh(0).value, 0)
if __name__ == '__main__':
unittest.main()
| ctgk/BayesianNetwork | test/nonlinear/test_tanh.py | Python | mit | 196 |
# ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... | diplomacy/research | diplomacy_research/models/draw/tests/draw_model_test_setup.py | Python | mit | 7,985 |
import io
import unittest
from unittest.mock import patch
from kattis import k_hardwoodspecies
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run an... | ivanlyon/exercises | test/test_k_hardwoodspecies.py | Python | mit | 1,481 |
import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="showticklabels",
parent_name="treemap.marker.colorbar",
**kwargs
):
super(ShowticklabelsValidator, self).__init__(
... | plotly/plotly.py | packages/python/plotly/plotly/validators/treemap/marker/colorbar/_showticklabels.py | Python | mit | 477 |
import sys
import os
#Adding directory to the path where Python searches for modules
cmd_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/Crypto/modules/')
sys.path.insert(0, cmd_folder)
#Importing common crypto module
import block
if __name__ == "__main__":
plaintext= 'aaaaaaaaaaaaaaaaaaaaaaaa... | arvinddoraiswamy/blahblah | cryptopals/Set2/c11.py | Python | mit | 625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.