code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import shutil import subprocess import tempfile import threading import time import traceback from flask import Flask, request, redirect app = Fl...
guykisel/inline-plz-bot
main.py
Python
isc
5,120
import sqlalchemy from sqlalchemy import Table, Column, Integer, String, ForeignKey def connect(user, password, db, host='localhost', port=5432): '''Returns a connection and a metadata object''' # We connect with the help of the PostgreSQL URL # postgresql://federer:grandestslam@localhost:5432/tennis ...
eugeneks/zmeyka
zmeyka_postgres.py
Python
mit
2,882
from lisp_lex import CookeryLexer import logging from functools import reduce from operator import sub, mul, truediv from itertools import dropwhile import ply.yacc as yacc import ply.lex as lex funs = { '+': sum, '-': lambda l: reduce(sub, l[1:], l[0]), '*': lambda l: reduce(mul, l[1:], l[0]), '/': la...
mikolajb/cookery
cookery/lisp_parse.py
Python
mit
2,890
__author__ = 'yangjiebin' from flask import Blueprint auth = Blueprint('auth',__name__) from . import views
rebortyang/flask_blog
app/auth/__init__.py
Python
mit
111
from ducktape import * @main(str,str,str) def hello(name,origin): """ This is the first hello world for python function/modules """ return "helo " + str.strip(str(name)) +" van "+ str.strip(str(origin)) print hello("Zen","Japan")
Data2Semantics/ducktape
src/test/resources/python/test.py
Python
mit
241
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-05-21 12:34 from __future__ import unicode_literals import dictionary.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dictionary', '0011_auto_20160503_1535'), ] operations = [ ...
nirvaris/nirvaris-dictionary
dictionary/migrations/0012_auto_20160521_1234.py
Python
mit
887
from unittest import TestCase, skip from pch2csd.patch import ModuleParameters, Location, Module from pch2csd.resources import ProjectData from pch2csd.util import AttrEqMixin class TestAttrEqMixin(TestCase): class ThreeSlots(AttrEqMixin): def __init__(self, one, two, three): self.one = one ...
gleb812/pch2csd
tests/test_utils.py
Python
mit
2,150
"""autogenerated by genpy from geographic_msgs/GetGeographicMapRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geographic_msgs.msg class GetGeographicMapRequest(genpy.Message): _md5sum = "505cc89008cb1745810d2ee4ea646d6e" _type = "...
superdyzio/PWR-Stuff
AIR-ARR/Projekt Zespołowy/catkin_ws/devel/lib/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py
Python
mit
33,019
import argparse import pandas as pd import sklearn.datasets if __name__ == "__main__": # parse command-line arguments parser = argparse.ArgumentParser(description="Create a synthetic gene expression dataset") parser.add_argument("--n-samples", help="number of samples", type=int, default=100) parser.add_argument(...
SystemsGenetics/KINC
scripts/make-input-data.py
Python
mit
1,349
from rest_framework import generics from rest_framework.views import APIView from django.views.generic.base import TemplateView from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.authentication import SessionA...
trcm/stew
stew/views.py
Python
mit
9,961
#!/usr/bin/env python import unittest from binary_search_tree import BST, Node class BSTTest(unittest.TestCase): def setUp(self): self.bst = BST() # node0 = BinarySearchTreeNode(1) # node1 = BinarySearchTreeNode(2) # node2 = BinarySearchTreeNode(3) # node3 = BinarySearchTr...
keithio/practice-data-structures-and-algorithms
data_structures/binary_search_tree/tests.py
Python
mit
1,049
from battlePy.utils import docprop (UP, DOWN, LEFT, RIGHT) = SHIP_ORIENTATIONS = range(4) VECTOR_DICT = {UP: (0, 1), DOWN: (0, -1), LEFT: (-1, 0), RIGHT: (1, 0)} class Ship(object): name = docprop('name', 'Name of the ship') size = docprop('size', 'Size of the ship') hits = docprop('hits', 'Set of curren...
kyokley/BattlePyEngine
src/battlePy/ship.py
Python
mit
1,526
import argparse import getpass import os import re import subprocess from datetime import datetime from pathlib import Path import requests SRC_FOLDER = "organize" CURRENT_FOLDER = Path(__file__).resolve().parent GITHUB_API_ENDPOINT = "https://api.github.com/repos/tfeldmann/organize" def ask_confirm(text): whil...
tfeldmann/organize
manage.py
Python
mit
5,445
from django.contrib import admin # Register your models here. from .models import Uploader admin.site.register(Uploader)
paihu/moebox
admin.py
Python
mit
124
# -*- coding: utf-8 -*- # # ackward documentation build configuration file, created by # sphinx-quickstart on Sat Apr 23 08:14:04 2011. # # 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...
abingham/ackward
docs/sphinx/source/conf.py
Python
mit
7,195
''' youtubeAlbumParser.py A python script for parsing a youtube album into individual songs First argument is url of video Second argument is the name for the songs Tom Kelly ''' from bs4 import * # beautiful soup import sys import urllib2 import re try: url = sys.argv[1] except: url = raw_input('...
tomkelly000/youtubeAlbumConverter
youtubeAlbumParser.py
Python
mit
1,807
def add_newline_segment(powerline): powerline.append("\n", Color.RESET, Color.RESET, separator='')
tswsl1989/powerline-shell
segments/newline.py
Python
mit
103
__author__ = 'saintdragon2' fname = 'C:/ttt/test.txt' f = open(fname) sum = 0 while True: line = f.readline() if not line: break sum += int(line) print(sum) f.close() file_to_write = open('c:/ttt/abc.csv', 'w') file_to_write.write('hahaha,kkk,1,2,3,4,5\n') file_to_write.write('a, b, c, e, d...
saintdragon2/python-3-lecture-2015
gui_practice/file_io_civil.py
Python
mit
347
import zmq, time port = "5550" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.connect("tcp://localhost:%s" % port) while True: socket.send_string("yo") time.sleep(4)
Jawoll/automatchthreads
test3.py
Python
mit
202
from phapi import ProductHuntApi import settings import json pha = ProductHuntApi(settings.DEVELOPER_TOKEN) posts = pha.get_posts() print json.dumps(posts, indent=2)
dangoldin/pyproducthunt
analyze.py
Python
mit
168
from core.himesis import Himesis import uuid class H02Package2ERModel(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule 02Package2ERModel. """ # Flag this instance as compiled now self.is_compiled = True super(H02Package2ERModel, self).__init__(name='H02Package2ER...
levilucio/SyVOLT
UML2ER/transformation/H02Package2ERModel.py
Python
mit
1,402
# System import json from .stage01_isotopomer_peakData_query import stage01_isotopomer_peakData_query from SBaaS_base.sbaas_template_io import sbaas_template_io # Resources from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData class stage01_isotopomer_peakDat...
dmccloskey/SBaaS_isotopomer
SBaaS_isotopomer/stage01_isotopomer_peakData_io.py
Python
mit
1,934
import unittest from datetime import datetime import pymongo from mongoengine import * from mongoengine.base import BaseField from mongoengine.connection import _get_db class DocumentTest(unittest.TestCase): def setUp(self): connect(db='mongoenginetest') self.db = _get_db() class Pe...
alex/mongoengine
tests/document.py
Python
mit
19,227
import unittest import datetime import struct from pyreplib import replay # Need to put in the useless bytes, so we replace 'x' (pad byte) with 'B'. PLAYER_PACK_FORMAT = replay.PLAYER_STRUCT_FORMAT.replace('x', 'B') HEADER_PACK_FORMAT = replay.HEADER_STRUCT_FORMAT.replace('x', 'B') class TestHelperFunctions(unittest...
HearthSim/pyreplib
tests/test_replay.py
Python
mit
7,090
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="font", parent_name="heatmapgl.hoverlabel", **kwargs ): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
plotly/plotly.py
packages/python/plotly/plotly/validators/heatmapgl/hoverlabel/_font.py
Python
mit
1,875
from django import forms def dummy_validator(value): if value == 'invalid': raise forms.ValidationError('invalid') return value class TestForm(forms.Form): foo = forms.CharField(required=False, validators=[dummy_validator]) bar = forms.CharField(help_text='help bar', required=False) baz ...
bmispelon/django-formtags
tests/forms.py
Python
mit
388
from components.base.ecu.software.abst_comm_layers import AbstractPhysicalLayer class StdPhysicalLayer(AbstractPhysicalLayer): ''' This class implements the Physical Layer of the implementation of a secure Communication Module, does actually nothing''' def __init__(self, sim_env): ...
PhilippMundhenk/IVNS
ECUSimulation/components/base/ecu/software/impl_physical_layers.py
Python
mit
1,524
# Written by Greg Ver Steeg (http://www.isi.edu/~gregv/npeet.html) import scipy.spatial as ss from scipy.special import digamma from math import log import numpy.random as nr import numpy as np import random # continuous estimators def entropy(x, k=3, base=2): """ The classic K-L k-nearest nei...
UltronAI/Deep-Learning
Pattern-Recognition/hw2-Feature-Selection/skfeature/utility/entropy_estimators.py
Python
mit
7,335
"""ML-ENSEMBLE Comparison of multiprocessing performance as data scales. Example Output -------------- ML-ENSEMBLE Threading performance test for data set dimensioned up to (10000, 50) Available CPUs: 4 Ensemble architecture Num layers: 2 Fit per base layer estimator: 2 + 1 layer-1 | Estimators: ['svr-1', 'svr-2',...
flennerhag/mlens
benchmarks/scale_cpu.py
Python
mit
5,516
from NodeDefender.manage.setup import (manager, print_message, print_topic, print_info) from flask_script import prompt import NodeDefender @manager.command def database(): print_topic('Database') print_info("Database is used to store presistant data.") print_info("By...
CTSNE/NodeDefender
NodeDefender/manage/setup/database.py
Python
mit
2,533
import sys, requests, json, csv key = "&wskey=<API KEY HERE> api = "http://www.europeana.eu/api/v2/search.json?" terms = ['proxy_dc_date','date'] types = ['IMAGE','TEXT'] #including year from_year = 1700 #until but excluding to_year = 2016 def getResults(term, types, conditions): global errors global key globa...
mzeinstra/Europeana-20th-century-gap
scrape.py
Python
mit
2,441
from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import logout from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.http import HttpResponseRedirect, HttpResponse from truco.forms import * from truco.models import Partida, Jugador...
emmanuel-santos/GEM
trucoGemSite/truco/views.py
Python
mit
4,850
import tty import sys import termios fd = sys.stdin.fileno() fdattrorig = termios.tcgetattr(fd) try: tty.setraw(fd) done = False while not done: ch = sys.stdin.read(1) sys.stdout.write('test: %s\r\n' % ord(ch)) if ord(ch) == 27: ch = sys.stdin.read(1) sys.st...
coreyabshire/marv
bin/experiments/key_test.py
Python
mit
472
"""SAJ solar inverter interface.""" from __future__ import annotations from datetime import date import logging import pysaj import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.const import ( ...
rohitranjan1991/home-assistant
homeassistant/components/saj/sensor.py
Python
mit
8,049
from kwonly_args import kwonly_defaults from .parser import ParserListener class ObjectBuilderParams(object): # By creating a subclass of this class and overriding these # attributes you can change the default values of __init__(). default_object_creator = None default_array_creator = None defaul...
pasztorpisti/json-cfg
src/jsoncfg/parser_listener.py
Python
mit
5,570
# -*- coding: utf-8 -*- # # catalog-harvesting documentation build configuration file, created by # sphinx-quickstart on Wed Jun 22 10:56:24 2016. # # 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 ...
ioos/catalog-harvesting
docs/source/conf.py
Python
mit
9,446
from settings import settings
bountyful/bountyfulcoins
bountyfulcoins/context_processors/__init__.py
Python
mit
29
AUTH_URL = "https://quality.hubwoo.com/rest/auth/latest/session"
AlexWPerfComm/Python-JIRA
const/Constants.py
Python
mit
65
# -*- coding: utf-8 -*- from datetime import datetime as dt import copy import random import os import traceback from tg import redirect, flash, expose, request, override_template from tg.decorators import paginate from ordering.controllers.basicMaster import * from ordering.model import * from ordering.util.common i...
LamCiuLoeng/jcp
ordering/controllers/master.py
Python
mit
23,382
__author__ = 'leif' from asg.abstract_search_game import ABSGame from asg.asg_generator import RandomYieldGenerator, TestHighYieldGenerator, ConstantLinearYieldGenerator, TestYieldGenerator, CueGenerator, GainBasedCueGenerator from asg.asg_generator import TestLowYieldGenerator, RandGainBasedCueGenerator from models im...
leifos/boxes
treasure-houses/asg/game.py
Python
mit
4,228
from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score from sklearn.naive_bayes import GaussianNB from threading import Thread import time from Queue import Queue, Empty from lib.in_subject_cross_validation import * import lib.in_subject_cross_valid...
jschavem/facial-expression-classification
source/classification/cv_subjects_multithreaded_pca.py
Python
mit
5,651
# For Arduino Data: import serial, signal, sys ################################################################################################ ARDUINO_SERIAL_PORT = '/dev/ttyACM0' # Serial port should be set to the port found in the Arduino Program when programming the board parallel_data_file = "parallel_data_file....
CACTUS-Mission/TRAPSat
rpi/tim/parallel_read_arduino.py
Python
mit
929
import myzlib st=z_stream() ZLIB_VERSION = "1.2.8" Z_NULL = 0x00 Z_OK = 0x00 Z_STREAM_END = 0x01 Z_NEED_DICT = 0x02 Z_NO_FLUSH = 0x00 Z_FINISH = 0x04 CHUNK = 1024 * 32 def compress(input, level=6): out = [] st = z_stream() st.avail_in = len(input) st.next_in = input st.avail_out = Z_NULL s...
drodri/python-cpp-accu2016
5pybind11_zlib/test_compress.py
Python
mit
2,059
from __future__ import print_function dictData = [ {'forename':'Marc','surname':'Mine','age':35, 'tags':('family','work'), 'job':{'name':'Baker','category':'Business'}, 'hobbies':[{'name':'swimming','period':7}, {'name':'reading','period':1}]}, ...
mtils/sqliter
examples/testdata.py
Python
mit
9,753
# standard library imports import io import logging import struct import warnings # 3rd party library imports import numpy as np from uuid import UUID # local imports from glymur import Jp2k from .lib import tiff as libtiff from .jp2box import UUIDBox # Map the numeric TIFF datatypes to the format string used by th...
quintusdias/glymur
glymur/tiff.py
Python
mit
24,820
import subprocess from utlz import func_has_arg, namedtuple CmdResult = namedtuple( typename='CmdResult', field_names=[ 'exitcode', 'stdout', # type: bytes 'stderr', # type: bytes 'cmd', 'input', ], lazy_vals={ 'stdout_str': lambda self: self.stdout.d...
theno/utlz
utlz/cmd.py
Python
mit
2,420
""" WSGI config for p27_d17 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`` ...
fogcitymarathoner/gae_p27_dj17
p27_d17_prj/wsgi.py
Python
mit
1,789
from ...utils.code_utils import deprecate_module deprecate_module("EMUtils", "waveform_utils", "0.16.0", error=True) from .waveform_utils import *
simpeg/simpeg
SimPEG/electromagnetics/utils/EMUtils.py
Python
mit
149
from dart.schema.base import base_schema, tag_list_schema from dart.schema.dataset import dataset_schema from dart.schema.event import event_schema from dart.schema.subscription import subscription_schema from dart.schema.workflow import workflow_schema def engine_schema(): return base_schema({ 'type': 'o...
RetailMeNotSandbox/dart
src/python/dart/schema/engine.py
Python
mit
3,658
# Workaround for issue in Python 2.7.3 # See http://bugs.python.org/issue15881#msg170215 try: import multiprocessing except ImportError: pass try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Igno...
winstonschroeder77/Python_KMR-1.8
setup.py
Python
mit
1,394
#!/usr/bin/env python import sys STRTAG = "<s" ENDTAG = "</s>" stc = None for l in sys.stdin: l = l.strip().split() # print >> sys.stderr, l[0] if l[0].startswith(STRTAG): stc = "" elif stc != None and l[0] == ENDTAG: if stc != "": print stc stc = None elif stc != None and l[0][0] != '<'...
ai-ku/upos_2014
src/scripts/sketct2tok.py
Python
mit
364
from django.apps import AppConfig class FilesConfig(AppConfig): name = 'files' verbose_name = 'Files' def ready(self): from . import signals
chaos-soft/chocola
files/apps.py
Python
mit
164
import sys import unittest __all__ = ['get_config_vars', 'get_path'] try: # Python 2.7 or >=3.2 from sysconfig import get_config_vars, get_path except ImportError: from distutils.sysconfig import get_config_vars, get_python_lib def get_path(name): if name not in ('platlib', 'purelib'): ...
letouriste001/SmartForest_2.0
python3.4Smartforest/lib/python3.4/site-packages/setuptools/py31compat.py
Python
mit
1,639
from nicepy.assertions import * from nicepy.decorators import * from nicepy.shortcuts import * from nicepy.utils import *
katakumpo/nicepy
nicepy/__init__.py
Python
mit
122
from decimal import Decimal import decimal from functools import total_ordering @total_ordering class Money(object): _round_amount = Decimal('1.00') def __init__(self, dollars=None, cents=None): if isinstance(dollars, Money): if cents: raise ValueError("if dollars is Money...
phillipgreenii/loan_payoff_tools
loan_payoff_tools/money.py
Python
mit
4,298
"""trackball_camera.py - An OpenGL Trackball Camera Class for Pyglet by Roger Allen, July 2008 roger@rogerandwendy.com A class for simple-minded 3d example apps. Usage: Initialize with a radius from the center/focus point: tbcam = TrackballCamera(5.0) After adjusting your projection matrix, set the modelview m...
fesh0r/xnb_parse
xnb_parse/trackball_camera.py
Python
mit
12,635
"""Unit tests for base41. Copyright: (c) Jazzy Services Limited 2017 License file: ../LICENSE """ import sys import unittest import context import base41 class Test_B41Encoder(unittest.TestCase): def test_sanity(I): 'Test the encoder with a standard byte string.' datum = b'John' sut = ...
JazzyServices/jazzy
tests/test_base41.py
Python
mit
19,680
import pytest from django.core.urlresolvers import reverse from django.test.utils import override_settings from democracy.models import Hearing @pytest.mark.django_db def test_hearing_delete_action(admin_client, default_hearing): change_url = reverse('admin:democracy_hearing_changelist') data = {'action': 'd...
stephawe/kerrokantasi
democracy/tests/test_admin.py
Python
mit
772
from django.core.urlresolvers import reverse from django.db import models from django.db.models import ObjectDoesNotExist from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel from jsonfield import JSONField ...
Bionetbook/bionetbook
bnbapp/bionetbook/_old/actions/models.py
Python
mit
3,335
from django import forms from django.utils.translation import ugettext_lazy as _ from registration.models import UserModel from models import User as AccountsUser class UserRegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in u...
hds-lab/dsechatweb
dsechat/apps/accounts/forms.py
Python
mit
4,148
from tests.integration.create_token import create_token from tests.integration.integration_test_case import IntegrationTestCase class TestQuestionnaireQuestionGuidance(IntegrationTestCase): def test_question_guidance(self): # Given I launch a questionnaire with various guidance token = create_tok...
qateam123/eq
tests/integration/questionnaire/test_questionnaire_question_guidance.py
Python
mit
4,682
""" ========================= Train error vs Test error ========================= Illustration of how the performance of an estimator on unseen data (test data) is not the same as the performance on training data. As the regularization increases the performance on train decreases while the performance on test is optim...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/examples/model_selection/plot_train_error_vs_test_error.py
Python
mit
2,578
# Copyright (c) Amber Brown, 2015 # See LICENSE for details. from __future__ import absolute_import, division from textwrap import dedent import pkg_resources from twisted.trial.unittest import TestCase from collections import OrderedDict from .._builder import render_fragments, split_fragments class FormatterT...
hawkowl/towncrier
src/towncrier/test/test_format.py
Python
mit
10,155
MOSTPOPULAR = [ 1342, # Pride and Prejudice 11, # Alice's Adventures in Wonderland 76, # Adventures of Huckleberry Finn 74, # The Adventures of Tom Sawyer 1952, # The Yellow Wallpaper 4300, # Ulysses 27827, # The Kama Sutra of Vatsyayana 174, # The Picture of Dorian...
andrewyang96/GutenbergsHorse
mostpopular.py
Python
mit
7,833
import astropy, astropy.io.fits as pyfits, numpy, scipy, sys, re,pylab def mypoly(a, x): #n = n terms in fit # float *a = poly terms, # x; = val array y = [1.] t = [x] print 'printing x' print x z=y[0]*t[0] #NORMPOINT = 10000 for i in range(1,len(a)+1): t.app...
deapplegate/wtgpipeline
subarucorr.py
Python
mit
4,836
# # Copyright 2015 by Justin MacCallum, Alberto Perez, Ken Dill # All rights reserved # import numpy as np import math class ProteinBase(object): ''' Base class for other Protein classes. Provides functionality for translation/rotation and adding H-bonds. ''' def __init__(self): self._t...
laufercenter/meld
meld/system/protein.py
Python
mit
7,985
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import simple_graph @pytest.fixture(scope="function") def create_graph(): new_graph = simple_graph.G() return new_graph @pytest.fixture(scope="function") def build_graph(create_graph): jerry = simple_gra...
jesseklein406/data-structures
tests/test_simple_graph.py
Python
mit
3,955
""" Basic widgets for UI. """ import csv import platform from enum import Enum from typing import Any, Dict from copy import copy from tzlocal import get_localzone import importlib_metadata from .qt import QtCore, QtGui, QtWidgets from ..constant import Direction, Exchange, Offset, OrderType from ..engine import Mai...
vnpy/vnpy
vnpy/trader/ui/widget.py
Python
mit
40,127
from ditutils.core import setup setup( name = 'morpheusapi', packages = ['morpheusapi'], version = '2.11.1', description = 'A python wrapper for Morpheus APIs', author = 'Adam Hicks', author_email = 'thomas.adam.hicks@gmail.com', url = 'https://github.com/tadamhicks/morpheus-python', dow...
tadamhicks/morpheus-python
setup.py
Python
mit
480
#! /usr/bin/python # -*- coding: utf-8 -*- import socket import threading from . import utils2 as utils from ..utils.message import info, error __author__ = 'fyabc' class LanClient: def __init__(self, user): self.user = user self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
fyabc/MiniGames
HearthStone2/MyHearthStone/network/lan_client.py
Python
mit
2,327
import os import csv import json from tables.templates import ( ResponseTemplate ) from seeders.base_seeder import BaseSeeder, print_delete_count class TemplateSeeder(BaseSeeder): def __init__(self, session): BaseSeeder.__init__(self, session) self.template_data = os.path.join(self.database_d...
Tactique/common
database/sql_scripts/seeders/template.py
Python
mit
1,052
from typing import List, Dict from pydantic import BaseModel, ValidationError class Pets(BaseModel): __root__: List[str] print(Pets.parse_obj(['dog', 'cat'])) print(Pets.parse_obj({'__root__': ['dog', 'cat']})) # not recommended class PetsByName(BaseModel): __root__: Dict[str, str] print(PetsByName.par...
samuelcolvin/pydantic
docs/examples/models_custom_root_field_parse_obj.py
Python
mit
478
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('gallery', '0005_piece_medium'), ] operations = [ migrations.AlterField( model_name='medium', name='m...
mudbungie/carrieocoyle
gallery/migrations/0006_auto_20151027_1101.py
Python
mit
404
import selector import socket mysel = selector.DefaultSelector() keep_running = True def read(connection, mask): ''' callback for read events ''' global keep_running client_address = connection.getpeername() print('read({})'.format(client_address)) data = connection.recv(1024) ...
gaufung/PythonStandardLibrary
Network/Selector/selector_echo_server.py
Python
mit
1,269
import _plotly_utils.basevalidators class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="namelengthsrc", parent_name="densitymapbox.hoverlabel", **kwargs ): super(NamelengthsrcValidator, self).__init__( pl...
plotly/python-api
packages/python/plotly/plotly/validators/densitymapbox/hoverlabel/_namelengthsrc.py
Python
mit
511
from celery import task @task() def add(x, y): return x + y
limbail/ceamon
pandorabox/ceamon/tasks.py
Python
mit
65
# coding: utf-8 # In[1]: import sys import pandas as pd import matplotlib.pyplot as plt filename1 = sys.argv[1] filename2 = sys.argv[2] #filename1 = "pagecounts-20160802-150000.txt" #filename2 = "pagecounts-20160803-150000.txt" # In[2]: dataframe1 = pd.read_table(filename1, sep=' ', header=None, index_col=1, ...
MockyJoke/numbers
ex2/code/create_plots.py
Python
mit
1,292
#!/usr/bin/env python3 import re import numpy as np import pandas as pd from bs4 import BeautifulSoup paper_session_ids = ['1a', '1b' ,'1c', '1d', '1e', '2a', '2b' ,'2c', '2d', '2e', '3a', '3b' ,'3c', '3d', '3e', '4a', '4b' ,'4c', '4d', '4e', ...
acl2017/acl2017.github.io
scripts/link-guidebook-authors-to-papers-and-posters.py
Python
mit
4,734
#!/usr/bin/env python import fnmatch import glob import os import sys from setuptools import setup with open("requirements.txt") as f: required = f.read().splitlines() VERSION = "1.2.4" setup( name='shmooze', version=VERSION, description='Framework for processed-backed web applications', author...
zbanks/shmooze
setup.py
Python
mit
1,029
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-09-11 01:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('message', '0001_initial'), ] operations = [ migrations.RemoveField( ...
tmcdonnell87/bananas
bananas/apps/message/migrations/0002_add_send_events.py
Python
mit
1,300
VERSION = "2.67.0"
stripe/stripe-python
stripe/version.py
Python
mit
19
import os import sys import logging import unittest try: # Append PySpark to PYTHONPATH / Spark 2.1.0 sys.path.append(os.path.join(os.environ["SPARK_HOME"], "python")) sys.path.append(os.path.join(os.environ["SPARK_HOME"], "python", "lib", "py4j-0.10.4-src.zip")) except Key...
datitran/PySpark-App-CF
tests/basetests.py
Python
mit
1,724
""" [2017-04-14] Challenge #310 [Hard] The Guards and the Mansion https://www.reddit.com/r/dailyprogrammer/comments/65fkwh/20170414_challenge_310_hard_the_guards_and_the/ # Description I recently came into some money and built myself a mansion. And I'm afraid of robbers who now want to come and steal the rest of my m...
DayGitH/Python-Challenges
DailyProgrammer/DP20170414C.py
Python
mit
1,976
# -*- coding: utf-8 -*- import http_lazy_headers as hlh from . import utils class TransferEncodingTest(utils.FieldTestCase): field = hlh.TransferEncoding def test_raw_values(self): self.assertFieldRawEqual( ['gzip, chunked', 'foobar;bar=qux'], ((hlh.Encodings.gzip, hlh.Para...
nitely/http-lazy-headers
tests/tests_fields_/tests_transfer_encoding.py
Python
mit
2,131
# coding=utf-8 __author__ = "zephor" class TestResultPipeLine(object): @classmethod def from_crawler(cls, crawler): crawler.spider.test_result = [] return cls() @staticmethod def process_item(item, spider): spider.test_result.append(item)
Zephor5/zspider
zspider/pipelines/test_result.py
Python
mit
283
""" Overrides the default URL open plugin command in Sublime Text. This gives me control over the regex so I can improve it over time. """ import sublime_plugin import webbrowser import re rex = re.compile( r'''(?x)(?i) \b(?: https?://(?:(?:[a-z\d][a-z\d\-_]*(?:\.[a-z\d\-._]+)+)|localhost)| # http:// ...
facelessuser/SublimeRandomCrap
url_open.py
Python
mit
1,951
import colorsys def to_rgb(hsv): """Converts a color from HSV to a hex RGB. HSV should be in range 0..1, though hue wraps around. Output is a hexadecimal color value as used by CSS, HTML and SVG""" r, g, b = [int(min(255, max(0, component * 256))) for component in colorsys.hsv_to_rgb(...
ondergetekende/python-panavatar
panavatar/color_scheme.py
Python
mit
5,222
import unittest from os import getcwd, path from maisen_core.helpers.runprogram import run_program class TestRunProgram(unittest.TestCase): def test_outputs(self): "Test outputs from program runner." pass def test_catching_program_errors(self): pass
mdziurzynski/maisen_core
tests/testrunprogram.py
Python
mit
287
# -*- coding: utf-8 -*- import time import os import asyncio from datetime import datetime from chunsabot.messages import Message, ResultMessage, ContentType from chunsabot.logger import Logger from chunsabot.database import Database from chunsabot.botlogic import Botlogic # async_status from threading import Thread ...
susemeee/Chunsabot-framework
chunsabot/chunsa.py
Python
mit
10,717
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Zheqi he, Xinlei Chen, based on code from Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __fu...
junranhe/tf-faster-rcnn
tools/test_net.py
Python
mit
3,912
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Apr 8 09:32:34 2017 This script is intended to import the fasta files into a SQL database for BLAST 4/9/17--wrote all fasta sequences to SQL that were extracted from MIRA. but still need to run the bash .sh scripts to pull the remaining. ##THIS IS VE...
DidemnumVex/IonTorrentVoucher
AssembledSequenceProcess.py
Python
mit
5,935
#!/usr/bin/env python """.""" import asyncio import inspect import io import subprocess import textwrap import traceback from contextlib import redirect_stdout import discord from discord.ext import commands from sys import platform class Admin: """.""" def __init__(self, bot): """.""" self.b...
Mat-Frayne/HsBot
cogs/Admin.py
Python
mit
7,956
from pokerstars.screen_scraper import ScreenScraper from public import map_card_string_to_tuple from public import change_terminal_color import re import time import json import copy class MoveCatcher(): def __init__(self, to_act, game_driver): self.to_act = to_act#{{{ self.game_driver ...
zhaw/Poker-Bot-Reformed
pokerstars/move_catcher.py
Python
mit
10,977
import bpy from bpy import context import string print("START") myObject = bpy.context.object try: myArmature = myObject.modifiers["Armature"].object.data #Doesn't work if your Armature modifier isn't named Armature. I don't think I care. except KeyError: print("Error: Armature is not named 'Armature'....
Ganonmaster/sfm-scripts
Met/JapoShit.py
Python
mit
5,997
print(len({(input()) for _ in range(int(input()))}))
avtomato/HackerRank
Python/_04_Sets/_04_Set .add()/solution.py
Python
mit
53
filenames = ['firstNames', 'secondNames', 'famousWrestlers', 'categories', 'jobs'] for filename in filenames: with open('%s.csv' % filename, 'r') as f: namelist = [] for name in f.read().split('\n'): if len(name)>1: namelist.append(name) with open('../js/%s.js' % filename, 'w') as dest_f: dest_f.write('%...
staudt/gimmick-generator
lists/generate.py
Python
mit
352
# 1. Create a new API key: https://exchange.gemini.com/settings/api # 2. Enter API key & secret below # 3. Optionally add any settings here that you want to override in settings.py API_KEY = 'gemini_API_KEY_here' API_SECRET = 'gemini_API_SECRET_here'
pirate/bitcoin-trader
secrets_default.py
Python
mit
252
import random import operator import copy from collections import Counter class Env(object): directions = [[1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]] empty = 'empty' @classmethod def flatten_list(cls, ls): l = [] for el in ls: if isinstance(el, li...
oddbitdev/schelling_model
schelling.py
Python
mit
6,435
# -*- coding: utf-8 -*- def device_location_token(pushbots, platform, token, lat, lng): return pushbots.device_location(platform=platform, token=token, lat=lat, lng=lng) def device_location_data(pushbots, data): return pushbots.device_location(data=data)
tchar/pushbots
pushbots/tests/device_location.py
Python
mit
303
# getnics.py - script to get the internal IP addresses from the VMs in a scale set # to do: do not hardcode the rgname and vmssname - instead make them command line # parameters import azurerm import json # Load Azure app defaults try: with open('azurermconfig.json') as configFile: configData = json.load(con...
gbowerman/vmsstools
cpuload/getnics.py
Python
mit
1,010