code stringlengths 1 199k |
|---|
class Style(object):
def __str__(self):
if len(self.__dict__) < 1:
return ''
s_str = ' '.join(['%s: %s;' % (k.replace('_', '-'), str(v))
for k, v in self.__dict__.items() if v])
return ' style="' + s_str + '"'
class Node(object):
TAG = ''
PRIVATE... |
from recon.wall import WallReader, WallWriter
from recon.meld import MeldReader, MeldWriter
def wall2meld(wfp, mfp):
"""
This function reads a wall file in and converts it to a
meld file.
"""
wall = WallReader(wfp)
meld = MeldWriter(mfp, metadata=wall.metadata)
objects = {}
tables = {}
... |
class Interface():
pass
class implementer:
def __call__(self, ob):
...
return ob |
from django.forms import CharField
from .widgets import SplitInputWidget
class SplitCharField(CharField):
widget = SplitInputWidget
splitter = ''
def __init__(self, *args, **kwargs):
"""Construct."""
super().__init__(*args, **kwargs)
if 'splitter' in kwargs:
self.splitter... |
import git2json as g
import subprocess as s
BENCH_REPO = '/home/tavish/capstone/nbdiff/.git'
check_added = '1f52ff8b5acaa408948d7a73b07b9dd2554e863a'
HEAD = check_added
commits = g.parse_commits(g.run_git_log(extra_args=[HEAD + '..', '--']).read())
i = 0
for commit in commits:
if i % 5 == 0:
s.call(('git --... |
import color_tracker
cam = color_tracker.WebCamera(video_src=0)
cam.start_camera()
detector = color_tracker.HSVColorRangeDetector(camera=cam)
lower, upper, kernel = detector.detect()
print("Lower HSV color is: {0}".format(lower))
print("Upper HSV color is: {0}".format(upper))
print("Kernel shape is:\n{0}".format(kernel... |
import unittest
from unittest.mock import patch
from api.entity_type import EntityTypeHandler
from api.meta_attribute import MetaAttributeHandler
from api.series_attribute import SeriesAttributeHandler
from api.tag_attribute import TagAttributeHandler
from api.tree import EntityHandler, TreeHandler
from .test_utils imp... |
import unittest
from anyradix import *
from anyradix.anyradix import to_base_10
from anyradix.anyradix import from_base_10
from timeit import timeit
class TestRadixPerformance(unittest.TestCase):
def test_perf(self):
def testtime():
for i in range(1000):
cast(i, 16, 32)
t... |
import os
import glob
__all__ = [os.path.basename(f)[:-3]
for f in glob.glob(os.path.dirname(__file__) + "/*.py")]
def _import_all_extractor_files():
__import__(__name__, globals(), locals(), __all__, 0)
def get_extractor_instances():
""" Get all classes with names ending with 'Extractor' from
th... |
from __future__ import absolute_import
import abc
from functools import partial
from typing import List, Tuple, Any, Union, Dict, Optional
import six
import numpy as np
from scipy.stats import itemfreq
from sklearn.base import BaseEstimator, clone
from sklearn.neighbors import KernelDensity
from sklearn.metrics import ... |
from __future__ import absolute_import, print_function
"""Unit tests for M2Crypto.BIO.File.
Copyright (c) 1999-2002 Ng Pheng Siong. All rights reserved."""
import socket
import sys
import threading
from M2Crypto import BIO
from M2Crypto import SSL
from M2Crypto import Err
from M2Crypto import Rand
from M2Crypto import ... |
"""flea_market URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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... |
import sys
import os
build_cmd_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"out", "Release", ".deps", "out", "Release",
"libnodewrap.d")
build_cmd = open(build_cmd_file).read().strip()
libs = build_cmd.split(" ")
if libs[0] != "cmd_out/Rele... |
"""Django settings for connecting via Google Cloud SQL Proxy."""
from .production import * # noqa: F403
DATABASES = {
"default": {
"ENGINE": 'django.contrib.gis.db.backends.postgis',
"HOST": "cloud_sql_proxy",
"PORT": "5432",
"NAME": "dthm4kaiako",
"USER": env("GOOGLE_CLOUD_... |
'''
Enable/Disable chalmers so that it will run at machine startup.
This command requires root/admin access for all platforms.
If you need to enable chalmers as a service without admin try::
chalmers @login --help
This command will install chalmers server to start on
boot for the current user (posix)::
sudo cha... |
from datetime import datetime as dt
import os
from sqlalchemy import *
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relation
from sqlalchemy.types import Time
from sqlalchemy.types import DateTime
from sqlalchemy.types import Integer
from sqlalchemy.types import Unicode
fro... |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError as RestValidationError
from rest_framework.utils.serializer_helpers import ReturnDict
from rest_framework_friendly_errors import settings
from rest_fr... |
import sys
sys.path.insert(0, '..')
from testing_harness import *
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* and source* have been created."""
TestHarness._test_output_created(self)
source = glob.glob(os.path.join(os.getcwd(), 'source... |
import unittest
from capnp import bases
class BasesTest(unittest.TestCase):
def test_camel_to_upper_snake(self):
for camel in ('http', 'HTTP', 'Http'):
self.assertEqual('HTTP', bases.camel_to_upper_snake(camel))
for camel in ('httpGet', 'HTTP_Get', 'http_Get', 'HttpGet'):
sel... |
import logging
logger = logging.getLogger('spacel.provision.app.alarm.trigger.metrics')
class MetricDefinitions(object):
def __init__(self):
self._metrics = {}
self._ec2_metrics()
self._elb_metrics()
self._system_metrics()
logger.debug('Loaded %d metric definitions.', len(sel... |
from distutils.core import setup
import py2exe
setup(console=['installer.py']) |
import sys
import os
import unittest
import time
import signal
from mock import Mock, patch
sys.path.append(os.path.abspath("."))
sys.path.append(os.path.abspath("rpirobot"))
from rpirobot.run_robot import RobotRunner, TimeoutError, create_robot
class timeout(object):
"""Timeout util."""
def __init__(self, seco... |
from os import listdir
import hashlib
class MapLauncher:
def __init__(self):
self.path = '/home/ut4/LinuxServer/UnrealTournament/Content/Paks/' # Your Maps Path Here, Add Mod Names Below
self.mods = ["Mutator_AbsoluteHitSounds-WindowsNoEditor.pak", "Elimination_113-WindowsNoEditor.pak"]
sel... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))
from subprocess import call
import files
def pairwise_global_alignment(id1, id2):
score = 0
call('needle -asequence embl:%s -bsequence embl:%s -datafile EDNAFULL -gapopen 10.0 -gapextend 1.0 -endweight -endopen 10.0 -endex... |
import subprocess,os
import numpy as np
import mygis
from bunch import Bunch
sfcvarlist=["SSHF_GDS4_SFC","SLHF_GDS4_SFC","Z_GDS4_SFC","BLH_GDS4_SFC","SSRD_GDS4_SFC","STRD_GDS4_SFC", "SSTK_GDS4_SFC", "CP_GDS4_SFC", "LSM_GDS4_SFC"]
icar_sfc_var=["sensible_heat","latent_heat","hgt_98","PBL_height","sw","lw", "tskin", "cp"... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tickets', '0020_ticket_due_at'),
]
operations = [
migrations.AlterField(
model_name='ticket',
name='ticket_type',
fie... |
from __future__ import absolute_import
import os
VERSION = (0, 4, 2)
__version__ = '.'.join(map(str, VERSION))
def js():
"returns home directory of js"
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'js') |
from __future__ import unicode_literals
from django.apps import AppConfig
class NwbbMembersConfig(AppConfig):
name = 'nwbb_members' |
from os import urandom, environ
from datetime import datetime
from hashlib import md5
import psycopg2
from pygments import highlight, util
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter
import pytz
import requests
from PyPaste.models import BaseModel
from PyPaste.... |
import cgi
import cgitb
import datetime
import sys
import lib.restapi.ciscoprimeapi as cispriapi
date_format = "%a %b %d %H:%M:%S %Y"
cgitb.enable()
form = cgi.FieldStorage()
user = form.getvalue('user')
password = form.getvalue('password')
enable_password = form.getvalue('enablepassword')
list_ap_cdp = []
list_ap_no_c... |
from pyelasticsearch import ElasticSearch
es = ElasticSearch('http://localhost:9200/')
es.search('*', index='agile_data_science') |
import hashlib
import json
import os
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sacred.dependencies import get_digest
from sacred.serializer import restore
Base = declarative_base()
class Source(Base):
__tablename__ = "source"
@classmethod
def get_or_create(cls, fil... |
"""
All the advanced Input/Output operations for Vapory
"""
import re
import os
import subprocess
from .config import POVRAY_BINARY
try:
import numpy
numpy_found=True
except IOError:
numpy_found=False
try:
from IPython.display import Image
ipython_found=True
except:
ipython_found=False
def ppm_t... |
from core.core import Board, World
def test_empty_board():
board = Board()
assert board.worlds == {}
assert board.neighbours == {}
def test_board_nodes():
worlds = [World((0, 0)), World((0, 1)), World((0, 2))]
board = Board(worlds=worlds)
assert board.worlds == {world.node: world for world in wo... |
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
cnt = 0
while n > 0:
if (n & 0x0001) != 0:
cnt += 1
n = n >> 1
if cnt == 1:
return True
return False |
from selenium import webdriver
import time,re,requests
import getpass
class QQ:
h={'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=3'}
def __init__(self):
self.d=wendriver.Firefox()
self.get('http://web2.qq.com/webqq.html')
def login(self,qq,pw,check=0):
self.d.find_element_by_id('alloy_... |
import math
import random
class Traveler:
# Single individual
# represents salesman's path
# Size of genome (max number of cities)
size = 0
# Genome is array of nodes (cities)
# They are conected in the same order as in the array
genome = []
# Fitness of this individual
# Assigned by population class
fitness ... |
import json
from django.template.loader import render_to_string
def json_html(value):
html = []
try:
content = json.loads(value)
except ValueError:
return value
pass
else:
for block in content['data']:
template_name = 'sirtrevor/blocks/%s.html' % block['type']
html.append(render_to_string(template_nam... |
"""
Michael Hirsch
Original fortran code by A. E. Hedin
from ftp://hanna.ccmc.gsfc.nasa.gov/pub/modelweb/atmospheric/hwm93/
"""
from pathlib import Path
from numpy import arange
from dateutil.parser import parse
from argparse import ArgumentParser
import hwm93
from matplotlib.pyplot import show
from hwm93.plots import ... |
"""
Analyze results returns by find_k
usage: python k_results.py <results file> [sort key(s)]
Sort keys: k n r m d
Lower-case sorts in increasing order
Upper-case sorts in decreasing order
k: number of clusters
n: total number of points
r: cluster radius (~ std dev)
m: number of corr... |
import datetime
import numpy as np
from hyperopt import hp, fmin, tpe
import os
import sys
sys.path.insert(0, os.getcwd())
import qml_workdir.classes.config
from qml.cv import QCV
from qml.models import QXgb
from qml_workdir.classes.models import qm
if __name__ == "__main__":
CV_SCORE_TO_STOP = 0.5413
DATAS = [... |
__author__ = 'qingfeng' |
from __future__ import print_function, absolute_import
import lasagne
import numpy
import time
import json
import h5py
import theano
import theano.tensor as T
from lifelines.utils import concordance_index
from .deepsurv_logger import DeepSurvLogger
from lasagne.regularization import regularize_layer_params, l1, l2
from... |
import datetime
import json
import itertools
from mwclient import Site
NUM_CONTRIBUTIONS = 1000
site = Site("en.wikipedia.org",
clients_useragent="Data generation bot run by User:APerson (apersonwiki@gmail.com)")
contributions = []
for contribution in itertools.islice(site.usercontributions("APerson", names... |
import sys,os
import types
import shutil
import filecmp
import subprocess
import tempfile
import tarfile
import codecs
mainTEESDir = os.path.abspath(os.path.join(__file__, "../.."))
print mainTEESDir
sys.path.append(mainTEESDir)
import Utils.InteractionXML.Catenate as Catenate
import Utils.Libraries.stats as stats
impo... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules=cythonize(Extension(
'td',
['td.pyx'],
libraries=['td']
)),
) |
class Solution:
def isValidSerialization(self, preorder):
preorder = preorder.split(",")
return self.is_valid_serialization(preorder)
def is_valid_serialization(self, preorder):
edge_count = 1
for node in preorder:
if edge_count == 0:
return False
... |
'''pytest-peach extension
Copyright (c) 2016 Peach Fuzzer, LLC
Provides integration with Peach WebProxy
'''
from __future__ import print_function
import os, warnings, logging
import pytest
import peachproxy
import requests, json, sys
from requests import put, get, delete, post
logger = logging.getLogger(__name__)
__pyt... |
from collections import defaultdict
from configdb import exceptions
from configdb.db import schema
from configdb.db.interface import base
class InMemoryObjectProxy(object):
def __init__(self, name):
self.name = name
class InMemoryRelationProxy(object):
"""Proxy for a database relation attribute.
Sup... |
__author__ = 'sean-abbott'
from setuptools import setup
from distutils.cmd import Command
import subprocess
import sys
import os
import versioneer
def readme():
with open('README.rst') as f:
return f.read()
class BaseCommand(Command):
user_options = []
def initialize_options(self):
pass
... |
"""
Argus deployment settings and defaults.
The settings of argus are passed via environment variables.
"""
import os
ARGUS_ADDRESS = os.getenv('ARGUS_ADDRESS', '0.0.0.0')
ARGUS_PORT = os.getenv('ARGUS_PORT', '5000')
ARGUS_ROOT = os.getenv('ARGUS_ROOT', '/') |
from mpl_toolkits.basemap import Basemap
import fiona
import rasterio
import pyresample
get_ipython().system('conda list') |
class myclass:
i = 10
x = myclass()
print x.i |
import logging
log = logging.getLogger(__name__)
from ReportGenerator.Scan import Scan
from ReportGenerator.IRC import IRC
from ReportGenerator.DRC import DRC
from ReportGenerator.Freq import Freq
from ReportGenerator.Opt import Opt
from ReportGenerator.NoJobType import NoJobType
from ReportGenerator.SinglePoint import... |
import random as rand
node_count = 20
soft_max = 5
data = {}
for i in range(node_count):
data[i] = []
for key, value in data.items():
for i in range(rand.randint(1, soft_max)):
node = rand.randint(0, node_count - 1)
if node != key and node not in value:
value.append(node)
... |
"""
Base management command for rubber.
"""
from __future__ import print_function
from optparse import make_option
import sys
import traceback
import six
from django.core.management.base import BaseCommand
from rubber import get_rubber_config
class ESBaseCommand(BaseCommand):
required_options = []
option_list =... |
import sqlite3
import argparse
import os.path
def init_db(dbcon):
f = open('schema.sql','r')
sql = f.read()
dbcon.executescript(sql)
def dump_db(dbcon):
with open('dump.sql', 'w') as f:
for line in dbcon.iterdump():
f.write('%s\n' % line)
def connect_db():
dbcon = None
# check if meteorologist.db exists
if ... |
from django.db import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin)
class SurmandlUserManager(BaseUserManager):
"""
Model manager for our surmandl site user
"""
def create_user(self, email, first_name, last_name, relation, password=None):
if... |
from __future__ import unicode_literals
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
from django.contrib.auth import get_user_model
from . impo... |
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from riders.models import Teammate
class TeammateCreationForm(forms.ModelForm):
# Ask for a password
password1 = forms.CharField(label = 'Password', widget = forms.PasswordInput)
password2 = forms.CharField(label = 'Pas... |
from slots.slots import MAB
def test_mab():
mab = MAB()
mab.run() |
"""
Bot to add new or existing categories to pages.
This bot takes as its argument the name of a new or existing category.
Multiple categories may be given. It will then try to find new articles
for these categories (pages linked to and from pages already in the category),
asking the user which pages to include and whi... |
__author__ = 'scottieb99'
def greeting(msg):
print(msg)
if __name__ == "__main__":
greeting("Hey y'all") |
import sys
import time
import sqlite3
import telepot
from pprint import pprint
from datetime import date, datetime
import re
import traceback
ROOT = '/root/git/stock-analyzer/'
def sendMessage(id, msg):
try:
bot.sendMessage(id, msg)
except:
print str(datetime.now()).split('.')[0]
traceba... |
from __future__ import unicode_literals, absolute_import
import sys
import phonenumbers
from django.conf import settings
from django.core import validators
if sys.version_info[0] == 3:
string_types = str
else:
string_types = basestring
class PhoneNumber(phonenumbers.PhoneNumber):
"""
A extended version ... |
"""
Sentry Blueprint
=================
**Fabric environment:**
.. code-block:: yaml
blueprints:
- blues.sentry
settings:
sentry:
auth_token: XXXXX
organization: some-org
environment: production
projects:
- proj-slug
- other-slug
"""
import urllib2
... |
from Story import Story
from HashTable import HashTable
import Printer as styler
xnor = lambda var1, var2 : not (var1 ^ var2)
previousStates = []
def generateTuple(tup, var, keyset, tupleLength):
newTuple = []
for i in range(0, tupleLength - 1):
if tup[i] not in keyset:
newTuple.append(tup[i])
else:
idx = k... |
from common_code import *
from common_parameters import *
hours_per_year = 5500.0
c0l_m = [infra_fixed_cost_per_hour(m, hours_per_year, L, width_m, land_cost_per_hectare, \
infracost_m, infralife_m, inframaint_m, discount_rate) \
for m in range(num_modes)]
c0s_m = [stop_fixed_cost_per_hour(m, hours_per... |
import argparse
import socket
import sys
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport
from interface_implementation.dali import TDali
from dali_core import DaliCore
def run(port):
handler = DaliCore()
processor = TDali.Processor(h... |
from .base import ImageAugmentor
__all__ = ['RandomChooseAug', 'MapImage', 'Identity', 'RandomApplyAug']
class Identity(ImageAugmentor):
def _augment(self, img, _):
return img
class RandomApplyAug(ImageAugmentor):
""" Randomly apply the augmentor with a prob. Otherwise do nothing"""
def __init__(sel... |
import sys
from pathlib import Path
from setuptools import setup
if sys.implementation != "cpython":
raise RuntimeError("This package only works on CPython.")
if sys.version_info[0:2] < (3, 3):
raise RuntimeError("This package requires Python 3.3+.")
install_requires = []
if sys.version_info[0:2] < (3, 5):
... |
import random
import behaviours
from objects import EnemyShip, Sensor
import resources as res
import constants as CONSTS
def spawn_line(self, x=None, y=None):
x, y = self.get_spawn_pos(150)
# spawn the first enemy of the line (the anchor)
enemy1 = EnemyShip(behaviours=[[behaviours.link], [behaviours.delay, ... |
"""Support for Satel Integra devices."""
import collections
import logging
from satel_integra.satel_integra import AsyncSatel
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helper... |
from django.apps import apps
from django.db import connection
from django.test import TestCase
from django.test.utils import override_settings
from django_tenants.utils import get_public_schema_name
class TestSettings(TestCase):
def tearDown(self):
apps.unset_installed_apps()
super().tearDown()
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('csyllabusapi', '0004_auto_20171030_0200'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', ... |
import logging
import falcon
import smtplib
from catcher import config
from catcher.models import MySQLModel
class Login(object):
@staticmethod
def send_email(recipient, message):
# TODO: nacitat z configu
sender = 'noreply.catcher@gmail.com'
try:
server = smtplib.SMTP('smtp.... |
from CIM14.IEC61970.Core.IdentifiedObject import IdentifiedObject
class MeterReading(IdentifiedObject):
"""Set of values obtained from the meter.
"""
def __init__(self, IntervalBlocks=None, CustomerAgreement=None, MeterAsset=None, EndDeviceEvents=None, Readings=None, ServiceDeliveryPoint=None, valuesInterva... |
import pylab as pl
import pyfits as pf
import astronomy as ast
import scipy.signal as sci
import os
files = os.listdir(os.curdir)
ff = []
for f in files:
name,ext = os.path.splitext(f)
if name[:2] == 'EC':
ff.append(f)
specgram = []
t = []
trailed_ft = []
for spec in ff[:-2]:
head = pf.getheader(spe... |
import json
import bandicoot as bc
import numpy as np
def parse_dict(path):
with open(path, 'r') as f:
dict_data = json.load(f)
return dict_data
def file_equality(f1, f2):
"""
Returns true if the files are the same, without taking into account
line endings.
"""
with open(f1, "r") as ... |
"""
lru_cache.py:
Implementation of an LRU cache.
"""
from __future__ import absolute_import, print_function
import sys
class Node(object):
next = None
prev = None
def __init__(self, data):
self.data = data
class Cache(object):
"""
{
'key': {
'value': 'value'
... |
"""
This module provides utility functions for operate git.
"""
from subprocess import Popen
class GitError(BaseException):
"""
This Error raises when git command runner has error.
"""
pass
class GitUtility(object):
"""
The GitUtility contains utility functions for operate git.
"""
def _... |
"""test ddf_utils.io"""
import os
import pandas as pd
import numpy as np
from ddf_utils.io import download_csv, serve_datapoint, open_google_spreadsheet
from tempfile import mkdtemp
def test_download_csv():
urls = [
'http://ipv4.download.thinkbroadband.com/5MB.zip',
'http://ipv4.download.thinkbroadb... |
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/mark/catkin_ws/src/open_bottle_utilities/csv_segment_proc/include".split(';') if "/home/mark/catkin_ws/src/open_bottle_utilities/csv_segment_proc/include" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = ""... |
import cgi
import json
import os
import re
import SimpleHTTPServer
import SocketServer
import subprocess
import sys
import threading
VERSION = 'v0.11.1'
hostname = ''
try:
command = "bash -c '[[ $(dig +short $HOSTNAME) ]] && echo $HOSTNAME || wget -q -O - icanhazip.com'"
hostname = subprocess.check_output(comma... |
import sys
filepath = sys.argv[1]
delim = '\t'
if len(sys.argv) > 2:
delim = sys.argv[2]
graph = {}
for line in open(filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
tag = entry[2].lower()
if not src in graph: graph[src] = {}
if not dst in graph[src]: graph[src][dst... |
import os
import re
import json
import requests
import fnmatch
from urllib import urlencode
from BeautifulSoup import BeautifulSoup
_ROOT = os.path.abspath(os.path.dirname(__file__))
invalid_url = {'error': 'Invalid URL'}
unreachable = {'error': 'Failed to reach the URL'}
empty_meta = {'error': 'Found no meta info for ... |
from setuptools import setup
setup(name='pytaf',
version='1.2.1',
description='TAF (Terminal Aerodrome Forecast) and METAR parser and decoder',
url='http://github.com/dmbaturin/pytaf',
author='Daniil Baturin',
author_email='daniil@baturin.org',
license='MIT',
package_dir={'': '... |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import AppPlatformManagementClientConf... |
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):
# Adding model 'Three'
db.create_table('mock_master_three', (
('id', self.gf('django.db.... |
import nltk
def main():
alice = nltk.corpus.gutenberg.words('carroll-alice.txt')
vocab = nltk.FreqDist(alice)
v1000 = list(vocab)[:1000]
mapping = nltk.defaultdict(lambda: 'UNK')
for v in v1000:
mapping[v] = v
alice2 = [mapping[v] for v in alice]
print alice2[:100]
print len(set(... |
import os
import codecs
import collections
from six.moves import cPickle
import numpy as np
import re
import itertools
import poetrytools as pt
import itertools
import string
class TextLoader():
def __init__(self, data_dir, batch_size, seq_length, encoding=None):
self.data_dir = data_dir
self.batch_... |
"""
Second-Hand-Shop Project
@author: Malte Gerth
@copyright: Copyright (C) 2015 Malte Gerth
@license: MIT
@maintainer: Malte Gerth
@email: mail@malte-gerth.de
"""
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail import get_connection, EmailMessage
from dj... |
"""
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import itertools
import textwrap
from collections import Counter
from datetime import timedelta
import click
import colorful as cf
from radish.ex... |
"""Suite Macintosh Connectivity Classes: Classes relating to Apple Macintosh personal computer connectivity
Level 1, version 1
Generated from /Volumes/Sap/System Folder/Extensions/AppleScript
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'macc'
class Macintosh_Connectivity... |
"""
.. function:: coltypes(query:None)
Returns the input query results column names and types.
:Returned table schema:
- *column* text
Column name of input query *schema*
- *type* text
Type of column
Examples:
>>> sql("coltypes select 5 as vt")
column | type
-------------
vt ... |
from grouch.parsers.parser import Parser
class AttributeParser(Parser):
def __init__(self):
self.methods = [self.splitlines, self.clean, self.split, self.remove_engr]
@staticmethod
def splitlines(item):
return item.splitlines()
@staticmethod
def clean(item):
item = [line.lstr... |
import pytest
from pyoffers.exceptions import HasOffersException
from pyoffers.models import Advertiser
CASSETTE_NAME = "advertiser"
def test_create_success(advertiser):
assert isinstance(advertiser, Advertiser)
assert advertiser.country == "CZ"
def test_find_by_id_success(api, advertiser):
instance = api.a... |
import pickle, sys
from pygrid import *
def modify_load(load, modifyValue):
loadVals = {}
for key in load.keys():
if key.startswith("constant"):
loadVals[key] = load[key].split("+")
loadVals[key][1] = float(loadVals[key][1].rstrip("j"))
loadVals[key][0] = float(loadVa... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bibbutler.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
class TelepotException(Exception):
pass
class BadFlavor(TelepotException):
def __init__(self, offender):
super(BadFlavor, self).__init__(offender)
@property
def offender(self):
return self.args[0]
class BadHTTPResponse(TelepotException):
def __init__(self, status, text, response):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.