code stringlengths 1 199k |
|---|
from seabreeze.pyseabreeze.features._base import SeaBreezeFeature
class SeaBreezeDataBufferFeature(SeaBreezeFeature):
identifier = "data_buffer"
def clear(self) -> None:
raise NotImplementedError("implement in derived class")
def remove_oldest_spectra(self, number_of_spectra: int) -> None:
r... |
"""
Basic pulsar-related functions and statistics.
"""
import functools
from collections.abc import Iterable
import warnings
from scipy.optimize import minimize, basinhopping
import numpy as np
import matplotlib.pyplot as plt
from .fftfit import fftfit as taylor_fftfit
from ..utils import simon, jit
from . import HAS_P... |
from Crypto import Random
from src.aes import encrypt_message, decrypt_message
def test_integrity():
plaintext = 'Test Text'
key = Random.new().read(16)
# Ensure that D(k, E(k, p)) == p
assert decrypt_message(key, encrypt_message(key, plaintext)) == plaintext
def test_privacy():
plaintext = 'Test Te... |
import shutil
import tempfile
import time
import os
import random
import subprocess
import unittest
from basefs.keys import Key
from basefs.logs import Log
from . import utils
class MountTests(unittest.TestCase):
def setUp(self):
__, self.logpath = tempfile.mkstemp()
__, self.logpath_b = tempfile.mk... |
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import datetime
from Bio.Seq import Seq
if __name__ == '__main__':
from needleman_wunsch import needleman_wunsch
else:
from .needleman_wunsch import needleman_wunsch
def plot_nw(seq_alpha_col,seq_beta_row,p_penalty):
if no... |
import random
def get_random_unicode(length):
try:
get_char = unichr
except NameError:
get_char = chr
# Update this to include code point ranges to be sampled
include_ranges = [
(0x0021, 0x0021),
(0x0023, 0x0026),
(0x0028, 0x007E),
(0x00A1,... |
"""
@author: Alexander David Leech
@date: 03/06/2016
@rev: 1
@lang: Python 2.7
@deps: YAML
@desc: Class to use as an interface to import YAML files
"""
import yaml
class yamlImport():
@staticmethod
def importYAML(pathToFile):
try:
with open(pathToFile, "r") as f:
c... |
"""
Example of module documentation which can be
multiple-lined
"""
from sqlalchemy import Column, Integer, String
from wopmars.Base import Base
class FooBaseH(Base):
"""
Documentation for the class
"""
__tablename__ = "FooBaseH"
id = Column(Integer, primary_key=True, autoincrement=True)
name = ... |
"""
Derivation and Elementary Trees live here.
"""
from __future__ import print_function
from baal.structures import Entry, ConstituencyTree, consts
from baal.semantics import Predicate, Expression
from collections import deque
from copy import copy, deepcopy
from math import floor, ceil
try:
input = raw_input
exce... |
import guess_language
import threading
from job_queue import JobQueue
from multiprocessing import cpu_count
from app_config import *
from html_parser_by_tag import HTMLParserByTag
from event_analysis import EventAnalysis
from events.models import Event, Feature, EventFeature, Weight
from tree_tagger import TreeTagger
f... |
BIT_NODE_ID_LEN = 160
HEX_NODE_ID_LEN = BIT_NODE_ID_LEN // 4
ALPHA = 3
K = 8 # pylint: disable=invalid-name
CACHE_K = 32
RPC_TIMEOUT = 0.1
ITERATIVE_LOOKUP_DELAY = RPC_TIMEOUT / 2
REFRESH_TIMEOUT = 60 * 60 * 1000 # 1 hour
REPLICATE_INTERVAL = REFRESH_TIMEOUT
DATE_EXPIRE_TIMEOUT = 86400 # 24 hours
CHECK_REFRESH_INTERV... |
"""Tests for distutils.archive_util."""
__revision__ = "$Id: test_archive_util.py 86596 2010-11-20 19:04:17Z ezio.melotti $"
import unittest
import os
import tarfile
from os.path import splitdrive
import warnings
from distutils.archive_util import (check_archive_formats, make_tarball,
... |
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=30)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
def _... |
import math
import warnings
from random import shuffle
from unittest import TestCase
from matrixprofile.exceptions import NoSolutionPossible
from tsfresh.examples.driftbif_simulation import velocity
from tsfresh.feature_extraction.feature_calculators import *
from tsfresh.feature_extraction.feature_calculators import (... |
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.utils.safestring import mark_safe
class ProductQuerySet(models.query.QuerySet):
def active(self):
return self.filter(active=True)
class P... |
import ringo_config
cfg = ringo_config.RingoConfig()
import pyximport;pyximport.install(build_dir=cfg.pyximport_build())
import argparse
import random
import numpy as np
import model
from simulation import Simulation, SimParameters, EventType, RearrangementType
def run_L_D_simulation(self, L, D):
# L = duplication ... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
mu = 0
variance1 = 20000**2
variance2 = 2000**2
sigma1 = math.sqrt(variance1)
sigma2 = math.sqrt(variance2)
x = np.linspace(mu - 3*sigma1, mu + 3*sigma1, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma1))
x2 = np.linspace(mu - 3*sig... |
VERSION = (0, 11)
__version__ = '.'.join(map(str, VERSION))
DATE = "2015-02-06" |
import sys
import os
import path_utils
import generic_run
def puaq():
print("Usage: %s input_file.flac" % path_utils.basename_filtered(__file__))
sys.exit(1)
def convert_flac_to_mp3(input_file, output_file, bitrate):
cmd = ["ffmpeg", "-i", input_file, "-ab", bitrate, "-map_metadata", "0", "-id3v2_version", ... |
"""
Flask-Validictory
-------------
Simple integration between Flask and Validictory.
"""
import os
from setuptools import setup
module_path = os.path.join(os.path.dirname(__file__), 'flask_validictory.py')
version_line = [line for line in open(module_path)
if line.startswith('__version_info__')][0]
__v... |
from .base import ApplicationVersion, package_version # noqa |
import json
from src.models import BaseModel
class <%= endpoint %>Model(BaseModel):
_parse_class_name = '<%= table %>'
pass |
from os import path
import github_update_checker
from setuptools import setup, find_packages
file_path = path.abspath(path.dirname(__file__))
with open(path.join(file_path, "README.md"), encoding="UTF-8") as f:
long_description = f.read()
setup(
name="github_update_checker",
version=github_update_checker.__... |
"""Forms to render HTML input & validate request data."""
from wtforms import Form, BooleanField, DateTimeField, PasswordField
from wtforms import TextAreaField, TextField
from wtforms.validators import Length, required
class AppointmentForm(Form):
"""Render HTML input for Appointment model & validate submissions.
... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(3,GPIO.OUT)
state=True
GPIO.output(3,True) |
from collections.abc import Mapping, Iterable
from ctypes import c_int, c_int32, c_double, c_char_p, POINTER
from weakref import WeakValueDictionary
import numpy as np
from numpy.ctypeslib import as_array
from openmc.exceptions import AllocationError, InvalidIDError
from . import _dll
from .core import _FortranObjectWi... |
import collections
import yaml
import netCDF4
import numpy as np
from pyresample import geometry
from pyresample import kd_tree
from pyresample import utils
from pyresample import grid
from satistjenesten.utils import get_area_filepath
class GenericScene(object):
""" Generic Scene object
It is a parent class to... |
"""kuoteng_bot URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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... |
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fields.Bool(location='query')
... |
from __future__ import print_function
import logging
_logger = logging.getLogger('theano.sandbox.cuda.opt')
import copy
import sys
import time
import warnings
import pdb
import numpy
import theano
from theano import scalar as scal
from theano import config, tensor, gof
import theano.ifelse
from six.moves import reduce,... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Komiksowiec'
copyright = '2017, Paweł pid Kozubal'
author = 'Paweł pid Kozubal'
version = '1.0'
release = '1.0'
language = N... |
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
print a + b
print a - b
print a * b |
import logging
import logging.config
import sys
import threading
import os
from amberclient.collision_avoidance.collision_avoidance_proxy import CollisionAvoidanceProxy
from amberclient.common.amber_client import AmberClient
from amberclient.location.location import LocationProxy
from amberclient.roboclaw.roboclaw impo... |
import unittest
import socket
import os
from shapy.framework.netlink.constants import *
from shapy.framework.netlink.message import *
from shapy.framework.netlink.tc import *
from shapy.framework.netlink.htb import *
from shapy.framework.netlink.connection import Connection
from tests import TCTestCase
class TestClass(... |
import setuptools
if __name__ == "__main__":
setuptools.setup(
name="aecg100",
version="1.1.0.18",
author="WHALETEQ Co., LTD",
description="WHALETEQ Co., LTD AECG100 Linux SDK",
url="https://www.whaleteq.com/en/Support/Download/7/Linux%20SDK",
include_package_data=True,
package_data={
... |
import itertools
import sys
from .stuff import word_set
__version__ = "1.1.0"
def find_possible(lst):
"""
Return all possible combinations of letters in lst
@type lst: [str]
@rtype: [str]
"""
returned_list = []
for i in range(0, len(lst) + 1):
for subset in itertools.permutations(lst... |
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations
import djstripe.fields
class Migration(migrations.Migration):
dependencies = [
('djstripe', '0020_auto_20161229_0041'),
]
operations = [
migrations.AlterField(
model_name='subsc... |
class MethodMissing(object):
def __getattr__(self, name):
try:
return self.__getattribute__(name)
except AttributeError:
def method(*args, **kw):
return self.method_missing(name, *args, **kw)
return method
def method_missing(self, name, *args, ... |
import threading
__author__ = "Piotr Gawlowicz"
__copyright__ = "Copyright (c) 2015, Technische Universitat Berlin"
__version__ = "0.1.0"
__email__ = "gawlowicz@tkn.tu-berlin.de"
class Timer(object):
def __init__(self, handler_):
assert callable(handler_)
super().__init__()
self._handler = h... |
import pytest
import responses
from document import Document
from scrapers.knox_tn_agendas_scraper import KnoxCoTNAgendaScraper
from . import common
from . import utils
class TestKnoxAgendaScraper(object):
session = None
page_str = ""
def test_get_docs_from_page(self):
scraper = KnoxCoTNAgendaScrape... |
"""
==========================================
Author: Tyler Brockett
Username: /u/tylerbrockett
Description: Alert Bot (Formerly sales__bot)
Date Created: 11/13/2015
Date Last Edited: 12/20/2016
Version: v2.0
==========================================
"""
import praw
imp... |
"""
spdypy.stream
~~~~~~~~~~~~~
Abstractions for SPDY streams.
"""
import collections
from .frame import (SYNStreamFrame, SYNReplyFrame, RSTStreamFrame,
DataFrame, HeadersFrame, WindowUpdateFrame, FLAG_FIN)
class Stream(object):
"""
A SPDY connection is made up of many streams. Each stream c... |
import urllib2, re
lines = []; last_url = None
for index in range(1, 25):
url = "http://axe-level-4.herokuapp.com/lv4/" if index == 1 \
else "http://axe-level-4.herokuapp.com/lv4/?page=" + str(index)
# The hint is that we shall make our bot look like a real browser.
req = urllib2.Request(url)
req.add_header('Acce... |
from collections import deque
N = int(input())
d = deque()
i = 0
while i < N:
command = input().split()
if command[0] == 'append':
d.append(command[1])
elif command[0] == 'appendleft':
d.appendleft(command[1])
elif command[0] == 'pop':
d.pop()
else:
d.popleft()
i ... |
import pytest
import pwny
target_little_endian = pwny.Target(arch=pwny.Target.Arch.unknown, endian=pwny.Target.Endian.little)
target_big_endian = pwny.Target(arch=pwny.Target.Arch.unknown, endian=pwny.Target.Endian.big)
def test_pack():
assert pwny.pack('I', 0x41424344) == b'DCBA'
def test_pack_format_with_endian()... |
"""optboard URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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-ba... |
def maxSumSub(arr):
maxSums = [0]*len(arr)
for i in range(len(arr)):
Si = arr[i]
maxS = Si
for j in range(0,i):
if (arr[j] < arr[i]):
s = maxSums[j] + arr[i]
if (s > maxS):
maxS = s
maxSums[i] = maxS
return max(m... |
import requests
import httpretty
from nose.tools import nottest
from pyrelic import BaseClient
@nottest # Skip until we can properly simulate timeouts
@httpretty.activate
def test_make_request_timeout():
"""
Remote calls should time out
"""
httpretty.register_uri(httpretty.GET, "www.example.com",
... |
from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.kfalse import ConstantFalse
from tokens.ktrue import ConstantTrue
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""T... |
'''
author : "George Profenza"
url : ("disturb", "disturbmedia.com/blog","My blog, http://tomaterial.blogspot.com")
Export meshes the three.js 3D Engine by mr.doob's et al.
More details on the engine here:
https://github.com/mrdoob/three.js
Currently supports UVs. If the model doesn't display correctly
you might nee... |
"""
This module houses ctypes interfaces for GDAL objects. The following GDAL
objects are supported:
CoordTransform: Used for coordinate transformations from one spatial
reference system to another.
Driver: Wraps an OGR data source driver.
DataSource: Wrapper for the OGR data source object, supports
OGR-suppo... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import assignment2_helper as helper
matplotlib.style.use('ggplot')
scaleFeatures = True
original_df = pd.read_csv ('Datasets/kidney_disease.csv')
new_df = original_df.dropna()
labels = ['red' if i=='ckd' else 'green' for i in new_df.classification]
n... |
import sys, math
from PIL import Image
import facedetect
def Distance(p1,p2):
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
return math.sqrt(dx*dx+dy*dy)
def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.BICUBIC):
if (scale is None) and (center is None):
return im... |
import theano
from theano import shared, tensor
from blocks.bricks import Feedforward, Activation
from blocks.bricks.base import application, lazy
from blocks_extras.initialization import PermutationMatrix
from blocks_extras.utils import check_valid_permutation
from blocks.utils import shared_floatx
class FixedPermutat... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissio... |
from django.contrib import admin
from api.models import (
CrawlUrls,
CrawlLinks,
)
admin.site.register(CrawlUrls)
admin.site.register(CrawlLinks) |
"""
WSGI config for PythonAnywhere test project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces import IProtocolFactory
from... |
import os
import re
import itertools
from functools import reduce
from .version import __version__
sep_regex = re.compile(r'[ \-_~!@#%$^&*\(\)\[\]\{\}/\:;"|,./?`]')
def get_portable_filename(filename):
path, _ = os.path.split(__file__)
filename = os.path.join(path, filename)
return filename
def load_convers... |
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.mapper = QtCore.QSignalMapper(self)
self.toolbar = self.addToolBar('Foo')
self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
for text in 'One ... |
from pydons import MatStruct, FileBrowser, LazyDataset
import netCDF4
import numpy as np
import tempfile
import os
DATADIR = os.path.join(os.path.dirname(__file__), 'data')
def test_netcdf4():
d = MatStruct()
data1 = np.random.rand(np.random.randint(1, 1000))
with tempfile.NamedTemporaryFile(suffix=".nc") a... |
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
import socket
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been... |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azur... |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline impo... |
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>> response = nexmo.send_sms(frm,... |
from ...errors.httpbadrequestexception import HttpBadRequestException
import saklient
class MustBeOfSameZoneException(HttpBadRequestException):
## 不適切な要求です。参照するリソースは同一ゾーンに存在しなければなりません。
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, status, code=None, mes... |
import math
import pandas as pd
import numpy as np
from scipy import misc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('ggplot')
def Plot2D(T, title, x, y):
# This method picks a bunch of random samples (images in your case)
# to plot onto the chart:
fig ... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Agency.alias'
db.add_column('lobbyingph_agency', 'alias',
self.gf('django.db.models.fields.CharFi... |
import random
import math
def estimatePi(error):
itt=1000 #itterations
previousPI=0
while True:
hits=0 # number of hits
for i in range(0,itt):
x=random.uniform(0,1)
y=random.uniform(0,1)
z=x*x+y*y #Pythagorean Theorum
if math.sqrt(z)<=1: #if point(x,y)lies within the triangle
hits=hits+1
curren... |
"""
Load winds on pressure levels and calculate vorticity and divergence
"""
import os, sys
import datetime
import iris
import iris.unit as unit
diag = '30201'
cube_name_u='eastward_wind'
cube_name_v='northward_wind'
pp_file_path='/projects/cascade/pwille/moose_retrievals/'
experiment_ids = ['djznw']
for experiment_id ... |
import time
import asyncio
from aiokafka import AIOKafkaProducer
from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC
class LogStreamer:
def __init__(self,
KAFKA_SERVERS,
KAFKA_TOPIC,
loop,
savepoint_file,
log_file)... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('users', '0013_auto_20161002_0504'),
... |
import copy
from cStringIO import StringIO
from fnmatch import fnmatch
import gzip
import hashlib
import mimetypes
import os
import boto
from boto.s3.key import Key
from boto.s3.connection import OrdinaryCallingFormat
import app_config
GZIP_FILE_TYPES = ['.html', '.js', '.json', '.css', '.xml']
class FakeTime:
def ... |
"""Imports for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python.keras import Input
from tensorflow.python.keras import Model
from tensorflow.python.keras import Sequential
from tensorflow.tools.api.generator.api... |
from test_framework.test_framework import AuroracoinTestFramework
from test_framework.util import assert_equal
class ListSinceBlockTest (AuroracoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def run_test (self):
'''
... |
def nextPalindrome(S):
def isPalindrome(x): return x == x[::-1]
while True:
S = S + 1
if isPalindrome(S): return S
def isRotation(A,B):
return B in A+A
def wS(s,i):
if i == len(s):
print "".join(s)
else:
if s[i] == "*":
s[i] = "1"
wS(s,i+1)
s[i] = "0"
wS(s,i+1)
else:
wS(s,i+1)
def allNonRe... |
import numpy as np;
np.set_printoptions(linewidth=40, precision=5, suppress=True)
import pandas as pd; pd.options.display.max_rows=80;pd.options.display.expand_frame_repr=False;pd.options.display.max_columns=20
import pylab as plt;
import os; home=os.path.expanduser('~') +'/'
import sys;sys.path.insert(1,'/... |
class Duck:
"""
this class implies a new way to express polymorphism using duck typing.
This class has 2 functions: quack() and fly() consisting no parameter.
"""
def quack(self):
print("Quack, quack!");
def fly(self):
print("Flap, Flap!");
class Person:
def quack(self):
... |
"""
This module defines serializers for the main API data objects:
.. autosummary::
:nosignatures:
DimensionSerializer
FilterSerializer
MessageSerializer
QuestionSerializer
"""
from django.core.paginator import Paginator
from rest_framework import serializers, pagination
import emoticonvis.apps.corp... |
cookie = '' |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class TestHuberLoss(unittest.TestCase):
def setUp(self):
self.shape = (4, 1... |
'''
compile_test.py - check pyximport functionality with pysam
==========================================================
test script for checking if compilation against
pysam and tabix works.
'''
import os
import unittest
import pysam
from TestUtils import make_data_files, BAM_DATADIR, TABIX_DATADIR
def setUpModule():... |
from pylab import *
import matplotlib.cm as cmx
import matplotlib.colors as colors
def MakeColourMap(N, colormap='jet'):
'''
To make colour map with N possible colours. Interpolated from map 'colormap'
'''
### Colour map for cells (if you want to plot multiple cells)
values = range(N)
jet = cm = plt.get_cmap(colo... |
from django.http import HttpResponse
import service.api
def api_available(request):
return HttpResponse(service.api.get_proxy())
def hello(request):
return HttpResponse("Hello world!") |
import os, time, subprocess, re
def Say(text, verbosity=0, end='\n', suppressTime=False):
if verbosity<=VERBOSITY:
if suppressTime:
timeStr = ''
else:
timeStr = time.strftime('%H:%M:%S ')
if verbosity == 0:
print(timeStr + text, end=end)
else:
... |
import unittest
from db.migrations import migrations_util
class TestMigrationUtil(unittest.TestCase):
"""Test the CLI API."""
@classmethod
def setUpClass(cls):
cls.db_path = '/some/random/path/file.db'
def setUp(self):
self.parser = migrations_util.make_argument_parser(self.db_path)
... |
import asyncio
import json
import uuid
import pytest
from photonpump import exceptions as exn
from photonpump import messages as msg
from photonpump import messages_pb2 as proto
from photonpump.conversations import CatchupSubscription
from ..fakes import TeeQueue
async def anext(it, count=1):
if count == 1:
... |
import numpy as np
from elephas.mllib.adapter import *
from pyspark.mllib.linalg import Matrices, Vectors
def test_to_matrix():
x = np.ones((4, 2))
mat = to_matrix(x)
assert mat.numRows == 4
assert mat.numCols == 2
def test_from_matrix():
mat = Matrices.dense(1, 2, [13, 37])
x = from_matrix(mat)... |
import zipfile
import re
import os
import hashlib
import json
import logging
from django.shortcuts import render
from django.db.models import Q, Count
from django.core.paginator import Paginator
from rest_framework.views import APIView
from django.conf import settings
from account.models import SUPER_ADMIN
from account... |
from scrapy.commands.crawl import Command
from scrapy.exceptions import UsageError
class CustomCrawlCommand(Command):
def run(self, args, opts):
if len(args) < 1:
raise UsageError()
elif len(args) > 1:
raise UsageError("running 'scrapy crawl' with more than one spider is no l... |
class SomeClass: # [blank-line-after-class-required]
def __init__(self):
pass |
"""Print all records in the pickle for the specified test"""
import sys
import argparse
from autocms.core import (load_configuration, load_records)
def main():
"""Print all records corresponding to test given as an argument"""
parser = argparse.ArgumentParser(description='Submit one or more jobs.')
parser.a... |
import numpy as np
import pandas as pd
"""
Specifications (So far, only implemented for the single index part below):
feature_df ... Data Frame of intervals along the genome,
equivalent of a bed file, but 1-indexed
index:
(chrom, start)
columns
required:
end
optional:
name
... |
import sys
import os
import Image
def simpleQuant():
im = Image.open('bubbles.jpg')
w,h = im.size
for row in range(h):
for col in range(w):
r,g,b = im.getpixel((col,row))
r = r // 36 * 36
g = g // 42 * 42
b = b // 42 * 42
im.putpixel((col,r... |
import os
import sys
import time
import subprocess
import datetime
import platform
from win10toast import ToastNotifier
import exception
class Notify(object):
def __init__(self):
self.title = 'Alert From Alertify'
self.platform = platform.system()
self.toaster = ToastNotifier()
def count... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Post'
db.create_table(u'blog_post', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True... |
"""
Q2(c): Recurrent neural nets for NER
"""
from __future__ import absolute_import
from __future__ import division
import argparse
import logging
import sys
import tensorflow as tf
import numpy as np
logger = logging.getLogger("hw3.q2.1")
logger.setLevel(logging.DEBUG)
logging.basicConfig(format='%(levelname)s:%(messa... |
from dice.tokens import Term
import pytest
def test_initialize_term():
"""
"""
pass
def test_term_repr():
pass
def test_term_str():
pass
def test_evaluate_term():
pass |
import _plotly_utils.basevalidators
class CustomdatasrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="customdatasrc", parent_name="scatter", **kwargs):
super(CustomdatasrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... |
"""
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langua... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.