code stringlengths 1 199k |
|---|
import math
import sys, os
def is_prime(n):
#---------------------------------------------------------------------------
# Method 1: The naive way.
#---------------------------------------------------------------------------
# mid = int(math.sqrt(n))
# for i in range(2, mid + 1):
# if n % i ... |
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without ... |
import six
import numbers
from .hash import hash160
from .tools import StringIO
from .base58 import VersionedPayload
from .destination import PubKeyHashId, ScriptHashId
from .errors import InvalidAddressError
class BitcoinAddress(VersionedPayload):
PUBKEY_HASH = 0
SCRIPT_HASH = 5
def __new__(cls, hash=None,... |
from baseMultiple import CBaseMultiple
from statisticalArbitrageMultiple import CStatisticalArbitrageMultiple
from formatPairDataMultiple import CFormatPairDataMultiple |
from django.conf.urls import *
from rest_framework import routers
urlpatterns = patterns(
'api_users.api.views',
url(r'^login/$', 'login', name='api_login'),
url(r'^signup/$', 'signup', name='api_signup'),
url(r'^lost_pword/$', 'lost_password', name='api_lost_password'),
url(r'^me/$', 'me', name='ap... |
import pandas as pd
ordered_satisfaction = ['Very unhappy', 'Unhappy', 'Neutral', 'Happy', 'Very Happy']
df = pd.DataFrame({'satisfaction': ['Mad', 'Happy', 'Unhappy', 'Neutral']})
df.satisfaction = df.satisfaction.astype('category', ordered=True, categories=ordered_satisfaction).cat.codes
print(df)
ani = ['Bird', 'Bir... |
from __future__ import absolute_import
import os, sys
from ignition import mergevars
from ignition.plugin import Plugin
class Mapping(Plugin):
def __init__(self):
super().__init__()
def on_program_init(self, program, **kwargs):
mapping = kwargs.get("remap", {})
if not type(mapping) is di... |
from cryptarithmetic import solve
from time_measure import timedcall
import time
examples = """TWO + TWO == FOUR
A**2 + B**2 == C**2
A**2 + BE**2 == CY**2
X / X == X
A**N + B**N == C**N and N > 1
ATOM**0.5 == A + TO + M
GLITTERS is not GOLD
ONE < TWO and FOUR < FIVE
ONE < TWO < THREE
RAMN == R**3 + RM**3 == N**3 + RX**... |
import asyncio
import logging
import aiohttp_debugtoolbar
from core import common, utils
from worker.queue_consumer import AsyncQueueConsumer
from worker.api import views as api_views
log = logging.getLogger(__name__)
class WorkerApp(common.BaseApplication):
def __init__(self, name, loop=None, router=None, middlewa... |
from setuptools import setup
version = '0.3.5'
url = 'https://github.com/Who8MyLunch/ipynb_canvas_widget'
download_url = '{}/tarball/{}'.format(url, version)
setup(name='widget_canvas',
description='A canvas image widget for the IPython Notebook',
version=version,
author='Pierre V. Villeneuve',
... |
"""
testkit.data
~~~~~~~~~~~~
Various Data Test Tools
"""
import random
NUMBERS = "0123456789"
SYMBOLS = """!@#$%^&*()_+=-[]\;',./{}|:"<>?~`"""
ALPHAS_LOWER = "abcdefghijklmnopqrstuvwxyz"
ALPHAS_UPPER = ALPHAS_LOWER.upper()
ALL_ALPHAS = ALPHAS_LOWER + ALPHAS_UPPER
ALPHA_NUMERIC = ALL_ALPHAS + NUMBERS
ALL_CHARS = SYMBOL... |
from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.httpexceptions import HTTPNotFound, HTTPFound
from .view_base import ViewBase
from ..models.meta import DBSession
from ..models.topic import Topic
from ..models.services.topic import TopicRecordService
""" Discussion
Classes:
* Dis... |
from __future__ import unicode_literals
import time
BLOG_AUTHOR = "Nikola Tesla" # (translatable)
BLOG_TITLE = "My Nikola Site" # (translatable)
SITE_URL = "http://matuu.github.io/nikola-gray-bootstrap-theme/"
BLOG_EMAIL = "n.tesla@example.com"
BLOG_DESCRIPTION = "This is a demo site for Nikola." # (translatable)
DE... |
import gtk
import sys
action = sys.argv[1]
uris = "\n".join(sys.argv[2:])
gnome_copied_files = action + "\n" + uris
targets = [("x-special/gnome-copied-files",0,0), ("text/uri-list",0,0), ("text/plain;charset=utf-8",0,0)]
def get_func(clipboard, selection_data, info, data):
if selection_data.get_target() == "x-specia... |
import ctypes
from ctypes.util import find_library
try:
library = ctypes.CDLL(find_library("simple-tiles"))
library.simplet_map_new()
except:
print "can't find the library for this test, you might want to run make install" |
"""
Django settings for my_edge project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from django.core.urlresolvers import reverse_lazy
from os.path import dirname... |
from setuptools import setup, find_packages
setup(
name = "seznam-captcha",
version = "1.2.1",
url = 'https://github.com/sikaondrej/seznam-captcha/',
download_url = 'https://github.com/sikaondrej/seznam-captcha/',
license = 'MIT Licence',
author = "Ondrej Sika",
aurhor_email = "ondrej@ondrej... |
import sys
def solveGomoku(size, grid, findAll=False):
"""Find the winning player from a gomoku game state.
If findAll is True, try to find all winning sets of 5 pawns."""
# Function to read the grid
def getPawn(row, col):
if (row < 0) or (row >= size) or (col < 0) or (col >= size):
... |
class TreeNode(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
fmt = 'TreeNode(data={}, left={}, right={})'
return fmt.format(self.data, self.left, self.right)
class BinarySearchTree(object)... |
from django.db import models
from datetime import datetime, timedelta
from durationfield.db.models.fields.duration import DurationField
from riders.models import Teammate
from django.utils import timezone
class Link(models.Model):
user = models.ForeignKey('riders.Teammate', verbose_name = "Rider")
kintera_id = models... |
class Listener:
def __init__(self):
import log
self.myLog = log.Log('listener.log')
# files and paths
self.fileName = 'rectest.wav' # default file name
import os
if not os.path.isfile(self.fileName):
file = open(self.fileName,'w')
file.write(""... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20171020_1502'),
]
operations = [
migrations.AlterField(
model_name='post',
name='slug',
field=mod... |
from GUI import *
def verify_username(username):
if username == "Luke":
return True
else:
return False
def verify_password(password):
if password == "password":
return True
else:
return False
def start_main_gui():
main_gui = MainImplementation("res/Main.glade", "SecureMail_Main")
main_gui.start_window()
c... |
import sys
import petsc4py
petsc4py.init(sys.argv)
import numpy as np
from petsc4py import PETSc
from src import stokes_flow as sf
from src.myio import *
from src.objComposite import createEcoliComp_tunnel
from src.myvtk import *
def get_problem_kwargs(**main_kwargs):
problem_kwargs = get_solver_kwargs()
OptDB ... |
__version__ = '$Id$'
from tools.docco.rl_doc_utils import *
from reportlab.platypus.tableofcontents import TableOfContents
from datetime import datetime
import reportlab
title("ReportLab PDF Library")
title("User Guide")
centred('ReportLab Version ' + reportlab.Version)
centred(datetime.now().strftime('Document generat... |
"""
Created on Mon Feb 26 14:29:11 2018
@author: Christian Bender
@license: MIT-license
This module contains some useful classes and functions for dealing
with linear algebra in python.
Overview:
- class Vector
- function zero_vector(dimension)
- function unit_basis_vector(dimension, pos)
- function axpy(scalar, vector... |
import json
from pprint import pprint
import sys
import os
folder = sys.argv[1]
print "Analyzing data from folder " + folder
os.chdir(folder)
archive_files = sorted([f for f in os.listdir(folder) if f.endswith('.tar.gz')])
analysis = {}
one_day_average = {}
for file in archive_files:
print "Analyzing tar.gz file: " + ... |
"""
eater.api.base
~~~~~~~~~~~~~~
Base Eater API classes and utilities.
"""
from abc import ABC, abstractmethod
from typing import Union, Callable
from schematics import Model
class BaseEater(ABC):
"""
Base Eater class.
"""
@property
@abstractmethod
def request_cls(self) -> Callable[... |
from operator import itemgetter
import Plane
import Polygon
import Receiver
import numpy as np
class Space(object):
def __init__(self):
self.polygons = []
self.__axes = np.zeros((3, 3))
def vertical_plane(self, origin, facing_angle): # compass direction, degrees
angle = (90 - facing_angl... |
from ctrls.error import ErrorCtrl
from ctrls.admin.index import Admin_IndexCtrl
from ctrls.login import LoginCtrl
from ctrls.admin.leave import LeaveCtrl
from ctrls.index.index import Index_IndexCtrl
from ctrls.admin.adminLeftMenu import Admin_AlogLoginCtrl, Admin_SettingCtrl, Admin_SettingCreateCtrl, \
Admin_Setti... |
"""
try to do ref-directed assembly for paired reads in a region of a .bam file
"""
import pysam,argparse,subprocess,sys,shutil,os,re
import bamsurgeon.parseamos as parseamos
import datetime
from uuid import uuid4
import logging
FORMAT = '%(levelname)s %(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
logger ... |
from application import app, db, parse_date, parse_command
from pytest import fixture
import datetime
import json
TODAY = datetime.date.today()
TOMORROW = datetime.date.today() + datetime.timedelta(days=1)
@fixture(scope='function')
def client(request):
app.config['DEBUG'] = True
app.config['TESTING'] = True
... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
q = 2**255 - 19
def expmod(b,e,m):
if e == 0: return 1
t = expmod(b,e/2,m)**2 % m
if e & 1: t = (t*b) % m
return t
def inv(x):
return expmod(x,q-2,q)
def radix255(x):
x = x % q
if x + x > q: x -= ... |
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
x... |
ti_simulate_battle = -5.0 # DEPRECATED
ti_on_party_encounter = -6.0 # DEPRECATED
ti_question_answered = -8.0 # Player selected an option in (question_box, ...) dialog. Commonly used in module_mission_templates, but should be usable on the global map as well.
# trigger param #1 = playe... |
import sys
from experiment import *
if len(sys.argv) != 3:
print("ERROR: You need to pass in two arguments.")
print("raw_data_processing.py play <path to recording.config of recording to view>")
print("Eg: raw_data_processing.py play .\\..\\..\\TrainingData\\Raw\\Am1\\recording.config\n")
print("raw_data_processing... |
"""
This is just a giant file full of commands we'll type into a python shell.
You probably don't want to import this or run this directly.
"""
from PIL import Image
im = Image.open('img/cake.jpg')
im.show()
print(im.format)
print(im.size)
print(im.mode)
size = (100, 100) # width, height
im.thumbnail(size)
im.save("th... |
from nodes import Node
class DivMod(Node):
char = ".D"
args = 2
results = 2
@Node.test_func([5,4], [1,1])
@Node.test_func([20,7], [2,6])
def func(self, a:int,b:int):
"""Returns a//b and a%b."""
return list(divmod(a,b)) |
"""
Copyright (c) 2015 by Sanhe Hu
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Author: Sanhe Hu
- Email: husanhe@gmail.com
- Lisence: MIT
Module description
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A Python code, comment, docstr line analysis ... |
from __future__ import print_function, division
from os.path import join, dirname, realpath
import pandas as pd
import numpy as np
from scipy.optimize import minimize
from kaggle.file import ProgressDictReader
import xgboost as xgb
import progressbar
from kaggle import KaggleCompetition
class RainCompetition(KaggleComp... |
"""Unit tests for data types."""
from libcloudvagrant.compute.types import (
VagrantAddress,
VagrantImage,
VagrantNetwork,
VagrantNode,
VagrantNodeSize,
VagrantVolume,
)
__all__ = [
"test_serializable",
"test_serializable_with_driver",
]
def test_serializable():
"""Serializable types... |
import pytest
import electrumx.lib.tx_dash as lib_tx_dash
bfh = bytes.fromhex
V2_TX = (
'020000000192809f0b234cb850d71d020e678e93f074648ed0df5affd0c46d3bcb177f'
'9ccf020000008b483045022100c5403bcf86c3ae7b8fd4ca0d1e4df6729cc1af05ff95'
'd9726b43a64b41dd5d9902207fab615f41871885aa3062fc7d8f8d9d3dcbc2e4867c5d'
... |
"""
Built-in notification-related types and instances.
"""
from . import callbacks, composites, emails, files, logs, mutexes, null, sql
__author__ = 'Aaron Hosford' |
from flask import Flask, render_template, request
from flask.ext.assets import Environment, Bundle
from config import config
import json
app = Flask(__name__)
data = {}
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index_2016.html')
@app.route('/2015', methods=['GET', 'POST'])
def in... |
import scrapy
from AverageBidPoints.items import ABPItem
class CORSSpider(scrapy.Spider):
name = "cors1314"
allowed_domains = ["nus.edu.sg/cors"]
start_urls = [
"http://www.nus.edu.sg/cors/Archive/201314_Sem2/avgbidinfo_3B_1808_20132014s2.html",
"http://www.nus.edu.sg/cors/Archive/201314_Sem... |
import pytest
import meshio
from . import helpers
@pytest.mark.parametrize(
"mesh",
[
# helpers.empty_mesh,
helpers.tri_mesh
],
)
def test_io(mesh, tmp_path):
helpers.write_read(tmp_path, meshio.off.write, meshio.off.read, mesh, 1.0e-15)
def test_generic_io(tmp_path):
helpers.generic... |
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
if len(num) < 3:
return None
res=[]
num.sort()
n=len(num)
for i in range(0,n-4):
start=i+1
end=n-1
while start < end:
print i,num[i],num[start],num[end]
if num[i]+num[start]+num[end] == 0:
... |
'''
Problem 32
06 December 2002
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example,
the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multiplicand, multiplier,
and product is 1... |
import logging
import requests
from sources.util import geocode
from sources.fts.util import engine, fts_entry
log = logging.getLogger(__name__)
KEYS = ['country', 'address', 'city', 'postcode']
def transform():
log.info("Geo-coding FTS recipients...")
for row in list(fts_entry.distinct(*KEYS)):
#print ... |
from django.contrib.sitemaps import Sitemap
from .models import KnowallCategory, Knowall
from django.core.urlresolvers import reverse
import time
import arrow
class KnowallSitemap(Sitemap):
changefreq = "weekly"
priority = 0.5
def items(self):
return ['knowall:index']
def location(self, obj):
... |
import os
import logging
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
FB_API_VERSION = 2.6
FB_ACCESS_TOKEN = 'this-is-in-local-config'
FB_VERIFY_TOKEN = 'this-is-in-local-config'
FB_WEBHOOK_URL = 'this-is-in-loca... |
import base64
hexString = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206'
'120706f69736f6e6f7573206d757368726f6f6d')
theBytes = bytes.fromhex(hexString)
conversion = (b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11'
b'c2hyb29t')
b64 = base64.b64encode(theBytes)
print(b... |
class App():
def __init__(self):
self.config = Config()
def run(self, runner):
runner(self.config)
class Config(dict):
def from_object(self, obj):
if isinstance(obj, str):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
... |
"""Provide functionality to keep track of devices."""
from __future__ import annotations
from homeassistant.const import ATTR_GPS_ACCURACY, STATE_HOME # noqa: F401
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
from .config_en... |
import os.path
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, GObject, Gtk, GdkX11, Gst, GstVideo
GObject.threads_init()
Gst.init(None)
class VideoController(GObject.GObject):
__gsignals__ = {
'playback-changed': ( GObject.SIGNAL_RUN_FIRST, None,
(type(Gst.Sta... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..')) # (needed this for functions.rst)
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon'
]
napolon_use_rtype = False
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'synkhronos'
copyright = '2017, Adam S... |
import random
mainValue = int( random.randrange( 10, 100, 1 ) )
userGuess = 1
guessAnswer = False
if userGuess and mainValue:
guessAnswer = True
while guessAnswer is True:
userGuess = input( 'Guess number from 10 to 99\n' )
if int( userGuess ) == mainValue:
guessAnswer = True
print( 'Congrat... |
import heap as h
class priorityqueue(h.min_heap):
def __init__(self):
super(priorityqueue, self).__init__()
self.items = {}
def insert(self, priority, val):
if priority in self.items:
self.items[priority].append(val)
else:
self.items[priority] = [val]
... |
"""
Holiday class implementation for Holiday by Moorescloud
Homepage and documentation: http://dev.moorescloud.com/
Copyright (c) 2013, Mark Pesce.
License: MIT (see LICENSE for details)
"""
__author__ = 'Mark Pesce'
__version__ = '0.01-dev'
__license__ = 'MIT'
import sys, json
try:
import requests
except ImportError:... |
POP_SIZE = 17 #pop size
NGEN = 1000000000 #generations to run
MUTATION = [0, 1, 2, 3] #randomly select one value from this list to determine the number of mutations an indiv. pass on to next gen.
ELITE = 3 #number best individuals to save at each generation
NCPUs = 16 #number of cpus to run on. Remember that after ... |
"""Random rotation matrix generators."""
import numpy as np
def generate(dim):
"""Generate a random rotation matrix.
Args:
dim (int): The dimension of the matrix.
Returns:
np.matrix: A rotation matrix.
Raises:
ValueError: If `dim` is not 2 or 3.
"""
if dim == 2:
r... |
class node(mathObject):
def __init__(self, attr, vals, param, paranets, parentsParam, child, childParam):
pass
def setProvence(self, val):
pass |
from mrjob.job import MRJob
class MRMatrixXY(MRJob):
def mapper(self, _, line):
v = line.split(',')
# product of y*xi
for i in range(len(v)-2):
yield i, float(v[1])*float(v[i+2])
# To calculate Intercept
yield i+1, float(v[1])
# Sum up the products
def red... |
from logger import Logger
class Worker(Logger):
def __init__(self, conn, *args, **kargs):
super(self.__class__, self).__init__(self.__class__.__name__)
self.conn = conn
self.kargs = kargs
def build_query(self, query):
return query.format(**self.kargs)
def __query(self, query)... |
"""Author: Dom Modica
Purpose: To solve the problem described @ http://www.reddit.com/r/dailyprogrammer/comments/2ovt2i/20141210_challenge_192_intermediate_markov_chain/
Essentially the purpose is to read in a large dictionary file of words, and analyze the frequencies of how letters follow each other.
For example in t... |
from django.apps import AppConfig
class AppConf(AppConfig):
name='acads'
verbose_name="Academics" |
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
(r'^beta/$', 'djangit.views.beta'),
(r'^beta/... |
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.forms import ModelForm
from django.forms.extras.widgets import SelectDateWidget
from jizhang.models import Item, Category
from jizhang.data_format_func import sort_category
class Item... |
import tarfile, zipfile, re, requests
from StringIO import StringIO
class PyPiDeps(object):
#using methods from: https://github.com/ogirardot/meta-deps/blob/master/PyPi%20Metadata.ipynb
def __init__(self, package_name):
self.package_name = package_name
def _get_requires(self, content):
resul... |
from runner.koan import *
class AboutMultipleInheritance(Koan):
class Nameable:
def __init__(self):
self._name = None
def set_name(self, new_name):
self._name = new_name
def here(self):
return "In Nameable class"
class Animal:
def legs(self):
... |
from pact_test.either import *
from pact_test.matchers.matcher import *
def match(interaction, pact_response):
return _match_status(interaction, pact_response)\
.concat(_match_headers, pact_response)\
.concat(_match_body, pact_response)
def _match_status(interaction, pact_response):
expected = i... |
import os
import time
from pyftpdlib.filesystems import FilesystemError
from pyftpdlib._compat import PY3, u, unicode
_months_map = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul',
8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
from pyftpdlib.filesystems import AbstractedFS
import oss_fs_... |
import numpy as np
def output_welcome():
"""print welcome information"""
order = """
,-----. ,--.
' .-. ',--.--. ,-| | ,---. ,--.--.
| | | || .--'' .-. || .-. :| .--'
' '-' '| | \ `-' |\ --.| |
`-----' `--' ... |
import configparser
import errno
import fnmatch
import itertools
import json
import logging
import os
import random
import re
import shutil
import string
import sys
import time
from contextlib import contextmanager
from subprocess import (
DEVNULL,
PIPE,
CalledProcessError,
Popen,
call,
check_ca... |
"""
WSGI config for django_class 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI... |
"""Tests for the generation of multipart/form-data request bodies."""
from collections import OrderedDict
from io import BytesIO
from pathlib import Path
import pytest
from anyio import open_file
from asks.multipart import MultipartData, build_multipart_body
pytestmark = pytest.mark.anyio
@pytest.fixture(scope="session... |
from django.db import IntegrityError
from .items import MegabetMatchOddsItem
import django
django.setup()
class MegabetScraperPipeline(object):
def process_item(self, item, spider):
try:
item.save()
except IntegrityError:
item = MegabetMatchOddsItem.django_model.objects.filte... |
from django.conf.urls import patterns, url
from test_app.views import FrontpageView
urlpatterns = patterns(
'test_app.views',
url(r'^$', FrontpageView.as_view(), name='frontpage'),
) |
"""Convert positive binary integers to decimal"""
import re
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def bin2dec(x):
"""Convert a positive binary integer to decimal
:param x: Positive binary integer
:return: Decimal number
"""
if re.match("^[0-1]+$", str(x)):
# <x> is a valid binary... |
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
address_list = []
self.dfs(0, 0, s, address_list)
return address_list
def dfs(self, level, begin, s, address_list):
if level >= 4 and begin >= len(s):
... |
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['inv', 'svd', 'det', 'slogdet', 'pinv', 'lstsq', 'norm']
import numpy as np
import scipy.sparse as sp
from .ch import Ch, depends_on
from .ch_ops import NanDivide
from .ch_ops import asarray as ch_asarray
from .ch_ops imp... |
import struct
import bpy
import Blender
def newFileName(ext):
return '.'.join(Blender.Get('filename').split('.')[:-1] + [ext])
def saveAllMeshes(filename):
for object in Blender.Object.Get():
if object.getType() == 'Mesh':
mesh = object.getData()
if (len(mesh.verts) > 0):
... |
import math
from ds.vortex.core import baseNode
from ds.vortex.core import plug as plugs
class SquareRootNode(baseNode.BaseNode):
def __init__(self, name):
"""
:param name: str, the name of the node
"""
baseNode.BaseNode.__init__(self, name)
def initialize(self):
baseNode... |
import os
import random
import letters
class Field(object):
'''
The Field is the data structure that will hold all tiles
currently on-screen, as well as the tile currently falling.
It is a list of lists, where for any <self.cells[i][j]>, i represents
the row and j represents the column.
'''
... |
import pyglet
import cocos
from cocos.layer import Layer,ColorLayer
from RulersLayer import RulersLayer
kCCBBorderDevice = 0
kCCBBorderTransparent = 1
kCCBBorderOpaque = 2
kCCBBorderNone = 3
kCCBAlignHorizontalCenter = 0
kCCBAlignVerticalCenter = 1
kCCBAlignLeft = 2
kCCBAlignRight = 3
class CocosScene(Layer):
def _... |
from django.shortcuts import HttpResponse
def index(request):
return HttpResponse("Hello world.") |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('papers', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='article',
name='authors',
field=models.... |
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
def convert_pdf_to_txt(path):
from pdfminer.converter import TextConverter
rsrcmgr = PDFResourceManager()
retstr = StringIO()
cod... |
from __future__ import division
import os
import tempfile
import unittest
import pyvips
IMAGES = os.path.join(os.path.dirname(__file__), 'images')
JPEG_FILE = os.path.join(IMAGES, "йцук.jpg")
SRGB_FILE = os.path.join(IMAGES, "sRGB.icm")
TEST_IMAGES = os.path.join(os.path.dirname(__file__),
'.... |
"""
Django settings for django_react project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BAS... |
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.... |
import logging
from .observer import Observer
import config
import smtplib
def send_email(subject, message):
_to = config.smtp_to
_from = config.smtp_from
mime_message = """From: Python Arbitrage Script <%(_from)s>
To: <%(_to)s>
Subject: %(subject)s
%(message)s
""" % locals()
try:
smtpObj = smtp... |
from chips.api.api import Component
def application(chip):
c = Component("application.c")
c(
chip = chip,
inputs = {
},
outputs = {
"rs232_tx": chip.outputs["output_rs232_tx"],
}
) |
import serial
import time
from sys import argv
import logging
direction_map = {'N': 0, 'E': 2, 'W': 3, 'S': 1}
class Create(object):
"""A class to manage the connection to and commands for a Create robot."""
# Opcodes
START = (128).to_bytes(1, byteorder='big')
FULL_MODE = (132).to_bytes(... |
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['--strict', '--verbose', '--tb=long']
self.test_suite = True
def run_tests(self):
... |
def longestCommonSubstring(self, A, B):
if A == None or B == None:
return 0
len_A = len(A)
len_B = len(B)
f = [[0] * (len_B+1) for row in xrange(len_A+1)]
max_ = 0
for i in xrange(len_A + 1):
for j in xrange(len_B + 1):
if i == 0 or j == 0:
f[i][j] = 0
else:
if A[i-1] == B[j-1]:
f[i][j] = f... |
from __future__ import print_function
import re
import string
import sys
import os
import argparse
class BasicAwk(object):
def __init__(self, files, FS=None, OFS=None,
RS=None, ORS=None):
self.FS = FS
if OFS is None:
self.OFS = ' '
else:
self.OFS = OFS
... |
'''
MLP network for MNIST digits classification with L2 reg
Test accuracy: 95.2%
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.datasets import m... |
import numpy as np
from sympy import Rational as frac
from sympy import sqrt
from ..helpers import article
from ._helpers import T2Scheme, register
source = article(
authors=["P. Hillion"],
title="Numerical Integration on a Triangle",
journal="International Journal for Numerical Methods in Engineering",
... |
import runabove
import unittest
import mock
import json
class TestSshKey(unittest.TestCase):
answer_list = '''[
{
"publicKey": "ssh-rsa very-strong-key1 key-comment",
"name": "TestKey1",
"fingerPrint": "aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:aa:a1",
"region... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.