code stringlengths 1 199k |
|---|
import datetime
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def custom_strftime(format, t):
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator."
start = int(raw... |
import praw
import re
import os
import pickle
from array import *
import random
REPLY = array('i',["I want all the bacon and eggs you have", "I know what I'm about son", "I'm not interested in caring about people", "Is this not rap?"])
if not os.path.isfile("inigo_config.txt"):
print "You must create the file swans... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import urls as djangoauth_urls
from search import views as search_views
from blog import views as blog_views
from wagtail.wagtaila... |
from django.conf.urls import patterns, url
from links import views
urlpatterns = patterns('links.views',
url(r'^link/settings/$', views.settings, name = 'settings'),
url(r'^link/donate/(?P<url>[\d\w.]+)$', views.kintera_redirect, name = 'donate'),
url(r'^link/rider/(?P<url>[\d\w.]+)$', views.t4k_redirect, n... |
def get_planet_name(id):
switch = {
1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
6: "Saturn",
7: "Uranus" ,
8: "Neptune"}
return switch[id] |
import sys
import time
import socket
import struct
import random
import hashlib
import urllib2
from Crypto import Random
from Crypto.Cipher import AES
timeout = 2
socket.setdefaulttimeout(timeout)
limit = 256*256*256*256 - 1
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk... |
"""Deals with input examples for deep learning.
One "input example" is one storm object.
--- NOTATION ---
The following letters will be used throughout this module.
E = number of examples (storm objects)
M = number of rows in each radar image
N = number of columns in each radar image
H_r = number of radar heights
F_r =... |
import os
import re
import sys
import json
import shlex
import logging
import inspect
import functools
import importlib
from pprint import pformat
from collections import namedtuple
from traceback import format_tb
from requests.exceptions import RequestException
import strutil
from cachely.loader import Loader
from .li... |
import antlr3;
import sqlite3;
import pickle;
import sys, os;
import re;
from SpeakPython.SpeakPython import SpeakPython;
from SpeakPython.SpeakPythonLexer import SpeakPythonLexer;
from SpeakPython.SpeakPythonParser import SpeakPythonParser;
def sortResults(results):
l = len(results);
if l == 1 or l == 0:
return re... |
from __future__ import unicode_literals
from __future__ import print_function
import socket
import time
import six
import math
import threading
from random import choice
import logging
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.protocol.states import EventType
from kazoo.handler... |
from turbogears.identity.soprovider import *
from secpwhash import check_password
class SoSecPWHashIdentityProvider(SqlObjectIdentityProvider):
def validate_password(self, user, user_name, password):
# print >>sys.stderr, user, user.password, user_name, password
return check_password(user.password,password) |
from __future__ import print_function
"""
Batch Normalization + SVRG on MNIST
Independent Study
May 24, 2016
Yintai Ma
"""
"""
"""
"""
under folder of batch_normalization
Before merge; number 1
have options for "mlp", "mlpbn"; "sgd" and "custom_svrg2" and "sgd_adagrad"
"""
import sys
import os
import time
import matplo... |
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.path import Path
else:
... |
from __future__ import unicode_literals
import re
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
UserManager)
from django.core import validators
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from notifi... |
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from orcid_api_v3.models... |
import sqlite3 as lite
import sys
import os
dropbox = os.getenv("dropbox")
dbfile = ("Databases\jarvis.db")
master_db = os.path.join(dropbox, dbfile)
con = None
try:
con = lite.connect(master_db)
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print
"SQLite versio... |
try:
from ._models_py3 import DetectedLanguage
from ._models_py3 import DocumentEntities
from ._models_py3 import DocumentError
from ._models_py3 import DocumentKeyPhrases
from ._models_py3 import DocumentLanguage
from ._models_py3 import DocumentLinkedEntities
from ._models_py3 import Docum... |
def wave(str):
li=[]
for i in range(len(str)):
x=list(str)
x[i]=x[i].upper()
li.append(''.join(x))
return [x for x in li if x!=str] |
import array
import struct
import zlib
from enum import Enum
from pkg_resources import parse_version
from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
if parse_version(ks_version) < parse_version('0.7'):
raise Exception(
"Incompatible Kaitai Struct Python API: 0.7 or la... |
"""
This bot regenerates the page VEIDs
The following parameters are supported:
-debug If given, doesn't do any real changes, but only shows
what would have been changed.
"""
__version__ = '$Id: basic.py 4946 2008-01-29 14:58:25Z wikipedian $'
import wikipedia
import pagegenerators, catli... |
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev = ... |
import sublime, sublime_plugin
from indenttxt import indentparser
class IndentToList(sublime_plugin.TextCommand):
def run(self, edit):
parser = indentparser.IndentTxtParser()
#Get current selection
sels = self.view.sel()
selsParsed = 0
if(len(sels) > 0):
for sel i... |
def Setup(Settings,DefaultModel):
# set1-test_of_models_against_datasets/osm299.py
Settings["experiment_name"] = "set1_Mix_model_versus_datasets_299px"
Settings["graph_histories"] = ['together'] #['all','together',[],[1,0],[0,0,0],[]]
# 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5556... |
import base64
import unittest
from ingenico.connect.sdk.defaultimpl.default_marshaller import DefaultMarshaller
from ingenico.connect.sdk.domain.metadata.shopping_cart_extension import ShoppingCartExtension
from ingenico.connect.sdk.meta_data_provider import MetaDataProvider
from ingenico.connect.sdk.request_header imp... |
import threading
import logging
import unittest
import gc
from stockviderApp.utils import retryLogger
from stockviderApp.sourceDA.symbols.referenceSymbolsDA import ReferenceSymbolsDA
from stockviderApp.localDA.symbols.dbReferenceSymbolsDA import DbReferenceSymbolsDA
from stockviderApp.sourceDA.symbols.googleSymbolsDA i... |
import wx
import win32clipboard
import win32con
import gui
import treeInterceptorHandler
import textInfos
import globalVars
def getSelectedText():
obj = globalVars.focusObject
if isinstance(obj.treeInterceptor, treeInterceptorHandler.DocumentTreeInterceptor) and not obj.treeInterceptor.passThrough:
obj = obj.treeIn... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
np.random.seed(0)
n_samples = 30
degrees = [1, 4, 15]
true_fun = lambda X: n... |
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
from cdo import Cdo
from pycmbs.data import Data
import tempfile as tempfile
import copy
import glob
import os
import sys
import numpy as np
from pycmbs.benchmarking import preprocessor
from p... |
from threading import Lock
import requests
from api.decorator import critical_section
from api.importer import AdditionalDataImporter
from api.importer import AdditionalDataImporterError
from api.importer.wiktionary import dyn_backend
rmi_lock = Lock()
class DictionaryImporter(AdditionalDataImporter):
def populate_... |
import math
class VirtualScreen: #cet ecran est normal a l'axe Z du Leap
def __init__(self,Xoffset=0,Yoffset=50,Zoffset=-50,Zlimit=220,length=350,height=300): #en mm
self.Xoffset = Xoffset; # position du milieu du bord bas de l'ecran par rapport au centre du Leap
self.Yoffset = Yoffset; # position du milieu du bor... |
from rewpapi.common.http import Request
from rewpapi.listings.listing import ListingResidential
class RemoteListingImages(Request):
def __init__(self, base_site, auth, listing_type, listing_uuid):
super(RemoteListingImages, self).__init__(auth)
self._base_site = base_site
self._auth = auth
... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import Async... |
from __future__ import absolute_import
import unittest
import types
if __name__ == "__main__":
from optional import * #imports from package, not sub-module
else:
from .optional import *
from .nulltype import *
class TestNullType(unittest.TestCase):
def test_supertype(self):
self.assert_(isinstan... |
import pymysql
import PyGdbUtil
class PyGdbDb:
# 初始化: 连接数据库
def __init__(self, host, port, dbname, user, passwd):
self.project = None
self.table_prefix = None
try:
self.connection = pymysql.connect(
host=host, port=int(port), user=user, password=passwd, db=dbn... |
import root
import j |
import os
import numpy as np
import time
a = np.array([
[1,0,3],
[0,2,1],
[0.1,0,0],
])
print a
row = 1
col = 2
print a[row][col]
assert a[row][col] == 1
expected_max_rows = [0, 1, 0]
expected_max_values = [1, 2, 3]
print 'expected_max_rows:', expected_max_rows
print 'expected_max_values:', expected_max_val... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'', include('frontpage.urls')),
url(r'^auth/', include('social.apps.django_app.urls', namespace='social')),
url(r'^admin/', include(admin.site.urls)),
url(r'^log... |
import fetchopenfmri.fetch |
"""
To run this test, type this in command line <kolibri manage test -- kolibri.core.content>
"""
import datetime
import unittest
import uuid
import mock
import requests
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.test import TestCase
fro... |
import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].rep... |
import urllib2
import os
baseurl = "http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A"
constituencyCount = 0
constituencyTotal = 229
while constituencyCount <= constituencyTotal:
pdfCount = 1
notDone = True
constituencyCount = constituencyCount + 1... |
import sys
import re
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
f... |
from pydatastream import Datastream
import json
import datetime
import sys
import os.path
dir_input = "input/"
dir_output = "output/"
numOfArgs = len(sys.argv) - 1
if numOfArgs != 3:
print "Please run this python script with username,password and input file location in that order respectively."
exit()
username = st... |
"""Unit tests for conus_boundary.py."""
import unittest
import numpy
from gewittergefahr.gg_utils import conus_boundary
QUERY_LATITUDES_DEG = numpy.array([
33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1,
49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2
])
QUERY_LONGITUDES_DEG = numpy.array... |
import somnTCP
import somnUDP
import somnPkt
import somnRouteTable
from somnLib import *
import struct
import queue
import threading
import socket
import time
import random
PING_TIMEOUT = 5
class somnData():
def __init__(self, ID, data):
self.nodeID = ID
self.data = data
class somnMesh(threading.Thread):
TC... |
from rest_framework import serializers
from workers.models import (TaskConfig,
Task,
Job,
TaskProducer)
from grabbers.serializers import (MapperSerializer,
SequenceSerializer)
from grabbers.models impor... |
import tensorflow as tf
from tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper
from tqdm import tqdm
from decoder import pointer_decoder
import dataset
import matplotlib.pyplot as plt
"""
Michel:
_____________________________________________________________________
- Plot tour with networkx
... |
import subprocess
from typing import List
import pytest
from libqtile.widget import caps_num_lock_indicator
from test.widgets.conftest import FakeBar
class MockCapsNumLockIndicator:
CalledProcessError = None
info: List[List[str]] = []
is_error = False
index = 0
@classmethod
def reset(cls):
... |
import random
from string import digits, ascii_letters, punctuation
def password_generator(length):
while True:
values = list(digits + ascii_letters + punctuation)
yield ''.join([random.choice(values) for i in range(length)]) |
"""
Utilities module containing various useful
functions for use in other modules.
"""
import logging
import numpy as np
import scipy.linalg as sl
import scipy.sparse as sps
import scipy.special as ss
from pkg_resources import Requirement, resource_filename
from scipy.integrate import odeint
from scipy.interpolate impo... |
import os
import pytest
import platform
import functools
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics.aio import TextAnalyticsClient
from azure.ai.textanalytics import (
VERSION,
DetectLanguageInp... |
import sys
import glob
import numpy as np
from .netcdf import netcdf_file
_exclude_global = ['close',
'createDimension',
'createVariable',
'dimensions',
'filename',
'flush',
'fp',
'mode',... |
"""Publishing native (typically pickled) objects.
"""
from traitlets.config import Configurable
from ipykernel.inprocess.socket import SocketABC
from traitlets import Instance, Dict, CBytes
from ipykernel.jsonutil import json_clean
from ipykernel.serialize import serialize_object
from jupyter_client.session import Sess... |
from __future__ import unicode_literals
from django.db import migrations, models
from blog.models import Post
def slugify_all_posts(*args):
for post in Post.objects.all():
post.save()
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
... |
import six
from unittest import TestCase
from dark.reads import Read, Reads
from dark.score import HigherIsBetterScore
from dark.hsp import HSP, LSP
from dark.alignments import (
Alignment, bestAlignment, ReadAlignments, ReadsAlignmentsParams,
ReadsAlignments)
class TestAlignment(TestCase):
"""
Tests fo... |
import requests
import platform
from authy import __version__, AuthyFormatException
from urllib.parse import quote
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
from django.utils import simplejson as json
class Resource(object):
def __init__(self... |
import datetime
import MySQLdb
from os import sys
class DBLogger:
def __init__(self, loc='default-location'):
self.usr = '<user>'
self.pwd = '<password>'
self.dbase = '<database>'
self.location = loc
self.conn = MySQLdb.connect(host="localhost", user=self.usr, passwd=self.pwd, db=self.dbase)
s... |
from unittest.mock import Mock
import sqlalchemy as sa
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.orm import query
from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm impo... |
'''
Creates an html treemap of disk usage, using the Google Charts API
'''
import json
import os
import subprocess
import sys
def memoize(fn):
stored_results = {}
def memoized(*args):
try:
return stored_results[args]
except KeyError:
result = stored_results[args] = fn(*ar... |
""" Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(test... |
__author__ = 'ysahn'
import logging
import json
import os
import glob
import collections
from mako.lookup import TemplateLookup
from mako.template import Template
from taskmator.task.core import Task
class TransformTask(Task):
"""
Class that transform a json into code using a template
Uses mako as template ... |
import sys
import traceback
import logging
import time
import inspect
def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0):
... |
"""
Solve day 23 of Advent of Code.
http://adventofcode.com/day/23
"""
class Computer:
def __init__(self):
"""
Our computer has 2 registers, a and b,
and an instruction pointer so that we know
which instruction to fetch next.
"""
self.a = 0
self.b = 0
... |
import subprocess
import os
import errno
def download_file(url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.path.exists(local_fname):
return local_fname
dir_name = os.path.d... |
import unittest
from locust.util.timespan import parse_timespan
from locust.util.rounding import proper_round
class TestParseTimespan(unittest.TestCase):
def test_parse_timespan_invalid_values(self):
self.assertRaises(ValueError, parse_timespan, None)
self.assertRaises(ValueError, parse_timespan, ""... |
from __future__ import division
"""
main.py -- main program of motif sequence coverage pipeline tool
example for running code: python main.py -jid test -confFile ./data/default_scan_only.conf
This will create a results folder with the name test. You will need to delete the folder if you want to run the code again with... |
from __future__ import annotations
from typing import Generic, TypeVar
T = TypeVar("T")
class DisjointSetTreeNode(Generic[T]):
# Disjoint Set Node to store the parent and rank
def __init__(self, data: T) -> None:
self.data = data
self.parent = self
self.rank = 0
class DisjointSetTree(Gen... |
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 azure.core.pipeline i... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('primus', '0006_auto_20160418_0959'),
]
operations = [
migrations.AlterField(
model_name='building',
name='modified',
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bikes_prediction.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import codecs, logging, os, util
from tokenizer import Tokenizer
from tokenparser import Parser
from api import Document
def setup_logging():
logger=logging.getLogger("W2L")
logger.setLevel(logging.DEBUG)
console_formatter = logging.Formatter("%(asctime)s - %(levelname)s"
... |
"""Testing for ORM"""
from unittest import TestCase
import nose
from nose.tools import eq_
from sets import Set
from mdcorpus.orm import *
class ORMTestCase(TestCase):
def setUp(self):
self.store = Store(create_database("sqlite:"))
self.store.execute(MovieTitlesMetadata.CREATE_SQL)
self.stor... |
from ddt import ddt, data
from django.test import TestCase
from six.moves import mock
from waldur_core.core import utils
from waldur_core.structure import tasks
from waldur_core.structure.tests import factories, models
class TestDetectVMCoordinatesTask(TestCase):
@mock.patch('requests.get')
def test_task_sets_c... |
"""
Make a grid of synths for a set of attenuations.
2015-04-30 - Created by Jonathan Sick
"""
import argparse
import numpy as np
from starfisher.pipeline import PipelineBase
from androcmd.planes import BasicPhatPlanes
from androcmd.phatpipeline import (
SolarZIsocs, SolarLockfile,
PhatGaussianDust, PhatCrowdin... |
from .sub_resource import SubResource
class ApplicationGatewayHttpListener(SubResource):
"""Http listener of an application gateway.
:param id: Resource ID.
:type id: str
:param frontend_ip_configuration: Frontend IP configuration resource of an
application gateway.
:type frontend_ip_configurat... |
"""
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pandoc_rst(source, from_form... |
import scrapy
from locations.items import GeojsonPointItem
DAYS = [
'Mo',
'Tu',
'We',
'Th',
'Fr',
'Sa',
'Su'
]
class SparNoSpider(scrapy.Spider):
name = "spar_no"
allowed_domains = ["spar.no"]
start_urls = (
'https://spar.no/Finn-butikk/',
)
def parse(self, respon... |
"""
Controller for voting related requests.
"""
import webapp2
from models.vote import VoteHandler
from models.vote_.cast_ballot import BallotHandler
from models.vote_.view_results import ResultsHandler
app = webapp2.WSGIApplication([
('/vote', VoteHandler),
('/vote/cast-ballot', BallotHandler),
('/vote/vie... |
from galaxy.test.base.twilltestcase import TwillTestCase
class EncodeTests(TwillTestCase):
def test_00_first(self): # will run first due to its name
"""3B_GetEncodeData: Clearing history"""
self.clear_history()
def test_10_Encode_Data(self):
"""3B_GetEncodeData: Getting encode data"""
... |
import click
from bitshares.amount import Amount
from .decorators import online, unlock
from .main import main, config
from .ui import print_tx
@main.group()
def htlc():
pass
@htlc.command()
@click.argument("to")
@click.argument("amount")
@click.argument("symbol")
@click.option(
"--type", type=click.Choice(["ri... |
import os.path
import requests
import time
from bs4 import BeautifulSoup
from geotext import GeoText as gt
from string import punctuation
from collections import Counter
import re
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
threats = ['loss', 'fragmentation', 'hunting', 'poaching', 'fishing', 'overfishing', ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('stats', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Dispensed',
fields=[
('id', models.AutoFi... |
MAX_LOOPS = 10
MAX_WAIT = 10
import Queue,time,random
def mmThread(inputQueue,exitQueue,outputQueue):
#Lists for all difficulties
noviceList = []
apprenticeList = []
adeptList = []
expertList = []
#put them in one list
playerList = [noviceList,apprenticeList,adeptList,expertList]
#This l... |
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi, sleep
import json
import MySQLdb
class JPC:
#
# 初期化
#
def __init__(self, filepath_config):
import hashlib
# 設定ファイルをロード
fp = open(filepath_config, 'r')
config = json.load(fp)
fp.close()... |
"""
download a file named filename from the atsc301 downloads directory
and save it as a local file with the same name.
command line example::
python -m a301utils.a301_readfile photon_data.csv
module example::
from a301utils.a301_readfile import download
download('photon_data.csv')
"""
import argpar... |
import matplotlib.pyplot as plt
from math import sqrt
from math import log
dx = [1/sqrt(16), 1/sqrt(64), 1/sqrt(256), 1/sqrt(1024)]
dx_tri = [1/sqrt(32), 1/sqrt(128), 1/sqrt(512), 1/sqrt(2048)]
dx_pert = [0.0270466, 0.0134827, 0.00680914, 0.00367054]
dx_fp = [0.122799, 0.081584, 0.0445639, 0.0225922, 0.0113763]
fp_actu... |
import sublime, sublime_plugin
import os.path
import platform
def compare_file_names(x, y):
if platform.system() == 'Windows' or platform.system() == 'Darwin':
return x.lower() == y.lower()
else:
return x == y
class SwitchFileCommand(sublime_plugin.WindowCommand):
def run(self, extensions=[]... |
from __future__ import print_function
from datetime import datetime
import inspect
import json
import logging
import os
try:
import pkg_resources
except ImportError: # pragma: no cover
pkg_resources = None
import random
import re
import subprocess
import shutil
import string
import sys
import time
import boto3... |
import sys
import mechanize
import re
import json
import time
import urllib
import dogcatcher
import HTMLParser
import os
h = HTMLParser.HTMLParser()
cdir = os.path.dirname(os.path.abspath(__file__)) + "/"
tmpdir = cdir + "tmp/"
voter_state = "SC"
source = "State"
result = [("authory_name", "first_name", "last_name", "... |
"""The tests for the MQTT cover platform."""
from unittest.mock import patch
import pytest
from homeassistant.components import cover
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_CURRENT_TILT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
)
from homeassistant.components.mqtt im... |
import pytest
from everest.repositories.rdb.testing import check_attributes
from everest.repositories.rdb.testing import persist
from thelma.tests.entity.conftest import TestEntityBase
class TestExperimentEntity(TestEntityBase):
def test_init(self, experiment_fac):
exp = experiment_fac()
check_attri... |
"""
virtstrap.log
-------------
Provides a central logging facility. It is used to record log info
and report both to a log file and stdout
"""
import sys
import logging
import traceback
CLINT_AVAILABLE = True
try:
from clint.textui import puts, colored
except:
# Clint is still not stable enough yet to just imp... |
from ...utils.tests import base as base
from ...utils.tests import mpi as mpit
__REFERENCE_RESULTS__ = {
"dryrun": {
0.1: {
0.1: {
"accuracy": 1-0.9300,
},
1: {
"accuracy": 1-0.9300,
},
10: {
... |
from __future__ import print_function
from eventlet import hubs
from eventlet.support import greenlets as greenlet
__all__ = ['Event']
class NOT_USED:
def __repr__(self):
return 'NOT_USED'
NOT_USED = NOT_USED()
class Event(object):
"""An abstraction where an arbitrary number of coroutines
can wait f... |
from PyQt4 import QtCore, QtGui
from components.propertyeditor.Property import Property
from components.RestrictFileDialog import RestrictFileDialog
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os
class QPropertyModel(QtCore.QAbstractItemModel):
def __init__(self, parent):
super(QPrope... |
"""
Sitemap builder
"""
import json, os
from treelib import Tree
from optimus.conf import settings
class SitemapError(Exception):
pass
class PageSitemap(object):
"""
Construct ressource page to build and published sitemap
"""
def __init__(self, tree, view, with_root=False):
self.tree = json.... |
import rcblog
if __name__ == '__main__':
rcblog.main() |
"""
calibrateCamera2.py:
"""
import cv2
import numpy as np
def draw_axis(img, charuco_corners, charuco_ids, board):
vecs = np.load("./calib.npz") # I already calibrated the camera
mtx, dist, _, _ = [vecs[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')]
ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard(
... |
def hamming_distance(bytes1, bytes2):
distance = 0
for b1, b2 in zip(bytes1, bytes2):
xored = b1^b2
distance += sum(1 for n in range(8) if (xored >> n) & 0x01)
return distance |
"""
Module containing MPG Ranch NFC coarse classifier, version 3.1.
An NFC coarse classifier classifies an unclassified clip as a `'Call'`
if it appears to be a nocturnal flight call, or as a `'Noise'` otherwise.
It does not classify a clip that has already been classified, whether
manually or automatically.
This class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.