code stringlengths 1 199k |
|---|
from rest_framework import routers
from . import views
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'complaints', views.ComplaintViewSet)
urlpatterns = router.urls |
'''
automate_scrape.py - runs throught the online verision of the text book, 'Automate the boring stuff with python' and pulls out all of the projects and stores them in a file.
'''
import requests, os, bs4, sys
def page_download(web_page, chapter_num, no_project_count, no_chapter_projects):
'''
Downloads the w... |
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Gwangcoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"gwangcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" "... |
import numpy as np
import tensorflow as tf
from agent.forward import Forward
from config import *
_EPSILON = 1e-6 # avoid nan
class Framework(object):
def __init__(self, access, state_size, action_size, scope_name):
self.Access = access
self.action_size = action_size
self.action_space = lis... |
from collections import Counter
from clarify_python.helper import get_embedded_items, get_link_href
MAX_METADATA_STRING_LEN = 2000
def default_to_empty_string(val):
return val if val is not None else ''
class ClarifyBrightcoveBridge:
def __init__(self, clarify_client, bc_client):
self.clarify_client = c... |
"""Softmax."""
scores = [3.0, 1.0, 0.2]
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x) / sum(np.exp(x))
print(softmax(scores))
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(... |
'''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
import ... |
import json
from django_api_tools.APIModel import APIModel, UserAuthCode
from django_api_tools.APIView import APIUrl, ReservedURL, StatusCode
from django_api_tools.tests.models import Foo, Bar, Baz, Qux, TestProfile
from django_api_tools.tests.views import TestAPIView
from django.test import TestCase
from django.test.c... |
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils.translation import ugettext as _
class UserProfile(models.Model):
'''
username: 用户名是唯一的,可以为Nul... |
from math import trunc
from .utils import ceil, jwday, monthcalendarhelper
from . import gregorian
EPOCH = 1948439.5
WEEKDAYS = ("al-'ahad", "al-'ithnayn",
"ath-thalatha'", "al-'arb`a'",
"al-khamis", "al-jum`a", "as-sabt")
HAS_29_DAYS = (2, 4, 6, 8, 10)
HAS_30_DAYS = (1, 3, 5, 7, 9, 11)
def leap... |
import unittest
import lib.globalclasses as gc
from lib.const import *
class UTGeneral(unittest.TestCase):
#local
#ID:0-99
def test_01_setting_signature(self):
print("\nThe expected unit test environment is")
print("1. TBD")
self.assertEqual(gc.SETTING["SIGNATURE"],'LASS-SIM')
de... |
import asyncio
import unittest
import random
from gremlinpy import Gremlin
from . import ConnectionTestCases, EntityTestCases, MapperTestCases
from gizmo import Mapper, Request, Collection, Vertex, Edge
from gizmo.mapper import EntityMapper
class BaseTests(unittest.TestCase):
def setUp(self):
self.request =... |
"""
This is used to pack testlib into a json
Then you can load into database by using:
manage.py loaddata <fixturename>
fixturename here is `testlib.json`
"""
import hashlib
import json
from os import path, listdir
def hash(binary):
return hashlib.sha256(binary).hexdigest()
category = ['checker', 'generator',... |
"""ShipToasting web handlers."""
import os
import sys
import atexit
import random
import traceback
import gevent
from flask import Response
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from apscheduler.schedulers.gevent import GeventScheduler
from ship... |
"""
flask.ext.acl
=============
This extension provides an Access Control implementation for `tipfy <http://www.tipfy.org/>`_.
Links
-----
* `Documentation <http://www.tipfy.org/wiki/extensions/acl/>`_
* `Source Code Repository <http://code.google.com/p/tipfy-ext-acl/>`_
* `Issue Tracker <http://code.google.com/p/tipfy... |
from django.db import models
from ..Models import *
from center.Exceptions.ModelsExceptions import *
class Tools_todo(models.Model):
STATUS_TYPES = (
(1, u'New'),
(2, u'Doing'),
(3, u'Waiting'),
(4, u'Done'),
)
SPECIES_TYPES = (
(1, u'Task'), # 查询
(2, u'Check'... |
telescope = "ATCA"
latitude_deg = -30.312906
diameter_m = 22.0
import os
import sys
from util_misc import ascii_dat_read
def main():
# Read the station lookup table
col, dummy = ascii_dat_read("ATCA_stations.txt", delim=" ",
doFloatCols=[2, 3])
statDict = {}
for st... |
__author__ = 'USER'
from learning.mlp.neuralnetwork import NeuralNetwork
from learning.mlp import learning
number_of_layers = 3
size_array = [2, 2, 1]
learning_rate = 0.3
momentum = 0.1
bnn = NeuralNetwork(number_of_layers, size_array, learning_rate, momentum)
xor_in = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
]... |
import os
import unittest
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.utils.conanfile import TestConanFile
from conans.test.utils.tools import TestClient, TestServer,\
NO_SETTINGS_PACKAGE_ID
from conans.util.files import set_dirty
class PackageIngrityTest(unittest.TestCase):
... |
import unittest
import Web_Method_Baspd
import Public_Base_Method
import requests
import time
import HTMLTestRunner
class ST_Bas_pd(unittest.TestCase):
u'商品功能性测试'
def setUp(self):
global cookie
r = Public_Base_Method.login_func("172.31.3.73:6020", "dongshichao", "dong", "a111111")
cookie... |
import glob
import numpy as np
import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.A*")
def between_range(row):
subset = repeats.loc... |
from livereload import Server, shell
server = Server()
style = ("style.scss", "style.css")
script = ("typing-test.js", "typing-test-compiled.js")
server.watch(style[0], shell(["sass", style[0]], output=style[1]))
server.watch(script[0], shell(["babel", script[0]], output=script[1]))
server.watch("index.html")
server.se... |
"""
EXAMPLE: Working with the uiverse class
"""
from universe import universe
import pandas as pd
usEqUniverse = universe('usEquityConfig.txt')
usEqUniverse.computeSummary()
usEqUniverse.assetReturns.AA.plot() |
import sys
import getpass
import helper
from argparse import ArgumentParser
if __name__ == "__main__":
parser = ArgumentParser(description="Simple file password based encryption/decryption tools. When run as pipe, use standard in/out.")
parser.add_argument("-a", "--action", choices=["encrypt", "decrypt"], requi... |
import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from ... |
import re
import abc
from collections import deque
from copy import copy
from rdp.ast import Node
from rdp.exceptions import ParseError, UnexpectedToken
from rdp.utils import chain
def to_symbol(str_or_symbol, copy_if_not_created=False):
if isinstance(str_or_symbol, Symbol):
if copy_if_not_created:
... |
from logging import getLogger
from yarl import URL
from aiohttp import BasicAuth
try:
from aiosocks import Socks4Auth, Socks5Auth
except ImportError:
class Socks4Auth(Exception):
def __init__(*args, **kwargs):
raise ImportError(
'You must install aiosocks to use a SOCKS proxy... |
from pandac.PandaModules import *
from toontown.toonbase.ToonBaseGlobal import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.fsm import StateData
from toontown.toontown... |
from __future__ import unicode_literals
from httoop import URI
def test_simple_uri_comparision(uri):
u1 = URI(b'http://abc.com:80/~smith/home.html')
u2 = URI(b'http://ABC.com/%7Esmith/home.html')
u3 = URI(b'http://ABC.com:/%7esmith/home.html')
u4 = URI(b'http://ABC.com:/%7esmith/./home.html')
u5 = URI(b'http://ABC... |
import os
import glob
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from tensorflow.contrib.keras.python import keras
from scipy import misc
def make_dir_if_not_exist(path):
if not os.path.exists(path):
os.makedirs(path)
def show(im, x=5, y=5):
plt.figure(figsi... |
import re
from user import make_anonymous_user
from exeptions import HttpStatusError, RegexError
def make_subject_url(url):
if url.endswith("/"):
return url + "subject.txt"
else:
return url + "/subject.txt"
def parse_board(string):
if not isinstance(string, unicode):
raise TypeError(... |
from tehbot.plugins import *
import tehbot.plugins as plugins
import wolframalpha
import prettytable
class WolframAlphaPlugin(StandardPlugin):
def __init__(self):
StandardPlugin.__init__(self)
self.parser.add_argument("query", nargs="+")
def initialize(self, dbconn):
StandardPlugin.initi... |
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting SUN values"""
n = Decimal("2000000... |
"""Detect same images and try to merge metadatas before deleting duplicates"""
import PIL.Image as Image
import PIL.ImageChops as ImageChops
import sys
import os
import pyexiv2
import datetime
import logging
def handler_mergeList(a, b):
"""List merger"""
#FIXME : there is certainly a better python way !
for... |
import pykka
from rx.subjects import *
from TorrentPython.DownloadManager import *
from TorrentPython.RoutingTable import *
class DownloaderActor(pykka.ThreadingActor):
def __init__(self, downloader):
super(DownloaderActor, self).__init__()
self.downloader = downloader
self.download_manager ... |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class ItemUpdateDelistingRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.num_iid = None
def getapiname(self):
return 'taobao.item.update.delisting' |
import os
import gnomevfs
from datetime import datetime
def get_file_info(uri):
"""Return the File information if uri exists"""
if uri is not None and gnomevfs.exists(uri):
return gnomevfs.get_file_info(uri)
return False
def is_uri_dir(uri):
"""Checks if given uri is a dir"""
file_info = get... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'video_gallery.tests.south_settings')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import unittest
from datetime import datetime
from tasks import old_issues as c
class TestCloseOldIssue(unittest.TestCase):
def test_is_closed_issue(self):
self.assertEquals(c.is_closed({'closed_at': None}), False)
self.assertEquals(c.is_closed({'closed_at': "2014-10-10T00:09:51Z"}), True)
def t... |
from __future__ import print_function, division # Valid as of 2.6
import sys
sys.path.insert(0, '/home/droark/Projects/etotheipi-BitcoinArmory')
import binascii, hashlib, string, os
from collections import namedtuple
from math import ceil, log
from copy import deepcopy
from armoryengine.BinaryUnpacker import * # Armory... |
'''
Online link spider test
'''
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import next
import unittest
from unittest import TestCase
import time
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__)... |
from org.gluu.model.custom.script.type.user import CacheRefreshType
from org.gluu.util import StringHelper, ArrayHelper
from java.util import Arrays, ArrayList
from org.gluu.oxtrust.model import GluuCustomAttribute
from org.gluu.model.custom.script.model.bind import BindCredentials
import java
class CacheRefresh(CacheR... |
import _plotly_utils.basevalidators
class ShowtickprefixValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="showtickprefix", parent_name="layout.yaxis", **kwargs
):
super(ShowtickprefixValidator, self).__init__(
plotly_name=plotly_name,
... |
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class ShopifyAccount(ProviderAccount):
pass
class ShopifyProvider(OAuth2Provider):
id = 'shopify'
name = 'Shopify'
accou... |
import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose... |
from django.contrib import admin
from .models import User
admin.site.register(User) |
from nota import Nota
from timingpoint import TimingPoint
from tools import *
import random
import math
def get_Name (osufile):
Splitlines = osufile.split('\n')
for Line in Splitlines:
if len(Line) > 0:
if Line.find('Title:', 0, len(Line)) != -1:
title = Line.split(':', 1)
return title[1].replace("\r", "")
... |
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="size", parent_name="histogram2d.xbins", **kwargs):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
ed... |
from twilio.rest import TwilioTaskRouterClient
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
client = TwilioTaskRouterClient(account_sid, auth_token)
workspace = client.workspaces.get(workspace_sid)
statistics = workspace.statistic... |
import numpy as np
__all__ = [
'multi_view_learner',
]
class multi_view_model(object):
def __init__(self, models):
self.models = models
def apply(self, features):
if len(features) != len(self.models):
raise ValueError('milk.supervised.two_view: Nr of features does not match t... |
"""
The MIT License (MIT)
Copyright (c) 2015 Ricardo Yorky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, ... |
import os
import copy
import scipy.interpolate as spi
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
data_root = 'toneclassifier'
train_data_path = "%s/train" % data_root
val_data_path = "%s/test" % data_root
test_data_path = "%s/test_new" % data_root
def SetPath(roo... |
"""
Post processing (subset of columns) to calculate intermediate sum edit counts
and other variables. Date sorted.
Usage:
calculate_intermediate_sums (-h|--help)
calculate_intermediate_sums <input> <output>
[--debug]
[--verbose]
Options:
-h, -... |
from collections import defaultdict
from django import template
from django.utils.safestring import mark_safe
from censusreporter.apps.census.utils import parse_table_id, generic_table_description, table_link
register = template.Library()
@register.filter
def format_subtables_for_results(table_ids):
parts = []
... |
import os
import os.path
import flask
import flask_assets
import flask_sqlalchemy
from .cross_domain_app import CrossDomainApp
from zeeguu.util.configuration import load_configuration_or_abort
import sys
if sys.version_info[0] < 3:
raise "Must be using Python 3"
app = CrossDomainApp(__name__)
load_configuration_or_... |
import re
import os
import struct
import sys
import numbers
from collections import namedtuple, defaultdict
def int_or_float(s):
# return number, trying to maintain int format
if s.isdigit():
return int(s, 10)
else:
return float(s)
DBCSignal = namedtuple(
"DBCSignal", ["name", "start_bit", "size", "is_l... |
"""Provides helper classes for testing option handling in pip
"""
import os
from pip._internal.cli import cmdoptions
from pip._internal.cli.base_command import Command
from pip._internal.commands import commands_dict
class FakeCommand(Command):
name = 'fake'
summary = name
def main(self, args):
inde... |
import numpy as np
class NeuralTrain:
def step_function(self, x):
return np.array(x > 0, dtype=np.int)
def sigmoid_function(self, x):
return 1 / (1 + np.exp(-x))
def relu_function(self, x):
return np.maximum(0, x) |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TanitJobsCategory(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return "%s" % self.name
class Kee... |
""" OneLogin_Saml2_Utils class
Copyright (c) 2014, OneLogin, Inc.
All rights reserved.
Auxiliary class of OneLogin's Python Toolkit.
"""
import base64
from datetime import datetime
import calendar
from hashlib import sha1, sha256, sha384, sha512
from isodate import parse_duration as duration_parser
import re
from textw... |
from Tkinter import *
import Pmw
import os
import numpy
class Ekin_map_annotate:
def map_datatab2structure(self):
"""If the PEATDB record has a structure, then we allow the user to map each datatab
to a specific part of the protein.
One can map a datatab to an atom, a residue, a chain, or de... |
from temp_tools import TestClient
from test_template import ApiTestTemplate
class TokensTest(ApiTestTemplate):
def setUp(self):
super(TokensTest, self).setUp()
TestClient.execute("""TRUNCATE auth_token""")
self.test_token_data = {'description': 'Test token 1',
... |
import six
if six.PY2:
import csv
import codecs
import cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__... |
from app import db
class Alternative(db.Model):
id = db.Column(db.Integer, primary_key=True)
experiment = db.Column(db.String(500), unique=True)
copy = db.Column(db.String(2500))
def __init__(self, id, experiment, copy):
self.id = id
self.experiment = experiment
self.copy = copy
... |
from rest_framework import serializers
from .models import User, Activity, Period
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email')
extra_kwargs = {
'url': {'view_name': 'timeperiod:user-detail'},
... |
if __name__ == '__main__':
import metrixpp
metrixpp.start() |
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
app_paths = None
def setup():
global app_paths
pymodules = []
for app in frappe.get_all_apps(True):
try:
pymodules.append(frappe.get... |
import hashlib
import os
import tempfile
import zipfile
from bs4 import BeautifulSoup
from django.test import Client
from django.test import TestCase
from mock import patch
from ..models import LocalFile
from ..utils.paths import get_content_storage_file_path
from kolibri.core.auth.test.helpers import provision_device
... |
from django.http import HttpResponse
from django.shortcuts import render
from survey.models import Choice
from survey.forms import ChoiceForm
import csv
import random
def index(request):
examples = ['controlling Exposure', 'changing Temperature', 'modifying Highlights', 'changing Shadows', 'Zooming in/out', 'changing... |
"""
Run on cluster
"""
import argparse
import os
import itertools
import networkx as nx
import pandas as pd
from . import compare_cases
def generate_run(graph, iterations, epsilon_control, epsilon_damage,
out_dir, nodes=None, mem=6000, runtime=120, activate=''):
"""
Generate bash scripts for an... |
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://mpdev.mattew.se'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = False |
'''
Created on Feb 20, 2013
@author: Maribel Acosta
@author: Fabian Floeck
'''
from wmf import dump
from difflib import Differ
from time import time
from structures.Revision import Revision
from structures.Paragraph import Paragraph
from structures.Sentence import Sentence
from structures.Word import Word
from structur... |
"""
The MIT License (MIT)
Copyright (c) <2015> <sarangis>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
import unittest
import os
from unittest.mock import patch
import migration
from configuration import Builder
import configuration
from tests import testhelper
class MigrationTestCase(unittest.TestCase):
def setUp(self):
self.rootfolder = os.path.dirname(os.path.realpath(__file__))
@patch('migration.Comm... |
from flask import Blueprint
error = Blueprint('error', __name__, )
from . import view |
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age > 36 and age <= 50):
return 5
elif age > 20 and age <= 35:
return 2
elif age < 10:
return 0
else:
return 1
def calculate_score_for_status(status):
... |
"""Angles and anomalies.
"""
from astropy import units as u
from poliastro.core.angles import (
D_to_M as D_to_M_fast,
D_to_nu as D_to_nu_fast,
E_to_M as E_to_M_fast,
E_to_nu as E_to_nu_fast,
F_to_M as F_to_M_fast,
F_to_nu as F_to_nu_fast,
M_to_D as M_to_D_fast,
M_to_E as M_to_E_fast,
... |
import sys
sys.path.append("/mnt/moehlc/home/idaf_library")
import vigra
import libidaf.idafIO as io
import numpy as np
from scipy import ndimage
from scipy.stats import nanmean
import time
import pickle
import os
import multiprocessing as mp
def gaussWeight(dat,sigma,mu):
return 1./np.sqrt(2*np.pi*np.square(sigma))*n... |
import sys
import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from matplotlib import path
from quadr import quadr
from LapSLPmatrix import LapSLPmatrix
def test_SLPn():
# test data dir
import os
dir_path = os.path.dirname(os.path.realpath(__file__)) + "/TestData/"
circle = sio.loadmat(dir_... |
from ..client import MODE_CHOICES
from ..client.tasks import ReadChannelValues, WriteChannelValue
from ..client.worker import Worker
from ..utils.command import BaseCommand
from ..values.channel import Channel
from ..values.signals import ValueChangeEvent
from optparse import OptionGroup, OptionConflictError
import log... |
from unittest import TestCase
from plivo import plivoxml
from tests import PlivoXmlTestCase
class RecordElementTest(TestCase, PlivoXmlTestCase):
def test_set_methods(self):
expected_response = '<Response><Record action="https://foo.example.com" callbackMethod="GET" ' \
'callbackU... |
from . import display
from . import prefs
from . import constants
from . import FoundationPlist
from munkilib.purl import Purl
from munkilib.phpserialize import *
import subprocess
import pwd
import sys
import hashlib
import platform
from urllib import urlencode
import re
import time
import os
from Foundation import NS... |
from pcitweak.bitstring import BitString
for n in range(0x10):
b = BitString(uint=n, length=4)
print " % 3d 0x%02x %s" % (n, n, b.bin) |
import luhn
def test_checksum_len1():
assert luhn.checksum('7') == 7
def test_checksum_len2():
assert luhn.checksum('13') == 5
def test_checksum_len3():
assert luhn.checksum('383') == 3
def test_checksum_len4():
assert luhn.checksum('2827') == 3
def test_checksum_len13():
assert luhn.checksum('43465... |
import unittest2
from zounds.util import simple_in_memory_settings
from .preprocess import MeanStdNormalization, PreprocessingPipeline
import featureflow as ff
import numpy as np
class MeanStdTests(unittest2.TestCase):
def _forward_backward(self, shape):
@simple_in_memory_settings
class Model(ff.Bas... |
"""
Django settings for expense_tracker project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
impor... |
def create_pos_n_neg():
for file_type in ['neg']:
for img in os.listdir(file_type):
if file_type == 'pos':
line = file_type+'/'+img+' 1 0 0 50 50\n'
with open('info.dat','a') as f:
f.write(line)
elif file_type == 'neg':
... |
import socket
import nlp
class NLPServer(object):
def __init__(self, ip, port):
self.sock = socket.socket()
self.sock.bind((ip, port))
self.processor = nlp.NLPProcessor()
print "Established Server"
def listen(self):
import thread
self.sock.listen(5)
print "Started listening at port."
while True:
c ... |
"""
Tests the pooled server
:license: Apache License 2.0
"""
from jsonrpclib import ServerProxy
from jsonrpclib.SimpleJSONRPCServer import PooledJSONRPCServer
from jsonrpclib.threadpool import ThreadPool
import random
import threading
import unittest
def add(a, b):
return a+b
class PooledServerTests(unittest.TestCa... |
import re, random, string
from Service import Service
class StringHelper(Service):
articles = ["a", "an", "the", "of", "is"]
def randomLetterString(self, numCharacters = 8):
return "".join(random.choice(string.ascii_letters) for i in range(numCharacters))
def tagsToTuple(self, tags):
return tuple(self.titleCase(... |
import unittest
from katas.kyu_6.help_the_bookseller import stock_list
class StockListTestCase(unittest.TestCase):
def setUp(self):
self.a = ['ABAR 200', 'CDXE 500', 'BKWR 250', 'BTSQ 890', 'DRTY 600']
self.b = ['A', 'B']
def test_equals(self):
self.assertEqual(stock_list(self.a, self.b)... |
import unittest
import smart_open.utils
class ClampTest(unittest.TestCase):
def test_low(self):
self.assertEqual(smart_open.utils.clamp(5, 0, 10), 5)
def test_high(self):
self.assertEqual(smart_open.utils.clamp(11, 0, 10), 10)
def test_out_of_range(self):
self.assertEqual(smart_open.... |
import os, argparse
from flask import Flask
parser = argparse.ArgumentParser() #настройка аргументов принимаемых с консоли
parser.add_argument("--port", default='7000', type=int, help='Port to listen'),
parser.add_argument("--hash-algo", default='sha1', type=str, help='Hashing algorithm to use'),
parser.add_argument(... |
"""
Python module for generating fake total emission in a magnitude band along a sightline.
This uses the Arepo/Illustris output GFM_Photometrics to get photometric band data,
which may or may not be accurate.
"""
from __future__ import print_function
import math
import os.path as path
import shutil
import h5py
import ... |
from django.shortcuts import render
from CnbetaApis.datas.Models import *
from CnbetaApis.datas.get_letv_json import get_letv_json
from CnbetaApis.datas.get_youku_json import get_youku_json
from django.views.decorators.csrf import csrf_exempt
from django.http import *
from datetime import timezone, timedelta
import jso... |
from django.utils import six
from sortedone2many.fields import SortedOneToManyField
def inject_extra_field_to_model(from_model, field_name, field):
if not isinstance(from_model, six.string_types):
field.contribute_to_class(from_model, field_name)
return
raise Exception('from_model must be a Mode... |
from subprocess import *
import gzip
import string
import os
import time
import ApplePythonReporter
class ApplePythonReport:
vendorId = YOUR_VENDOR_ID
userId = 'YOUR_ITUNES_CONNECT_ACCOUNT_MAIL'
password = 'ITUNES_CONNECT_PASSWORD'
account = 'ACCOUNT_ID'
mode = 'Robot.XML'
dateType = 'Daily'
... |
from django_evolution.mutations import AddField, RenameField
from django.db import models
MUTATIONS = [
RenameField('FileDiff', 'diff', 'diff64', db_column='diff_base64'),
RenameField('FileDiff', 'parent_diff', 'parent_diff64',
db_column='parent_diff_base64'),
AddField('FileDiff', 'diff_hash... |
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='poloniex',
version='0.1',
packages=[
'poloniex',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.