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 |
|---|---|---|---|---|---|
import sys
import os
import json
import hashlib
import codecs
import base64
import requests
import ConfigParser
from urllib import quote
from datetime import datetime
DIR = os.path.dirname(__file__)
CONFIG_FILE = os.path.join(DIR, 'settings.cfg')
class Uploader():
def upload_data(self, path, data):
url =... | device42/SolarwindsWHD | d42_sync_tool.py | Python | mit | 12,130 |
import os
import sys
import numpy as np
from theano import config
from pandas import DataFrame
from seizure.cnn.conv_net import ConvNet
from seizure.cnn_trainer.loader import load_train, load_test
config.floatX = 'float32'
def train_and_test(patient_name, prediction_target, root_path, csv_path):
path = root_p... | IraKorshunova/kaggle-seizure-detection | seizure/cnn_trainer/main.py | Python | mit | 4,444 |
# Copyright (c) 2016-2021 John Mihalic <https://github.com/mezz64>
# Licensed under the MIT license.
# Used this guide to create module
# http://peterdowns.com/posts/first-time-with-pypi.html
# git tag 0.1 -m "0.1 release"
# git push --tags origin master
#
# Upload to PyPI Live
# python setup.py register -r pypi
# py... | mezz64/pyHik | setup.py | Python | mit | 905 |
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# 表示怀疑是中等题
return sorted(nums, reverse=True)[k - 1]
| Junnplus/leetcode | algorithms/medium/kth-largest-element-in-an-array.py | Python | mit | 242 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import configparser
import datetime
import email.encoders
import email.mime.base
import email.mime.image
import email.mime.multipart
import email.mime.text
import getpass
import optparse
import os
import smtplib
import sys
# ipa参数
ipaRootDir = "/Users/" + getpass.getuser... | atbj505/pythonIpa | pythonIpa/package.py | Python | mit | 11,636 |
#
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/
#
class BSTIterator(object):
def __init__(self, ro... | hs634/algorithms | python/trees/morris_traversal.py | Python | mit | 1,400 |
# Copyright 2001 Brad Chapman.
# Revisions copyright 2009-2010 by Peter Cock.
# Revisions copyright 2010 by Phillip Garland.
# All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""D... | zjuchenyuan/BioWeb | Lib/Bio/Blast/Applications.py | Python | mit | 56,120 |
## A module to do operations on SQllite db , Execute DDL , bhav csv to bhav table etc ##
## Licensed Freeware ##
## Author Paarth Batra ... | PaarthBatra/Predict_StockMarket | Database/SQLiteDBOperations.py | Python | mit | 7,467 |
#!/usr/bin/python
# Chat Program
# author: https://medium.com/@dataq
# execute server: ./chat.py server <IP>:<PORT>
# execute server: ./chat.py client <Server IP>:<Server PORT> <username>
# type "/<username> <message>" to send private message
import sys
import socket
import select
import signal
import json
class Ser... | datanduth/python-tutorial | Network Tutorial/Chat/chat.py | Python | mit | 4,718 |
#!/usr/bin/env python
'''
FILE NAME : [:VIM_EVAL:]expand('%:t')[:END_EVAL:]
AUTHOR : msarver
CREATE DATE : [:VIM_EVAL:]strftime('%d %B %Y')[:END_EVAL:]
'''
| mrsarver/dotfiles | .vim/skeleton/skeleton.py | Python | mit | 157 |
from flask_wtf import FlaskForm
from wtforms import TextAreaField
from wtforms.validators import InputRequired, Length
class CommentForm(FlaskForm):
""" Form for comments. """
comment = TextAreaField('Comment:', validators=[InputRequired(),
Length(min=6,
... | oldani/nanodegree-blog | app/forms/comment_form.py | Python | mit | 486 |
__author__ = 'lac'
import datetime
from django.http import HttpResponse,Http404
from django.shortcuts import render,render_to_response
from django.template import RequestContext
from myblog.models import BlogPost
from django.http import Http404, HttpResponseRedirect
from django.views.decorators.cache import cache_page... | liaicheng/lacblog | code/myblog/views.py | Python | mit | 3,993 |
# I want to Define what descriptors can be used with each weapon.
# I'll start with first, opening, and reading a file
# with a weapon and its damage type on it.
import sys
wepfile = "Weapons.txt"
# Define the 'Weapon' Class, which will be how the weapon information is stored.
class WeaponObj(object):
... | Laventhros/DescGenerator | Test.py | Python | mit | 2,088 |
import json
import csv
def get_a(channel, device):
filename = "channels/%s/%s.csv" % (channel, device)
y = []
with open(filename, 'rb') as f:
reader = csv.reader(f)
#channel = "CP_OP10C_D"
i = 0
z = []
for row in reade... | mabotech/mabo.io | node/opcua/monitor/parse_tags02.py | Python | mit | 1,157 |
from HTMLParser import HTMLParser
class ItemGridParser(HTMLParser):
def __init__(self, html_string, *args, **kwargs):
HTMLParser.__init__(self, *args, **kwargs)
self.products = []
HTMLParser.feed(self, html_string)
@property
def product_id_to_product_path(self):
return dict(self.products)
@... | silasbw/hungryskunk | goodeggs_parser.py | Python | mit | 2,996 |
import json
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.generics import ListCreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from apis.betterself.v1.events.filters import SleepLogFilter
from apis.betterself.v1.events.serializers... | jeffshek/betterself | apis/betterself/v1/sleep/views.py | Python | mit | 2,651 |
from __future__ import unicode_literals, print_function, absolute_import
from nikola.plugin_categories import SignalHandler
from nikola import utils
from nikola import metadata_extractors
import blinker
import hashlib
import io
import os
__all__ = []
_LOGGER = utils.get_logger('static_comments')
class Comment(obj... | getnikola/plugins | v8/static_comments/static_comments.py | Python | mit | 11,214 |
__all__ = ["make_graph", "add_edges", "Results",
"find_solution", "add_edges_numerical", "find_solution_numerical"]
import numpy as np
import copy
import networkx as nx
def make_graph(node_ids, node_labels):
"""
Make an undirected graph with the nodes specified
in `node_ids`. Each node will hav... | dhuppenkothen/AstroChairs | astrochairs/graphscheduler.py | Python | mit | 19,634 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
carry = 0
head = ListNode(0)
l3 = head
whil... | rahul-ramadas/leetcode | add-two-numbers/Solution.8447558.py | Python | mit | 868 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from pyquery import PyQuery as pq
import re, os, multiprocessing
from CnbetaApis.datas.Models import *
from urllib.parse import urlparse
from CnbetaApis.datas.get_article_by_id import get_article_by_id, fixSource
from requests import get
from datetime import datetime, time... | kagenZhao/cnBeta | CnbetaApi/CnbetaApis/datas/get_home_models.py | Python | mit | 8,089 |
from random import randint
'''
This is an easy copy/paste for creating dicts:
Table = {
'': ,
'': ,
'': ,
'': ,
'': ,
'': ,
'': ,
'':
}
'''
def random_choice(chances_dict):
chances = chances_dict.values()
strings = list(chances_dict.keys())
return strings[random_choice_index(chances)... | venn177/heroesoflegend.py | heroesoflegend/rolltables.py | Python | mit | 96,123 |
import numpy as np
import pytest
from lsh.cache import Cache
from lsh.minhash import MinHasher
@pytest.fixture
def default_hasher():
return MinHasher(seeds=100)
@pytest.fixture
def default_cache(default_hasher):
return Cache(default_hasher)
def is_nondecreasing(L):
# http://stackoverflow.com/a/498335... | mbatchkarov/LSH | lsh/test/test_cache.py | Python | mit | 9,113 |
from setuptools import setup
setup(name='scram_plot',
version='0.68.0',
description='scram_plot',
author='Stephen Fletcher',
author_email='s.fletcher@uq.edu.au',
license='MIT',
packages=['scram_plot'],
classifiers=[
# How mature is this project? Common values are
# 3... | sfletc/scram2_plot | setup.py | Python | mit | 1,074 |
# -*- coding: utf-8 -*-
import json
import pytest
import pyroonga
from pyroonga.odm import query, table
from pyroonga.tests import utils as test_utils
class TestGroongaRecord(object):
@pytest.fixture
def Table1(self, Table):
class Tb(Table):
name = table.Column()
grn = pyroonga... | naoina/pyroonga | pyroonga/tests/functional/odm/test_query.py | Python | mit | 3,656 |
import random
import math
import check_eng
def decrypt(msg, key):
no_of_col = math.ceil(len(msg)/key)
no_of_row = key
unused = (no_of_row * no_of_col) - len(msg)
dec = [''] * no_of_col
col = 0
row = 0
for symbol in msg:
dec[col] = dec[col] + symbol
col = col + 1
if(col == no_of_col ... | AlMikFox3/Ciphers | TranspositionCipher/hack_transposition.py | Python | mit | 880 |
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# if we want to connect to a broker on a different machine we'd simply specify its name or IP address here
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='... | calebgregory/scraps | rabbitmq/helloworld/send.py | Python | mit | 434 |
"""
The topography module provides interfaces to global elevation models.
So far, only an interface to the `SRTM30
<https://dds.cr.usgs.gov/srtm/version2_1/SRTM30/srtm30_documentation.pdf>`_ data
set is provided, which has a resolution of 1 km.
Elevation data is downloaded on the fly but is cached to speed up subseque... | atmtools/typhon | typhon/topography.py | Python | mit | 15,246 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Event'
db.delete_table('narrative_event')
def backwards(self, orm):
# Adding... | ambitioninc/django-narrative | narrative/south_migrations/0007_auto__del_event.py | Python | mit | 5,756 |
import lldb
import os
kNoResult = 0x1001
@lldb.command("load_swift")
def load_swift(debugger, path, ctx, result, _):
with open(os.path.expanduser(path)) as f:
contents = f.read()
if path.endswith(".swift"):
options = lldb.SBExpressionOptions()
options.SetLanguage(lldb.eLanguageTypeSwif... | sberrevoets/dotfiles | lldbhelpers/load_swift.py | Python | mit | 543 |
from __future__ import print_function
import filecmp
import glob
import itertools
import os
import sys
import sysconfig
import tempfile
import unittest
project_dir = os.path.abspath(os.path.join(__file__, '..', '..', '..'))
test_dir = os.getenv("BROTLI_TESTS_PATH")
BRO_ARGS = [os.getenv("BROTLI_WRAPPER")]
# Fallback... | google/brotli | python/tests/_test_utils.py | Python | mit | 3,811 |
#!python
import boto.kinesis
con = boto.kinesis.connect_to_region('ap-northeast-1')
res = con.delete_stream('test')
print res
| digitalbot/KinesisSample | delete-stream.py | Python | mit | 135 |
import logging
from pprint import pformat
from .. import settings
LOG = logging.getLogger(__name__)
# Event handler mapping
handlers = {}
# Event types
UNHANDLED = -1
MSG = 1
JOIN = 2
LEAVE = 3
INVITE = 4
PROFILE_CHANGE = 5
class RoomEventHandlerType(type):
"""
Metaclass that automatically registers the r... | simonklb/matrix-leaf | leaf/client/room_event.py | Python | mit | 7,074 |
# 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-mgmt-network/azure/mgmt/network/v2017_11_01/operations/application_security_groups_operations.py | Python | mit | 20,853 |
# 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/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/aio/operations/_load_balancer_probes_operations.py | Python | mit | 8,483 |
# coding=utf-8
from django.http import HttpResponse, HttpResponseServerError
from .models import CompoundAdverseEvent, OpenFDACompound, AdverseEvent
import ujson as json
# TODO TODO TODO REVISE IN PYTHON 3
import cgi
import html
def main(request):
"""Default to Server Error"""
return HttpResponseServerError(... | UPDDI/mps-database-server | drugtrials/ajax.py | Python | mit | 6,822 |
#!/usr/bin/python
import abc
class base_fun(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self):
pass
@abc.abstractmethod
def run(self):
return
| trelay/multi-executor | main/main.py | Python | mit | 211 |
import tarfile
import io
import sys
from datetime import datetime
import pytz
tz = pytz.timezone('Asia/Kolkata')
archive_size = 1000 # lines
log_dir = '/home/ubuntu/migration/slog/'
def archive_gen():
log_count = 0
while True:
data = yield
log_count += 1
... | apoorv-kumar/PyThugLife | logx/giant_compressed_log.py | Python | mit | 1,761 |
from jsonmodels.models import Base
from .channel import Channel
class Device(Base):
""" Contains info about a device and it's channels. """
def __init__(self, **kwargs):
"""
Initializes a Device object by looping through the
keywords in kwargs and setting them as attributes.
:... | keerts/pyninjasphere | pyninjasphere/logic/device.py | Python | mit | 744 |
#rainfall sensor.
#VCC
#GND
#DO <--> GPIO(X12) Digital data
#AO <--> ADC Port(X11) Analog data
#if value is low than defined data, DO value is 0,
#if value is high than defined data, DO value is 1.
#AO is the specific value.
import pyb
from pyb import Pin
p_in = Pin('X12', Pin.IN, Pin.PULL_UP)
p_in.value
adc = pyb... | Python-IoT/Smart-IoT-Planting-System | device/src/rainfall.py | Python | mit | 609 |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
i... | onshape-public/onshape-clients | python/onshape_client/oas/api/release_management_api.py | Python | mit | 30,910 |
"""Echo request message tests."""
from pyof.foundation.basic_types import DPID, HWAddress
from pyof.v0x01.common.phy_port import PhyPort, PortConfig, PortState
from pyof.v0x01.controller2switch.features_reply import FeaturesReply
from tests.test_struct import TestStruct
class TestFeaturesReply(TestStruct):
"""Fea... | cemsbr/python-openflow | tests/v0x01/test_controller2switch/test_features_reply.py | Python | mit | 1,921 |
#!/usr/bin/env python
# "genstyles" Notepad++ to Atom Syntax Style Converter
# Copyright (c) 2014, Adam Rehn
#
# Script to convert Notepad++ style XML files to LESS stylesheets for Atom.
#
# Requires the following files in the current directory:
#
# styleMappings.json - contains required conversion information... | adamrehn/notepad-plus-plus-default-styles | genstyles/genstyles.py | Python | mit | 3,631 |
import ast
import csv
import datetime
import pytz
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.dialects.postgresql import INET
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Gateway(Base):
__tablename__ = 'gateways'
id = Column(Inte... | Fluent-networks/floranet | floranet/data/seed/gateways.py | Python | mit | 1,604 |
# Copyright (c) Hynek Schlawack, Richard Wall
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
import getdns
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath
from OpenSSL import crypto
from danex import _dane
class TLSAD... | hynek/tnw | danex/test/test_dane.py | Python | mit | 12,017 |
"""pytest tests for reading the result file"""
import pytest
import serpentTools.data
from serpentTools.settings import rc
@pytest.fixture(scope="module")
def read_2_1_29():
with rc:
rc["serpentVersion"] = "2.1.29"
yield
@pytest.fixture
def fullPwrFile(read_2_1_29):
return serpentTools.data... | CORE-GATECH-GROUP/serpent-tools | tests/test_pt_results.py | Python | mit | 740 |
#! /usr/bin/python3
import xmlrpc.client
SATELLITE_URL = 'https://pm1.solutions.local/rpc/api'
SATELLITE_LOGIN = ''
SATELLITE_PASSWORD = ''
client = xmlrpc.client.Server(SATELLITE_URL, verbose=0)
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)
existing_channels = [x['label'] for x in client.channel.lis... | peteches/Houston | sync_repos.py | Python | mit | 477 |
# coding: utf8
from __future__ import print_function
from itertools import product
from nltk.tree import Tree
class ChunkTreeInformationExtractor():
def __init__(self):
self.arg = lambda chunk: ' '.join([word for word, tag in chunk.leaves()])
def extract(self, chunked_tree):
""" extracts information from chu... | sobhe/baaz | baaz/ChunkTreeInformationExtractor.py | Python | mit | 2,465 |
#!/usr/bin/env python
import argparse
import os
import subprocess
import sys
from lib.config import get_target_arch, PLATFORM
from lib.util import meson_gyp, import_vs_env
CONFIGURATIONS = ['Release', 'Debug']
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PRODUCT_NAME = meson_gyp()['prod... | go-meson/framework | script/build.py | Python | mit | 1,907 |
# Copyright (C) 2020 kamyu. All rights reserved.
#
# Google Code Jam 2014 Qualification Round - Problem C. Minesweeper Master
# https://code.google.com/codejam/contest/2974486/dashboard#s=p2
#
# Time: O(R * C)
# Space: O(1)
#
def minesweeper_master():
R, C, M = map(int, raw_input().strip().split())
result, em... | kamyu104/GoogleCodeJam-2014 | Qualification Round/minesweeper_master.py | Python | mit | 1,750 |
import InstagramAPI
# /////// CONFIG ///////
username = ''
password = ''
debug = False
photo = '' # path to the photo
caption = '' # caption
# //////////////////////
i = InstagramAPI.Instagram(username, password, debug)
try:
i.login()
except Exception as e:
e.message
exit()
try:
i.uploadPhoto(pho... | danleyb2/Instagram-API | examples/uploadPhoto.py | Python | mit | 376 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the MIT License
"""
Bootstrapping Lattice graph designer
Detect environment and execute program from source
@author: Ivan Luchko (luchko.ivan@gmail.com)
"""
if __name__ == '__main__':
import sys
from latticegraph_designer.app i... | luchko/latticegraph_designer | bootstrap.py | Python | mit | 356 |
from pyga.operator.mutation import Mutation
class ListOrderMutation(Mutation):
"""
Mutate order on candidate which has data of list type.
:param mutations: int
:param probability: Probability
:param random: Random
"""
def __init__(self, probability, random, mutations):
super().__i... | Eyjafjallajokull/pyga | pyga/operator/list_order_mutation.py | Python | mit | 867 |
# encoding: utf-8
# pylint: disable=too-few-public-methods,invalid-name,bad-continuation
"""
RESTful API User resources
--------------------------
"""
import logging
from flask_login import current_user
from flask_restplus_patched import Resource
from app.extensions.api import Namespace, http_exceptions
from app.ext... | millen1m/flask-restplus-server-example | app/modules/users/resources.py | Python | mit | 3,746 |
"""mydisk URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | KirovVerst/photogram | photogram/urls.py | Python | mit | 1,311 |
from django.http import Http404,HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from mysite.credits.models import Student,Logdate
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.core.context_processors import csrf
import decimal
imp... | berry10086/credit | mysite/views.py | Python | mit | 1,964 |
# coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_cl... | ltowarek/budget-supervisor | third_party/saltedge/test/test_consent_request_body.py | Python | mit | 942 |
# -*- coding: utf-8 -*-
from src.actions import BambooFilterableMenu, HOST_URL, PLANS_CACHE_KEY, UPDATE_INTERVAL_PLANS, \
BambooWorkflowAction, build_bamboo_facade
from src.util import workflow
class BranchesFilterableMenu(BambooFilterableMenu):
def __init__(self, args):
super(BranchesFilterableMenu, ... | mibexsoftware/alfred-bamboo-workflow | workflow/src/actions/branches.py | Python | mit | 2,616 |
import pickle
import numpy as np
import os
import cv2
import random
import gate
from itertools import repeat
import sys
import time
INPUT_SIZE = 32 * 32 * 3
OUTPUT_SIZE = 1
HEAD_START = 10
TRAINING_DURATION = 3
TRAINING_SAMPLE_SIZE = 200
TESTING_SAMPLE_SIZE = 100
def load_batch(fpath, label_key='labels'):
# Int... | mertyildiran/GateFactory | examples/classification_medium.py | Python | mit | 4,925 |
from maka.data.EditHistory import Edit, EditHistory
class Document(object):
extensionName = None # string, more human-friendly than class name
observationClasses = None # set, useful for constructing document formats
fieldClasses = None # set, useful for constructing... | HaroldMills/Maka | src/maka/data/Document.py | Python | mit | 4,372 |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | onshape-public/onshape-clients | python/onshape_client/oas/models/bt_update_mesh_units_params.py | Python | mit | 4,589 |
from django.shortcuts import render
from .models import Contest, Score
from django.http import Http404
from problems.models import Problem
from datetime import datetime
from django.template.context_processors import csrf
from django.contrib.auth.models import User
from django.utils import timezone
from core.models impo... | cs251-eclipse/EclipseOJ | EclipseOJ/contests/views.py | Python | mit | 6,017 |
from collections import namedtuple
import lasagne as nn
from lasagne.layers.dnn import Conv2DDNNLayer, MaxPool2DDNNLayer
import data_iterators
import numpy as np
import theano.tensor as T
from functools import partial
import nn_heart
import utils_heart
from pathfinder import PKL_TRAIN_DATA_PATH, TRAIN_LABELS_PATH, PKL_... | 317070/kaggle-heart | ira/configurations/ch4_zoom_leaky_after_nomask_seqshift.py | Python | mit | 9,506 |
from rl.core import Processor
from rl.memory import Memory
from rl.policy import Policy
from package.environment import SeleniumEnvironment
class AbstractConfiguration(object):
mode = None # type: KickoffModes
use_preset_training = None # type: bool
render = None # type: bool
warmup_steps = None... | bewestphal/SeleniumAI | package/models.py | Python | mit | 1,419 |
__author__ = 'chris'
import sys
import argparse
import json
import time
from twisted.internet import reactor
from txjsonrpc.netstring.jsonrpc import Proxy
from binascii import hexlify, unhexlify
from dht.utils import digest
from txjsonrpc.netstring import jsonrpc
from market.profile import Profile
from protos import ob... | the9ull/OpenBazaar-Server | networkcli.py | Python | mit | 27,857 |
import redis
import yaml
import json
from slackclient import SlackClient
##############
# user stuff #
##############
class UserMap:
"""
So we don't have to keep track of two dictionaries.
Easiest is just to keep one instance of this in the game state.
We create this at the beginning of the game.
... | nickweinberg/werewolf-slackbot | plugins/werewolf/user_map.py | Python | mit | 1,736 |
import collections
import cProfile
import pstats
import functools
import unittest
data = """turn on 489,959 through 759,964
turn off 820,516 through 871,914
turn off 427,423 through 929,502
turn on 774,14 through 977,877
turn on 410,146 through 864,337
turn on 931,331 through 939,812
turn off 756,53 through 923,339
tu... | misterwilliam/advent-of-code | 6/main.py | Python | mit | 13,814 |
# -*- coding: utf-8 -*-
import os
from fabric.api import *
import config
import david
# Example usage
env.hosts = ['david@david']
APP_ROOT = os.path.dirname(os.path.abspath(__file__)) + '/david'
TRANSLATION_ROOT = APP_ROOT + '/translations'
REMOTE_APP_ROOT = '/srv/user/david/app/tongdawei.cc'
REMOTE_ALEMBIC_CONFIG... | ktmud/david | fabfile.py | Python | mit | 2,023 |
import os
import warnings
from gcloud import storage
import pocs.utils.logger
class PanStorage(object):
""" Class for interacting with Google Cloud Platform """
def __init__(self, project_id='panoptes-survey', bucket_name=None, prefix=None):
assert bucket_name is not None, warnings.warn(
... | AstroHuntsman/POCS | pocs/utils/google/storage.py | Python | mit | 3,627 |
class Entity():
"""
Class to represent an antity used to hold the information for debtor and
creditor
@ivar _name: Entity name
@type _name: string
@ivar _address_lines: List of address lines for the entity (max 5 lines)
@type _address_lines: string
@ivar _country: Country
@typ... | luojus/bankws | bankws/entity.py | Python | mit | 1,061 |
import unittest
from irc_hooky.github.pull_request import PullRequest
from irc_hooky.github.pull_request_event import PullRequestEvent
from irc_hooky.github.github_user import GithubUser
class TestPullRequestEvent(unittest.TestCase):
def setUp(self):
self.ghpre = PullRequestEvent()
def test_default_... | marvinpinto/irc-hooky | tests/github/test_pull_request_event.py | Python | mit | 1,926 |
cal=0
print("Welcome to Chip's fast food imporium")
print("(1)Cheeseburger (461 calories)")
print("(2)Fish Burger (431 calories)")
print("(3)Veggie Burger (420 calories)")
print("(4)None(0 calories)")
burger=input("Please enter a burger choice:")
if burger==1:
cal+=461
if burger==2:
cal+=431
if burger==3:
cal+=420
i... | lizerd123/github | Dungeon/burger.py | Python | mit | 1,185 |
from datetime import datetime
from unittest import skip
from django.test import TestCase
from pyanalysis.apps.corpus import models as corpus_models
from pyanalysis.apps.dimensions import registry
class DatasetModelTest(TestCase):
def test_created_at_set(self):
"""Dataset.created_at should get set automat... | nanchenchen/script-analysis | pyanalysis/apps/corpus/tests.py | Python | mit | 4,324 |
"""
WSGI config for pizzaweb 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.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | DaBbleR23/Pizza-web | pizzaweb_backend/pizzaweb/pizzaweb/wsgi.py | Python | mit | 393 |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
HostIncompatibleForRecordReplayReason = Enum(
'processor',
'product',
)
| xuru/pyvisdk | pyvisdk/enums/host_incompatible_for_record_replay_reason.py | Python | mit | 243 |
import sys
from setuptools import setup, find_packages
py26_dependency = []
if sys.version_info[:2] <= (2, 6):
py26_dependency = ["argparse >= 1.1", "ordereddict >= 1.1"]
setup(
name='dataset',
version='0.7.0',
description="Toolkit for Python-based data processing.",
long_description="",
clas... | stefanw/dataset | setup.py | Python | mit | 1,472 |
import _plotly_utils.basevalidators
class SymmetricValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="symmetric", parent_name="scatter.error_y", **kwargs
):
super(SymmetricValidator, self).__init__(
plotly_name=plotly_name,
parent... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/error_y/_symmetric.py | Python | mit | 425 |
#!/usr/bin/env python3
##
## Mixlr ChatBox (IRC)
##
## Version: idunnolol?
## Dependency: https://pypi.python.org/pypi/irc
##
## Description: this is poorly commented and written. I don't know what I'm doing, lol?
## Original Author: Bob Barker
##
## PS. this is really dumb, like multiple layers of abstraction dumb.
#... | therealtakeshi/jefflr | pymixlr/chatbox.py | Python | mit | 3,106 |
# -*- encoding: utf-8 -*-
import socket
class conversador:
def __init__(self):
self.PORT = 50007
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.data = ''
def connectar(self, identitat, adreca):
"""
El constructor de la classe
estableix la connexió am... | kitusmark/bash-python | Chat Project/conversador.py | Python | mit | 2,145 |
#!/usr/bin/env python
from setuptools import setup, find_packages
from imp import load_source
setup(
name='cmis',
version=load_source('', 'cmis/_version.py').__version__,
description='A server architecture built on top of a solid foundation '
'provided by flask, sqlalchemy, and various ext... | concordusapps/python-cmis | setup.py | Python | mit | 1,105 |
# -*- coding: utf-8 -*-
import mock
import falcon
import falcon.testing
from keyard.app import utils
from keyard.app import errors
class TestUtils(falcon.testing.TestBase):
@mock.patch('keyard.app.utils._add_error_handlers')
def test_prepare_app(self, handler_mock):
app = mock.MagicMock()
ut... | rzanluchi/keyard | tests/app/test_utils.py | Python | mit | 941 |
from django.conf import settings
def google_credentials(request):
return {
'GOOGLE_ANALYTICS_KEY': getattr(settings, 'GOOGLE_ANALYTICS_KEY', False),
'GOOGLE_TAG_MANAGER': getattr(settings, 'GOOGLE_TAG_MANAGER', False),
'GOOGLE_MAPS_API_KEY': getattr(settings, 'GOOGLE_MAPS_API_KEY', False)... | springload/madewithwagtail | core/context_processors.py | Python | mit | 845 |
import os
from AppKit import *
import vanilla
from defconAppKit.controls.placardScrollView import DefconAppKitPlacardNSScrollView, PlacardPopUpButton
# -------
# Sorting
# -------
def fontFileNameSort(fonts):
sortable = []
noPathCounter = 0
for font in fonts:
if font.path is not None:
... | Ye-Yong-Chi/defconAppKit | Lib/defconAppKit/controls/fontList.py | Python | mit | 17,293 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
下载国家气象局所有气候数据 (VPN连接)
"""
import os
import re
import threading
from ftplib import FTP
from time import sleep
def ftp_get_data(tid, n, step):
# year: 1901 - 2017
# pattern = r"[12][09][0-9]{2}"
start = n
end = n + step - 1
if n == 1:
start ... | qrsforever/workspace | python/test/noaa/get_beijing_weather.py | Python | mit | 2,835 |
import json
import re
import os
import time
from google.appengine.api import memcache
from google.appengine.api import urlfetch
import jinja2
import webapp2
import yaml
from google.appengine.ext import vendor
vendor.add('lib')
import twitter
def rel(path):
return os.path.join(os.path.dirname(__file__),path)
... | hancock-lighting/hancock.lighting | src/backend/weatherbeacon.py | Python | mit | 4,640 |
# coding=utf8
class Config(object):
DEBUG = False
TESTING = False
class ProductionConfig(Config):
pass
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
| torpedoallen/amazing | config.py | Python | mit | 218 |
"""View of the notification window."""
from gi.repository import Gtk
from lib.mvc.bases import WindowViewBase
from lib.exception_feedback import add_default_exception_handling
from lib.helpers import getuid
class NotificationWindowView(Gtk.Window, WindowViewBase):
def __init__(self, app, model):
"""Ctor... | realm01/gnome-quota-indicator | lib/mvc/notification_window/view.py | Python | mit | 3,331 |
from collections import deque
try:
from lxml.html import fromstring, tostring
import difflib
except ImportError: fromstring = tostring = None
class Element(object):
tag = None
format = '<{tag}{attrs}>{text}{children}</{tag}>'
attr_remap = {}
def __init__(self, *args, **kwargs):
self.... | zeekay/elemental | elemental/core.py | Python | mit | 6,783 |
import json
import time
import os
import libgreader as gr
class JsonArchive(object):
def __init__(self, fn):
self.fn = fn
self.loaded = set()
self.items = []
self.min_time = None
self.max_time = None
if not os.path.exists(fn):
open(fn, "wb").close()
... | deactivated/google-jawa | google_jawa/__init__.py | Python | mit | 3,236 |
import copy
from nylas.client.restful_model_collection import RestfulModelCollection
from nylas.client.restful_models import Scheduler
from nylas.client.scheduler_models import (
SchedulerTimeSlot,
SchedulerBookingConfirmation,
)
class SchedulerRestfulModelCollection(RestfulModelCollection):
def __init__... | nylas/nylas-python | nylas/client/scheduler_restful_model_collection.py | Python | mit | 2,374 |
from datetime import datetime, date, timedelta
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.generic import View
from app.models import Task
def get_day_of_week(date... | schatten/planner | app/views.py | Python | mit | 5,291 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-18 15:37
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20170718_1517'),
]
operati... | OleaGulea/fin_manager | fin_manager/users/migrations/0003_auto_20170718_1837.py | Python | mit | 754 |
from django.shortcuts import render, get_object_or_404, redirect
from optboard.settings import MEDIA_ROOT
from collections import OrderedDict
from queue import Queue
import subprocess
import base64
import io
import os
import re
import ast
from .models import Solver, Result, Project
from .forms import SolverForm, Proje... | tanutarou/OptBoard | dashboard/views.py | Python | mit | 10,474 |
import random
from transitions import *
class Markov(object):
def __init__(self, agent_aux):
self.agent = agent_aux
self.markov = TransitionMatrix(self.agent.markov_matrix)
def runStep(self, markov_matrix):
self.markov.matrix = markov_matrix
currentState = self.agent.state
numberCurrentState = False
se... | gsi-upm/soba | projects/oldProyects/EWESim/behaviourMarkov.py | Python | mit | 1,237 |
"""
The DNSLookupCheckCollector does a DNS lookup and returns a check
##### Dependencies
* socket
Example config file DNSLookupCheckCollector.conf
```
enabled = True
ttl = 150
dnsAddressList = www.google.com, www.yahoo.com
```
"""
from collections import defaultdict
import diamond.collector
try:
import socket
exc... | Netuitive/netuitive-diamond | src/collectors/dnslookupcheck/dnslookupcheck.py | Python | mit | 2,280 |
from __future__ import absolute_import
import logging
from math import ceil
import numpy as np
import subprocess
from . import liblinear_utils
import local_pyutils
ONE_BASED = 0 # until we don't support the MATLAB version
# if not ONE_BASED:
# raise NotImplementedError('ZERO_BASED not supported.')
def create_... | alliedel/anomalyframework_python | anomalyframework/shuffle.py | Python | mit | 4,986 |
import settings as s
import decimal
from csv import DictReader, DictWriter
from sys import exit
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
DEBUG = s.DEBUG
def get_name_list(poi_dataset):
"""
Returns list of names of POIs in order of appearance in dataset
"""
assert ... | JimHaughwout/GADM_DBSCAN | utils.py | Python | mit | 5,820 |
########################################################################
# Helper functions
########################################################################
import os
import json
def save_wardata(wardata):
if wardata['state'] != 'notInWar':
war_id = "{0}{1}".format(wardata['clan']['tag'][1:],
... | mehdisadeghi/clashogram | clashogram/utils.py | Python | mit | 1,378 |
from .base import (rpartial, BaseAllocateCase, BaseSplitCase, BasePackCase,
BaseGetBandCase, BaseMergeCase, BaseUnpackCase)
from .pillow import Image, PillowTestCase
class AllocateCase(BaseAllocateCase):
def runner(self):
Image.new(self.mode, self.size)
class UnpackCase(BaseUnpackCase... | python-pillow/pillow-perf | testsuite/cases/pillow_allocate.py | Python | mit | 1,605 |
import os, sys
cmdstring = "dmd "
currentDirName = os.path.basename( os.getcwd() )
if sys.platform.startswith( "win" ):
slash = "\\"
outfileSuffix = ".exe"
else:
slash = "/"
outfileSuffix = ".bin"
# Recursively add all files in "./" and below for compilation.
for dirpath, dirlist, filelist in os.walk( "." ):
fo... | jackoblades/D_MarkovChain | make.py | Python | mit | 1,113 |
# views.py - Django views for notification management web interface
#
# Copyright (c) 2014, 2015, 2017 Jim Fenton
#
# 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, includ... | jimfenton/notif-mgmt | mgmt/views.py | Python | mit | 10,845 |