code stringlengths 1 199k |
|---|
from utils import *
def rasterize_line_2(x0, y0, xn, yn):
inc_x = 1
inc_y = 1
dx = abs(xn - x0)
dy = abs(yn - y0)
reverse = False
if xn < x0:
inc_x = -1
if yn < y0:
inc_y = -1
if dx < dy:
reverse = True
i = dx
dx = dy
dy = i
inc_up = 2*... |
"""
Author: Mohammed Fahad Kaleem
"""
class BinaryTreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def setData(self,data):
self.data = data
def getData(self):
return self.data
def getLeft(self):
return self.left
de... |
"""DOES NOT WORK"""
from Queue import PriorityQueue
def dijkstra(weighted_graph, start, end):
dict_node_totalweight = {}
dict_node_totalweight[start] = 0
prev = []
pq = PriorityQueue()
for node in weighted_graph.nodes():
if node is not start:
dict_node_totalweight[node] = float("... |
"""
flask_via.examples.blueprints.app
=================================
A blueprint ``Flask-Via`` example Flask application.
"""
from flask import Flask
from flask.ext.via import Via
app = Flask(__name__)
app.config['VIA_ROUTES_MODULE'] = 'flask_via.examples.blueprints.routes'
via = Via()
via.init_app(app)
if __name__ ... |
import httplib, sys, time, hmac, json
CLIENT_ID = "test-client"
CLIENT_SECRET = "test-client"
def get_secret(timestamp):
h = hmac.new(CLIENT_SECRET)
h.update(timestamp)
return h.hexdigest()
def main(host="localhost", port="7000"):
port = int(port)
conn = httplib.HTTPConnection(host, port)
ti... |
from pipes.pipe import Pipe
import numpy as np
class BlackAndWhitePlusSlicing(Pipe):
def pipe(self, data):
BlackAndWhitePlusSlicing = data
BlackAndWhitePlusSlicing1 = BlackAndWhitePlusSlicing[200:400, :, 1:2]
BlackAndWhitePlusSlicing2 = BlackAndWhitePlusSlicing[500:700, :, 1:2]
Black... |
import os
import numpy as np
from setuptools import setup, find_packages, Extension
PACKAGE_PATH = os.path.abspath(os.path.join(__file__, os.pardir))
lpnorm_extension = Extension('lpnorm._lpnorm',
sources=['lpnorm/lpnorm.c'],
extra_compile_args=['-O3', '-march=native', '-fopenmp', '-std=c99'],
e... |
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import redirect, render, get_object_or_404
from django.urls import reverse
from django.views.generic import View
from account.decorators import login_required
from .hooks import hookset
from .proxies import ActivityState
f... |
tagExchange_Type = "enum" |
from galaxy import datatypes
def exec_after_process(app, inp_data, out_data, param_dict, tool, stdout, stderr):
for name, data in out_data.items():
if data.ext == "bed":
data = datatypes.change_datatype(data, "interval")
data.flush() |
import struct
from Crypto.Cipher import AES
def run_ctr(data, key):
return xor(data, AES_CTR_keystream(key))
def xor(x, y):
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(x, y))
def AES_ECB_encrypt(string, key):
cipher = AES.new(key, AES.MODE_ECB)
return cipher.encrypt(string)
def AES_CTR_keystream... |
"""Another useless util. This one to demo coverage."""
def add_stuffs2(arg1, arg2):
"""Return two args added together."""
return arg1 + arg2 |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "noball.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
1 game
level
ball (multi ?)
2 players (or more ? 4)
For the moment, basic version
"""
import pygame, sys
from pygame.locals import *
from elements import *
from gui import *
pygame.init()
fps_clock = pygame.time.Clock()
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
window_surface_obj = pygame.display.set_m... |
import time
import logging
from binascii import hexlify
from collections import deque
from weakref import WeakValueDictionary
from . import command
from .packet import int32
pdu_log = logging.getLogger('smpipi.pdu')
class BrokenLink(Exception):
pass
class Proto(object):
def __init__(self, logger=None):
... |
"""Script for testing the performance of pickling/unpickling.
This will pickle/unpickle several real world-representative objects a few
thousand times. The methodology below was chosen for was chosen to be similar
to real-world scenarios which operate on single objects at a time. Note that if
we did something like
... |
from PIL import Image
from pylab import *
import os
pil_im = Image.open('lena.jpg')
pil_dst = pil_im.convert('L')
im = array(pil_dst)
imshow(im)
figure()
hist(im.flatten(),128)
print('Please Click 3 pts')
x = ginput(3)
print('You Click :', x)
title('Draw : "lena.jpg"')
show() |
import tornado.concurrent
def future_returning(result):
future = tornado.concurrent.Future()
future.set_result(result)
return future
def future_raising(exception):
future = tornado.concurrent.Future()
future.set_exception(exception)
return future |
from test_framework.mininode import *
from test_framework.test_framework import DashTestFramework
from test_framework.util import *
from time import *
'''
InstantSendTest -- test InstantSend functionality (prevent doublespend for unconfirmed transactions)
'''
class InstantSendTest(DashTestFramework):
def __init__(s... |
from pwn import *
import os, signal
context.log_level = 1000
with tempfile.NamedTemporaryFile() as fd:
s = randoms(12)+"\n"
fd.write(s)
fd.flush()
try:
p = process(["python", "doit.py", "FLAG=%s"%fd.name])
#p.sendline(fd.name)
flagenc = p.recvline(timeout=5).strip()
if fl... |
import pandas as pd
import numpy as np
problem = 'porto'
if problem == 'porto':
fid_sol = 'sol_porto_0_10.csv'
fid_btw = '../mathematica/rank_porto_edge_betweenness_centrality.csv'
fid_eid = '../instances/porto_edges_algbformat.txt'
fid_nid = '../instances/porto_nodes_algbformat.txt'
def distance(x_lon,... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cc', '0007_numericexpressionresponse_assignment_id'),
]
operations = [
migrations.AddField(
model_name='numericexpressionresponse',
... |
import os
import socket
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ON_PAAS = 'OPENSHIFT_REPO_DIR' in os.environ
if ON_PAAS:
SECRET_KEY = os.environ['OPENSHIFT_SECRET_TOKEN']
else:
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')_7av^!cy(wfx=k#3*7x+(=j^fzv+ot^1@sh... |
import io
import os
from twisted.trial import unittest
import mock
from ..cli import cmd_ssh
OTHERS = ["config", "config~", "known_hosts", "known_hosts~"]
class FindPubkey(unittest.TestCase):
def test_find_one(self):
files = OTHERS + ["id_rsa.pub", "id_rsa"]
pubkey_data = u"ssh-rsa AAAAkeystuff emai... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Offer.button_text'
db.alter_column(u'offer_offer', 'button_text', self.gf('django.... |
'''
A list of helper functions useful throughout the compiler
'''
from reservedwords import RESTRICTED
def checkIfVariable(var):
return (var[0]>='a' and var[0]<='z' or var[0]>='A' and var[0]<='Z') and (not var in RESTRICTED)
def mapRemoveLast(subTree, index):
if (len(subTree) == 0):
return subTree
ret... |
"""Texture analysis.
Texture methods are of three possible types: 'map' produces a texture map by
using a sliding window, 'mbb' uses selected voxels to produce a single value
for each slice, and 'all' produces a single value for selected voxels from all
slices.
Output type can be one of the following: 'map' just return... |
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
IMAGE_FILES = []
with mp_pose.Pose(
static_image_mode=True,
model_complexity=2,
min_detection_confidence=0.5) as pose:
for idx, file in enumerate(IMAGE_FILES):
image = cv2.imread(file)
image_heigh... |
import time
from functools32 import lru_cache
@lru_cache()
def fib(n):
x, y = 0, 1
for _ in xrange(n):
x, y = x + y, x
return x
def fib2(n):
x, y = 0, 1
for _ in xrange(n):
x, y = x + y, x
return x
start = time.time()
print fib(16)
print 'cache time: ', time.time() - start
prin... |
class Calculator:
def __init__(self, ina, inb):
self.a = ina
self.b = inb
def add(self):
return self.a + self.b
def mul(self):
return self.a*self.b
class Scientific(Calculator):
def power(self):
return pow(self.a,self.b)
first_num = int(raw_input('Write a first number: '))
second_num = int(raw_input('Writ... |
import unittest
import sys
sys.path.insert(0,'../')
import ftp_chunker
class TestFtpChunkder(unittest.TestCase):
def test_get_paths_returns_generator(self):
my_generator = ftp_chunker.get_paths(1901)
next(my_generator)
self.assertTrue(isinstance(next(my_generator)['size'], int))
def test... |
from django.contrib import admin
from polls.models import Poll
admin.site.register(Poll) |
class Window:
def __init__(self, width, height):
self.width = width
self.height = height
self.dimensions = (width, height)
def center(self):
return [self.width / 2, self.height / 2] |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
'''
Created on 13 Sep 2016
@author: sennikta
'''
import numpy as np
from scipy.stats import norm, mstats
import os
from os import listdir
import math
base_dir = os.path.dirname(os.path.dirname(__file__))
data_dir = os.path.join(base_dir, 'data')
seed_dir = os.path.join(data_dir, 'seed')
baseline_dir = os.path.join(data... |
import os
for f in os.listdir("geojson"):
filename = "geojson/" + f
out = "geojson/simple/" + f
cmd = "mapshaper " + filename + " -simplify 40% -o format=geojson " + out
os.system(cmd) |
import os
import glob
try:
input = raw_input
except NameError: pass
print("")
print("")
print("What would you like to call your new analyzer?")
print("")
print(">>The files under '/source' will be modified to use it.")
print(">>Examples include Serial, MySerial, JoesSerial, Gamecube, Wiimote, 2Wire, etc.")
print(">... |
"""Test the parsing of arguments gives the correct results."""
import pytest
from statdyn.sdrun.main import create_parser
parser = create_parser()
FUNCS = [
('prod', ['infile']),
('equil', ['infile', 'outfile']),
('create', ['outfile']),
('figure', []),
('comp_dynamics', ['infile']),
]
@pytest.mark.... |
"""This file contains the descriptions and settings for all modules. Also it contains functions to add modules and so on"""
try:
import json
except ImportError:
import simplejson as json
from flask import jsonify, render_template, request
from maraschino.database import db_session
import maraschino
import copy
... |
import re
import json
nameFile = open('lastNameInput.txt', 'r')
lastNameFile = open('lastNames.txt', 'w')
lastNameList = []
for line in nameFile:
result = re.search('<b> ([a-zA-Z]+) <\/b>', line)
if result != None:
lastNameList.append(result.group(1))
lastNameFile.write(json.dumps(lastNameList))
nameFile.close()
la... |
from django.db import models, transaction
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django.utils.functional import cached_property
from django.db.models import F
from ...core.conf import settings
from ...core.utils import get_query_string
from .managers import (
C... |
'''
Created on 29-Jan-2017
@author: abhay
'''
import sys
import os
from configure_slaves.slave import Slave
from health_check.check_network_connectivity import get_all_slaves_ip_as_a_list
from health_check.generate_key_value_pair import generate_key_value_pair
import paramiko
list_of_slave_objects = []
def create_slave... |
"""Module for handling OVF and OVA virtual machine description files.
**Classes**
.. autosummary::
:nosignatures:
OVF
"""
import logging
import os
import os.path
import re
import tarfile
import xml.etree.ElementTree as ET # noqa: N814
from xml.etree.ElementTree import ParseError
import textwrap
from COT.xml_file... |
'''
On September 11, 2012, Camilla Cavicchi reported to me the finding of
a new fragment in the Ferrara archives. One unknown piece has an extraordinary
large range in the top voice: a 15th within a few notes. The clefs can't
be read and the piece is an adaptation into
Stroke notation, so it's unlikely to have an exa... |
import requests
from bs4 import BeautifulSoup
import time
def is_number(s):
"""
Check and parse entered value as a number
"""
try:
int(s)
return True
except ValueError:
return False
def connect(fname, url_to_scrape):
"""
Connect to the requested url using the get method of ... |
from __future__ import absolute_import
from past.types import long
from builtins import bytes
from serialization import reflect
from serialization import base
UNICODE_ATOM = "unicode"
UNICODE_FORMAT_ATOM = "UTF-8"
BOOL_ATOM = "boolean"
BOOL_TRUE_ATOM = "true"
BOOL_FALSE_ATOM = "false"
NONE_ATOM = "None"
TUPLE_ATOM = "t... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import quandl as Quandl
import wbdata as wb
from scipy import stats
import runProcs
countryCodes = {}
try:
text_file = open('../txt/country_codes', 'r')
lines = text_file.readlines()
for line in lines:
split = line.split('|')
... |
from functools import wraps
from random import shuffle
from flask import Flask, render_template, redirect, url_for, flash, send_from_directory, request
from flask_babel import Babel, gettext
from flask_login import LoginManager, login_required, \
login_user, logout_user, current_user
from flask_mail import Mail
fro... |
from toolchain import CythonRecipe
from os.path import join
class KivyRecipe(CythonRecipe):
version = "1.9.1"
url = "https://github.com/kivy/kivy/archive/{version}.zip"
library = "libkivy.a"
depends = ["python", "sdl2", "sdl2_image", "sdl2_mixer", "sdl2_ttf", "ios",
"pyobjus"]
pbx_fra... |
from flask import Flask
from flask_graphql import GraphQLView
from tests.schema import Schema
def create_app(path="/graphql", **kwargs):
app = Flask(__name__)
app.debug = True
app.add_url_rule(
path, view_func=GraphQLView.as_view("graphql", schema=Schema, **kwargs)
)
return app
if __name__ =... |
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
def isMagic(a,b,c,d,e,f,g,h,i):
return (sorted([a,b,c,d,e,f,g,h,i]) == list(range(1, 10)) and
(a+b+c == d+e+f == g+h+i == a+d+g ==
b+e+h == c+f+i == a+e+i == c+e+g == 15))
coun... |
"""Test that everything gets tied together."""
import flask
import frost.app
import os
def test_create_app():
os.environ.clear()
app = frost.app.create_app()
assert isinstance(app, flask.Flask)
assert app.config['REDIS_URL'] == ''
assert app.config['GITHUB_CLIENT_ID'] == ''
assert app.config['GI... |
from __future__ import absolute_import, division, print_function
import os
import pip
import struct
import ssl
import sys
from six.moves.urllib.request import urlretrieve
def download_numpy_wheel():
base_url = os.getenv('NUMPY_URL')
if base_url is None:
raise ValueError('NUMPY_URL environment variable i... |
import numpy
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
class ResizeImages(function_node.FunctionNode):
def __init__(self, output_shape):
self.out_H = output_shape[0]
self.out_W = output_shape[1]
def check_... |
class DepthSerializerMixin(object):
"""Custom method 'get_serializer_class', set attribute 'depth' based on query parameter in the url"""
def get_serializer_class(self, *args, **kwargs):
serializer_class = super(DepthSerializerMixin, self).get_serializer_class(*args, **kwargs)
query_params = self.request.QUERY_PA... |
from yaweb.app import Application
app = Application()
@app.get('/')
def index():
pass
@app.get('/login')
def login():
pass
@app.post('/login')
def do_login():
pass
@app.post('/logout')
def logout():
pass
@app.get('/avatar')
def avatar():
pass
@app.post('/avatar/upload')
def avatar_upload():
pass... |
from partsdb.partsdb import PartsDB
from tables import *
import os
from partsdb.tools.Exporters import GenBankExporter
if "MARPODB_DB_NAME" in os.environ:
dbName = '/' + os.environ["MARPODB_DB_NAME"]
else:
dbName = "marpodb.io/marpodb3?user=common"
marpodb = PartsDB('postgresql://' + dbName, Base = Base)
session = ma... |
import nengo
import nengo.config
import nengo.params
import pool
import numpy as np
import collections
import nengo.utils.numpy as npext
from nengo.utils.distributions import Distribution, Uniform
BuiltEnsemble = collections.namedtuple(
'BuiltEnsemble', ['eval_points', 'encoders', 'intercepts', 'max_rates',
... |
import datetime as dt
import signal
import socket
import sys
from utils import bytes_len, convert_size, dump_to_csv, row_print
def udp_server_single_node(lim='10MB'):
UDP_IP = '127.0.0.1'
UDP_PORT = 5005
sock = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
sock.bind((UDP_IP, UDP_PORT))
cnt = 0
running_b... |
from .question import Job, Question, Choice, Answer, Report |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Hoverlabel(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatter3d"
_path_str = "scatter3d.hoverlabel"
_valid_props = {
"align",
"al... |
import unittest
from conans.client.run_environment import RunEnvironment
class CppInfo(object):
def __init__(self):
self.bin_paths = []
self.lib_paths = []
class MockDepsCppInfo(dict):
def __init__(self):
self["one"] = CppInfo()
self["two"] = CppInfo()
@property
def deps(... |
import json
import os
from courses import courses
filedir = os.path.dirname(__file__)
heatmaps = {}
for course_id in courses:
filename = os.path.join(filedir, 'heatmaps/%s-heatmap.json' % course_id)
with open(filename) as jsonfile:
heatmaps[course_id] = json.load(jsonfile)
def get_heatmap(course_id, lec... |
import unittest
import os
import sys
if os.environ.get('USELIB') != '1':
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pyleri import (
KeywordError,
create_grammar,
Sequence,
Choice,
Keyword,
) # nopep8
class TestChoice(unittest.TestCase):
def test_choice_most_greed... |
import sys
from .base import Element
class el(Element):
def __init__(self, tag, *children, **attrs):
self.tag = tag
Element.__init__(self, *children, **attrs)
def define_simple_tag(tag_name, self_closing_tag=False):
class new_tag(Element):
tag = tag_name
self_closing = self_closi... |
import random, os, uuid, bcrypt, sys, inspect, setup, configparser
from cassandra.cluster import Cluster
from webtest import TestApp
config = configparser.ConfigParser()
config.read('config.ini')
syskey = config.get('application','syskey')
def test_insert():
res = setup.app().post('/%s/organization' % (syskey,), {'na... |
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("pip install --upgrade " + dist.project_name, shell=True) |
from codecs import open
from os import path
import versioneer
from setuptools import find_packages, setup
cmdclass = versioneer.get_cmdclass()
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='prx',
version=v... |
"""
Forward Simulation on a Cylindrical Mesh
========================================
Here we use the module *SimPEG.electromagnetics.frequency_domain* to simulate the
FDEM response for an airborne survey using a cylindrical mesh and a conductivity
model. We simulate a single line of airborne data at many frequencies f... |
"""A tool for modeling composite beams and aircraft wings.
``Aerodynamics``
This module provides the aerodynamics models used within AeroComBAT
``AircraftParts``
This module provides a full-fledged wing object that can be used to
determine if a design is both statically adequate as well as stable.
``F... |
import sys
sys.path.append('/usr/share/inkscape/extensions') # or another path, as necessary
sys.path.append('/Applications/Inkscape.app/Contents/Resources/extensions')
sys.path.append('C:\Program Files\Inkscape\share\extensions')
from lxml import etree
import inkex
from simplestyle import *
class FigureFirstFigureTagE... |
import requests
import shutil
from PIL import Image
class metadisk_connect:
#~ metadisk_server = 'http://node1.metadisk.org/api/'
#~ download_command = 'download/'
def __init__(self):
self.metadisk_server = 'http://node1.metadisk.org/api/'
self.download_command = 'download/'
self.upload_command = 'upl... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('studies', '0017_auto_20170710_1449'),
('studies', '0014_merge_20170710_1420'),
]
operations = [
] |
import threading
import os
from ...signals import on_exception
from .. import BaseResponder
from markov import Chain
class Markov(BaseResponder):
"""Generates random responses using Markov chains from the files defined in
config. This module will discover the files automatically by name if a
directory conta... |
import numpy as np
import re
import os
NTVPATH=os.getenv('NTVPATH','https://ayanc.github.io/ntviz/')
htpfx='''
<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="$NTVPATHntviz.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.14/d3.min.js"></script></head><body><div id='graph'></div>... |
import argparse
import os
import sys
import csv
import requests
import datetime
AUTH = (os.environ.get("DCC_API_KEY"), os.environ.get("DCC_SECRET_KEY"))
BASE_URL = 'https://www.encodeproject.org/{}/?format=json'
ENCODE4_ATAC_PIPELINES = [
'/pipelines/ENCPL344QWT/',
'/pipelines/ENCPL787FUN/',
]
PREFERRED_DEFAULT... |
import sys
from bcbio.pipeline.config_loader import load_config
if len(sys.argv) < 6:
print """
Usage:
make_RseqQc_gbc.py <sample_name> <bed_file> <mail> <config_file> <path>
sample_name This name: /tophat_out_<sample name>
bed_file
mail eg: jun.wang@scilifelab.se
... |
INTERNALERROR_IOTACTIONSYSTEMERROR = 'InternalError.IotActionSystemError'
INTERNALERROR_IOTDBERROR = 'InternalError.IotDbError'
INTERNALERROR_IOTLOGSYSTEMERROR = 'InternalError.IotLogSystemError'
INTERNALERROR_IOTSHADOWSYSTEMERROR = 'InternalError.IotShadowSystemError'
INTERNALERROR_IOTSYSTEMERROR = 'InternalError.IotS... |
import re
from django import template
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from threadedcomments.models import ThreadedComment, FreeThreadedComment
from thread... |
from threading import Thread
import urllib
import json
import redis
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import re
import pandas as pd
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from TwitterAPI import TwitterAPI, TwitterRestPager, TwitterReque... |
xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml'
music_folder_dir = 'name' |
"""
Peewee integration with pysqlcipher.
Project page: https://github.com/leapcode/pysqlcipher/
**WARNING!!! EXPERIMENTAL!!!**
* Although this extention's code is short, it has not been propery
peer-reviewed yet and may have introduced vulnerabilities.
* The code contains minimum values for `passphrase` length and
... |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
fr... |
from .simhash import unsigned_hash, num_differing_bits, compute, find_all
from six.moves import range as six_range
def shingle(tokens, window=4):
"""A generator for a moving window of the provided tokens."""
if window <= 0:
raise ValueError("Window size must be positive")
# Start with an empty outpu... |
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- getblockchaininfo
- gettxoutsetinfo
- getdifficulty
- getbestblockhash
- getblockhash
- getblockheader
- getchaintxstats
- getnetworkhashps
- verifychain
Tests correspond to code in rpc/blockchain.cpp.
"""
from decim... |
from carepoint import Carepoint
from sqlalchemy import (Column,
String,
Integer,
Boolean,
)
class FdbAllergenRel(Carepoint.BASE):
__tablename__ = 'fdrhicd'
__dbname__ = 'cph'
hic_seqn = Column(
Integer,
... |
"""
.. module:: organization.admin
:synopsis: Django organization application admin module.
Django organization application admin module.
"""
from __future__ import absolute_import
from django.contrib import admin
from django_core_utils.admin import (NamedModelAdmin, admin_site_register,
... |
import requests
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import time
from bills.ingest.setup_database import New_York_Bill
def extractNyBills(dbname='bills_db', username='Joel',
offset=0, year=2015, limit=1000, my_max=50000):
engine = create_engine('postgres://... |
import pytest
from marshmallow_jsonapi import utils
@pytest.mark.parametrize(
"tag,val",
[
("<id>", "id"),
("<author.last_name>", "author.last_name"),
("<comment.author.first_name>", "comment.author.first_name"),
("True", None),
("", None),
],
)
def test_tpl(tag, val)... |
"""
Description
Given a list of n items, each with w_i and dollar value v_i, and a weight
capacity W, what is the most valuable combination of items?
Example:
Input: weights_array; value_array; W
6 3 4 2; 30 14 16 9; 10
Output: item_nums, value
1 3; 46
"""
def stringAsIntArr(str):
elems = str.split(" ")
arr = [... |
"""Abstract class for all result handler tests."""
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from future.builtins import zip
from future.utils import with_metaclass
from django.test.testcases import TransactionTestCase
from rotest.core.suite import TestSuite
from rotest.core.models.... |
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns("",
#url(r'^torneo/agregar$','complejos.views.agregar', name='agregar_torneo'),
#url(r'^torneo/editar/$','complejos.views.editar', name='editar_torneo'),
#url(r'^torneo/editar/(?P<id>\d+)/$','complejo... |
from uwhoisd import caching
from . import utils
class LFU(caching.LFU):
def __init__(self, max_size=256, max_age=300):
self.clock = utils.Clock()
super(LFU, self).__init__(max_size, max_age)
def test_insertion():
cache = LFU()
assert len(cache.cache) == 0
assert len(cache.queue) == 0
... |
from allauth.socialaccount.providers import registry
from allauth.socialaccount.tests import create_oauth2_tests
from allauth.tests import MockedResponse
from .provider import GitHubProvider
class GitHubTests(create_oauth2_tests(registry.by_id(GitHubProvider.id))):
def get_mocked_response(self):
return Mock... |
import glob
from joblib import Parallel, delayed
import os
import click
def cdo_command(ifile, opath, command, ext, skip):
if opath != 'no':
ofile = os.path.join(opath, '{}_{}.nc'.format(os.path.basename(ifile)[:-3], ext))
else:
ofile = ' '
if skip:
if os.path.isfile(ofile):
... |
"""
https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html
8.3.1 Readline Init File Syntax
There are only a few basic constructs allowed in the Readline init file. Blank lines are ignored. Lines beginning with a ‘#’ are comments. Lines beginning with a ‘$’ indicate conditional constructs (see... |
from keras.applications import VGG16
from keras import models
from keras import layers
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
train_dir = '/home/han/code/data/dogsvscats/small/train'
val_dir = '/home/han/code/data/dogsvscats/small/validation... |
"""
This module provides an entrypoint for WSGI servers, accessible by ``application``
or by running this file as a script.
This module is not currently using the :class:`werkzeug.wsgi.DispatcherMiddleware`
as there is not a need for it in this case. There is only one "app",
:module:`{{cookiecutter.repo_name}}.api`, so... |
from __future__ import print_function, division, unicode_literals
from abc import ABCMeta, abstractproperty, abstractmethod
from collections import namedtuple
from distutils.version import LooseVersion
from functools import wraps
from itertools import takewhile, dropwhile
import operator
import re
import sys
try:
f... |
from itertools import izip_longest
class Vector(object):
def __init__(self, nums):
self.nums = nums
def __str__(self):
return '({})'.format(','.join(str(a) for a in self.nums))
def add(self, v2):
return Vector([b + c for b, c in izip_longest(self.nums, v2.nums)])
def dot(self, v2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.