content stringlengths 4 20k |
|---|
from django.conf.urls import patterns, include, url
from django.conf import settings
import cart.views
import orders.views
urlpatterns = patterns('',
url(r'^$', 'cart.views.view_cart', name='view_cart'),
#url(r'^rebuild/(?P<cart_id>[-\w]+)/$', 'cart.views.cart_rebuilder', name='cart_rebuilder'),
url(r'^add... |
'''
Fix the labels created by Wmatrix
'''
print('Fix the labels created by Wmatrix')
#--------------------------------------------
#run create_Info_Files.py before running this
#--------------------------------------------
import pickle, time, pprint
from prettytable import PrettyTable
LVLs = ['lvl1','lvl2','lvl3'... |
import json
from time import sleep
from gitlabform.gitlab.core import (
GitLabCore,
NotFoundException,
TimeoutWaitingForDeletion,
)
class GitLabProjects(GitLabCore):
def get_project_case_insensitive(self, some_string):
# maybe "foo/bar" is some project's path
try:
# try ... |
import psutil
from Hologram.Network.Modem.ModemMode.pppd import PPPConnection
from Hologram.Network.Modem.ModemMode.IPPP import IPPP
from Hologram.Network.Route import Route
from Exceptions.HologramError import PPPError
DEFAULT_PPP_TIMEOUT = 200
DEFAULT_PPP_INTERFACE = 'ppp0'
MAX_PPP_INTERFACE_UP_RETRIES = 10
MAX_RERO... |
# -*- coding: utf-8 -*-
'''
Created on 23 may 2014
@author: Ronald Portier, Therp
<EMAIL>
http://www.therp.nl
For the model defined here _auto is set to False to prevent creating a
database file. All i/o operations are overridden to use a sql SELECT that
takes data from res_partner_connection_type where each type is... |
import datetime
import glob
import logging
import optparse
import os
import sys
import time
from django.conf import settings
from django.core.management.base import BaseCommand
from threedi_verification.models import LibraryVersion
from threedi_verification.models import TestCase
from threedi_verification.models impo... |
import os
import sys
import glob
# Find path to the BERNAISE root folder
bernaise_path = "/" + os.path.join(*os.path.realpath(__file__).split("/")[:-2])
# ...and append it to sys.path to get functionality from BERNAISE
sys.path.append(bernaise_path)
from common import info, info_cyan
def get_help(methods, methods_fol... |
from django.utils.translation import gettext_lazy as _
from .registries import model_templates_registry, ModelTemplateBase
from .models import Series, PublicEvent
@model_templates_registry.register
class BaseEventTemplate(ModelTemplateBase):
model = PublicEvent
template_name = 'core/event_pages/individual_ev... |
"""Simple XML-RPC Server.
This module can be used to create simple XML-RPC servers
by creating a server and either installing functions, a
class instance, or by extending the SimpleXMLRPCServer
class.
It can also be used to handle XML-RPC requests in a CGI
environment using CGIXMLRPCRequestHandler.
A list of possibl... |
import argparse
import json
import re
from utils import libconf
import utils.common as Tools
def ConvertFile(args):
print(r'''//================= Hercules Database =====================================
//= _ _ _
//= | | | | | |
//= | |_| | ___ _ __ ___ _ _| |... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This submodule contains functions for calculating the topological invariants from the result of a WCC / Wilson loop calculation.
"""
from fsc.export import export
from ._utils import _pol_step, _sgng, _check_kramers_pairs
@export
def chern(surface_result):
r"""
... |
from asyncio import Future
from typing import cast, Any, Callable, Union
from rx import from_future
from rx.core import Observable
from rx.disposable import CompositeDisposable, SingleAssignmentDisposable, SerialDisposable
from rx.internal.utils import is_future
def _switch_latest() -> Callable[[Observable], Observa... |
#!/usr/bin/env python
"""
DNS popper
Asks openstack about all the running instances that currently have floats
then creates a CNAME record to point to the public-X.X.X.X username
"""
import keystoneclient
from keystoneclient import exceptions as kc_exceptions
import MySQLdb as mdb
import re
import syslog
class dns... |
'''
Created on 2018. 1. 2.
@author: donghwa
'''
import datetime
import base64
# common value set #
strApp = "maepagesafer"
strPVersion = "25131"
strSignature = "MARKANYEPS"
# 2D Bacode value set #
# dev setting
# strMAServerIP = 'docker.for.mac.localhost'
# iMAServerPort = 8888
# real settin... |
import numpy as np
from sum_conv import sum_conv
def extcoeff_M(x,ME,MM,settings):
# ME,MM : ME[0],MM[0]
# x : x[nK]
nNmax=ME.shape[1]
n=np.arange(1,nNmax+1)[None,:] # 1 x N
cc1 = 2*n+1 # 1 x N
x2inv=1/x**2 # L x 1
# print(x2inv.shape)
# scattering efficiency
tmp1=np.absolute(-ME[:,:... |
#!/usr/bin/env python
#This is a small modification from the simpletorrentstreaming module on pypi
"""
Utils
"""
# -*- coding: utf-8 -*-
import mimetypes
import urlparse
import re
import config
import os
BUFF_PERCENT = 5
def rm_rf(d):
for path in (os.path.join(d,f) for f in os.listdir(d)):
if os.pa... |
"""
Optimization of the CADRE MDP.
"""
from __future__ import print_function
import numpy as np
from openmdao.api import Problem, PETScKrylov # , LinearBlockGS
from CADRE.CADRE_mdp import CADRE_MDP_Group
import cProfile
import pstats
import sys
argv = sys.argv[1:]
if 'paper' in argv:
# These numbers are for ... |
"""System tests for Google BigQuery hooks"""
import unittest
import pytest
from airflow.providers.google.cloud.hooks import bigquery as hook
from tests.providers.google.cloud.utils.gcp_authenticator import GCP_BIGQUERY_KEY
@pytest.mark.system("google.cloud")
@pytest.mark.credential_file(GCP_BIGQUERY_KEY)
class Big... |
"""Class to predict memory usage for runs at various nsides.
"""
import os
import numpy as np
import healpy as hp
import esutil
import fitsio
from ..configuration import Configuration
from ..catalog import Entry
class MemPredict(object):
def __init__(self, configfile):
"""Instantiate a MemPredict.
... |
from unittest.mock import Mock
from opendrop.mvp.view import View
def test_view_init_sets_presenter():
class MyView(View):
pass
my_view = MyView()
mock_presenter = Mock()
my_view._init(presenter=mock_presenter)
assert my_view.presenter == mock_presenter
def test_view_init_passes_optio... |
"""
Tests for the order_with_respect_to Meta attribute.
"""
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class Question(models.Model):
text = models.CharField(max_length=200)
@python_2_unicode_compatible
class Answer(model... |
# -*- coding: utf-8 -*-
import pytest
from mock import MagicMock
from .utils import db_helper
from models import (Journalist, Submission, Reply, Source, get_one_or_else,
LoginThrottledException)
def test_source_public_key_setter_unimplemented(journalist_app, test_source):
with journalist_app... |
"""
Purpose
Creates an Amazon DynamoDB table to use for the demonstration.
"""
# snippet-start:[dynamodb.Python.TryDax.01-create-table]
import boto3
def create_dax_table(dyn_resource=None):
"""
Creates a DynamoDB table.
:param dyn_resource: Either a Boto3 or DAX resource.
:return: Th... |
"""Adds Beatport release and track search support to the autotagger
"""
from __future__ import division, absolute_import, print_function
import json
import re
import six
from datetime import datetime, timedelta
from requests_oauthlib import OAuth1Session
from requests_oauthlib.oauth1_session import (TokenRequestDenie... |
# This file contains all relevant configuration for the system
# The location where this server is to be deployed to
# Only URIs in the dump that start with this address will be published
# Should end with a trailing /
BASE_NAME = "http://localhost:8080/"
# The prefix that this servlet will be deployed, e.g.
# if the ... |
import base64
import binascii
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from Crypto.Cipher import AES
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.conf import settings
from django import template
re... |
import csv
import os.path as osp
from collections import defaultdict
import stable_baselines3.common.logger as sb_logger
import imitation.util.logger as logger
def _csv_to_dict(csv_path: str) -> dict:
result = defaultdict(list)
with open(csv_path, "r") as f:
for row in csv.DictReader(f):
... |
from openerp import models, fields, api
from openerp.exceptions import ValidationError
class AccountThirdCheck(models.Model):
_inherit = 'account.third.check'
@api.depends('deposit_slip_ids')
def get_deposit_slip_id(self):
for check in self:
check.deposit_slip_id = check.deposit_slip... |
"""
Support for interacting with and controlling the cmus music player.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.cmus/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MEDIA_TYPE_MU... |
"""The base Controller API
Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
from pylons import request, response, session, tmpl_context as c
from zkpylons.model.db_content import DbContent, DbContentType
from zkpyl... |
"""
Cache driver that uses SQLite to store information about cached images
"""
from __future__ import absolute_import
from contextlib import contextmanager
import os
import sqlite3
import stat
import time
from eventlet import sleep
from eventlet import timeout
from oslo_config import cfg
from oslo_log import log as l... |
import pkg_resources
from random import randrange
from .names import NameGenerator
class EmailGenerator(object):
_tlds = None
_words = None
@property
def words(self):
if not EmailGenerator._words:
EmailGenerator._words = []
with pkg_resources.resource_stream("mockingb... |
"""TensorFlow Lite Python Interface: Sanity check."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from tensorflow.lite.tools import test_utils
from tensorflow.lite.tools import visualize
from tensorflow.python.framework import test_u... |
"""Contains the model definition for the OverFeat network.
The definition for the network was obtained from:
OverFeat: Integrated Recognition, Localization and Detection using
Convolutional Networks
Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and
Yann LeCun, 2014
http://arxiv.org/a... |
#!/usr/bin/env python
#
# test_backbone_builder.py
#
# unit tests for reconstructing full backbones
# e.g. after loop insertsions.
#
# http://iimcb.genesilico.pl/moderna/
#
__author__ = "Magdalena Rother, Tomasz Puton, Kristian Rother"
__copyright__ = "Copyright 2008, The Moderna Project"
__credits__ = ["Janusz Bujnick... |
"""This module contains a collection of unit tests which
validate ..main
"""
import os
import signal
import sys
import tempfile
import unittest
import mock
import tor_async_util
import tornado.httpserver
from ..main import Main
from . import Patcher
class IsLibcurlCompiledWithAsyncDNSResolverPatcher(Patcher):
... |
from capture_gui.vendor.Qt import QtCore, QtWidgets
import capture_gui.plugin
import capture_gui.lib as lib
import capture
class ViewportPlugin(capture_gui.plugin.Plugin):
"""Plugin to apply viewport visibilities and settings"""
id = "Viewport Options"
label = "Viewport Options"
section = "config"
... |
#------------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation.
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated ... |
import Tkinter as tk
import time
import random
class Propiedades:
#Clase que contiene todas las variables "globales"
anchoPantalla = 250 # alto de la pantalla.
altoPantalla = 250 # ancho de la pantalla.
tile = 10 # alto y ancho del tile.
colorFondo = [0,0,0] # color del fondo.
modoPaleta = "MC" # ... |
import os
import py
import pytest
from infrared.core.services import workspaces
from infrared.core.utils import exceptions
@pytest.fixture(scope="session")
def workspace_manager_fixture(tmpdir_factory):
"""Sets the default workspace direcotry to the temporary one. """
temp_workspace_dir = tmpdir_factory.mk... |
"""Support for Axis lights."""
from axis.event_stream import CLASS_LIGHT
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
LightEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .axis_base import Ax... |
# -*- coding: utf-8 -*-
import urllib
from django import http, test
from django.conf import settings
from django.core import mail
from mock import Mock, patch
from nose.tools import eq_
from olympia import amo
from olympia.amo.tests import TestCase
from olympia.addons.models import Addon
from olympia.amo.urlresolver... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import json
import locale
import logging
import operator
import time
from multiprocessing.dummy import Pool as ThreadPool
import bs4
import requests
import xlwt
def write_results(brand_results, item_results):
xls_file = xlwt.Workbook()
incoming_brand_... |
"""Tests for tfx.orchestration.launcher.kubernetes_component_launcher."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from unittest import mock
from kubernetes import client
from kubernetes import config
import tensorflow as tf
from tfx.orche... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012 Fabio Erculiani
Authors:
Fabio Erculiani
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 3.
This program is distributed in the hope that it ... |
# Jython
import org.openscience.cdk as cdk
import java
import common
class MyAromaticSmilesWriter(common.AromaticSmilesWriter):
def getoutput(self, smi):
sp = cdk.smiles.SmilesParser(cdk.silent.SilentChemObjectBuilder.getInstance())
mol = sp.parseSmiles(smi)
aromaticity = cdk.a... |
import re
import io
import os
import sys
import codecs
from weakref import WeakKeyDictionary
PY2 = sys.version_info[0] == 2
WIN = sys.platform.startswith('win')
DEFAULT_COLUMNS = 80
_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')
def _make_text_stream(stream, encoding, errors):
if encoding is None:
... |
import platform
import setuptools
from setuptools.command import test
import sys
install_requires = [
'future',
# mock-1.0.1 is the last version compatible with setuptools <17.1,
# which is what comes with Ubuntu 14.04 LTS.
'mock<=1.0.1',
'portpicker',
'psutil',
'pytz',
'pyyaml',
't... |
#!/usr/bin/env python
"""
Python routines for scraping data from Princeton's registrar.
by Alex Ogier '13.
Kept limping along by Brian Kernighan, with bandaids every year
as the registrar makes format changes.
If run as a python script, the module will dump information on all the courses available
on the registrar we... |
from hyperstream.stream import StreamInstance
from hyperstream.tool import SelectorTool
from collections import Counter
def safe_key(item):
k, v = item
return str(k).replace(".", "__dot__").replace("$", "__dollar__"), v
class PercentilesToCsv(SelectorTool):
"""
For each document assumed to be a list... |
import unittest
import hex.documents as documents
import hex.encodings as encodings
import hex.hexwidget as hexwidget
from hex.charcolumn import CharColumnModel
from PyQt4.QtGui import QFont
data = b'\xd1\x82\xd0\xb5\xd0\xba\xd1\x81\xd1\x82\x31\x32\x33'
class CharColumnTest(unittest.TestCase):
def test(self):
... |
def binomial_to_dict(input):
'''compute dictionary equivalent to input
'''
input = input.strip()
if input in ['?', '']:
return {}
result = {'object': 'taxon',
'ht-rank': 'genus',
'hybrid': False,
'rank': 'species'}
values = input.split(' ', 2)
... |
import datetime
import logging
import os
from lxml import etree
logger = logging.getLogger('tests')
now = datetime.datetime.now()
future = now + datetime.timedelta(days=1)
__path__ = os.path.dirname(os.path.realpath(__file__))
NAMESPACE_PREFIX = '{http://ws.plimus.com}'
SANDBOX_CLIENT_CONFIG = {
'env': 'sand... |
"""Provides an HTTP API for mobile_app."""
from __future__ import annotations
from contextlib import suppress
import secrets
from aiohttp.web import Request, Response
import emoji
from nacl.secret import SecretBox
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant... |
import logging
import time
import re
import os
from autotest.client.shared import error
from autotest.client import utils
from virttest import virt_vm, utils_misc, qemu_storage, data_dir
class EnospcConfig(object):
"""
Performs setup for the test enospc. This is a borg class, similar to a
singleton. The ... |
"""add certificate to dbs
Revision ID: b5998378c225
Revises: 72428d1ea401
Create Date: 2020-03-25 10:49:10.883065
"""
# revision identifiers, used by Alembic.
revision = "b5998378c225"
down_revision = "72428d1ea401"
from typing import Dict
import sqlalchemy as sa
from alembic import op
from sqlalchemy_utils import... |
#!/usr/bin/python2
import sys
from collections import OrderedDict
# Daniel Elsner
#Takes a tabular blast results file (outfmt 6), reduced to the the three colums query, hit and score (use "cut", from GNU coreutils, presumably included in most Linux distros), to obtain the score of each relevant pairwise comparison.
... |
import os
import sys
from os.path import abspath, dirname, join
from site import addsitedir
VIRTUALENV_BASE = "/home/harley/projects/social-commerce-project/env"
if not VIRTUALENV_BASE:
raise Exception("VIRTUALENV_BASE is not set correctly.")
activate_this = join(VIRTUALENV_BASE, "bin/activate_this.py")
execfile... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... |
"""
A collection of utilities used for SSL tests.
"""
import json
import logging
from typing import Any, Dict, Optional
import sdk_cmd
import sdk_security
import sdk_utils
log = logging.getLogger(__name__)
def setup_service_account(
service_name: str, service_account_secret: Optional[str] = None
) -> Dict[str,... |
import contextlib
import itertools
import numpy as np
import pytest
import bezier
from bezier import curve
from bezier.hazmat import algebraic_intersection
from bezier.hazmat import geometric_intersection
from bezier.hazmat import triangle_helpers
from bezier.hazmat import triangle_intersection
from tests import util... |
from scipy import sqrt, arctan, arctan2, sin, cos
from numpy.linalg import norm
from typing import Sequence, Tuple
from .geo_error import GeolocationError
from dedop.conf import ConstantsFile
# ATK patch for newer ecef2lla():
from numpy import mod, pi, abs, logical_and
import numbers
COORD_ITERS = 10
GEODETIC_ERR =... |
# coding=utf-8
"""Unit tests for mapi/providers/_provider.py."""
import pytest
from mapi.exceptions import MapiException
from mapi.providers import (
TMDb,
TVDb,
has_provider,
has_provider_support,
provider_factory,
)
def test_has_provider__true():
assert has_provider("tmdb") is True
as... |
import pygame
import pygame.draw
from . import ptext
from .rect import RECT_CLASSES
from . import loaders
def round_pos(pos):
"""Round a tuple position so it can be used for drawing."""
x, y = pos
return round(x), round(y)
def make_color(arg):
if isinstance(arg, tuple):
return arg
return... |
#!/usr/bin/env python
"""MediaCrush manage.
Usage:
mcmanage.py database clear
mcmanage.py database sync
mcmanage.py admin list
mcmanage.py admin add <pwhash>
mcmanage.py admin delete <pwhash>
mcmanage.py report show
mcmanage.py report email
mcmanage.py files delete <hash>
mcmanage.p... |
"""Test UPnP/IGD config flow."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import ssdp
from homeassistant.components.upnp.const import (
CONFIG_ENTRY_HOSTNAME,
CONFIG_ENTRY_SCAN_INTERVAL,
... |
"""Test for graphics things that don't really deserve there own test module.
XXX Right now this test occasionally fails with a trace like:
File "/usr/local/lib/python2.1/site-packages/reportlab/graphics/
charts/lineplots.py", line 182, in calcPositions
datum = self.data[rowNo][colNo] # x,y value
IndexError: list ... |
import Biskit.tools as T
import Biskit.mathUtils as MaU
from Biskit import TrajCluster, EnsembleTraj, PCRModel, molUtils
from Biskit.Dock import hexTools
from Biskit.EnsembleTraj import traj2ensemble
import numpy.oldnumeric as N
import os.path
import copy, sys
def _use():
print """
selectModels: Select non-redund... |
"""This module is for parsing and conversion functions that needs
objects from both music library and music service data structures
"""
import logging
from urllib.parse import urlparse
from .xml import XML, ns_tag
from .data_structures import didl_class_to_soco_class
from .exceptions import DIDLMetadataError
from .... |
#!/usr/bin/env python3
from os import environ
import connexion
import logging
from google.cloud import logging as glogging
from google.cloud.logging.handlers.handlers import EXCLUDED_LOGGER_DEFAULTS
from oca.encoder import JSONEncoder
from oca.environment import PORT, DEBUG
all_excluded_loggers = list(EXCLUDED_LOGGE... |
import os
from tests.helpers import get_free_port
class Config(object):
BASEDIR = os.path.dirname(os.path.realpath(__file__))
PORT = get_free_port()
# PostgreSQL dbname
DATABASE = "postgresql://vmmaster:vmmaster@localhost/vmmaster_db"
ENDPOINT_THREADPOOL_PROCESSES = 1
# screenshots
SCREE... |
"""Zenodo access request dump functions."""
from __future__ import absolute_import, print_function
from invenio_migrator.legacy.utils import dt2iso_or_empty
def get(*args, **kwargs):
"""Get users."""
from zenodo.modules.accessrequests.models import AccessRequest
q = AccessRequest.query
return q.coun... |
# this example shows how to append new calculated results to an already
# existing cmr file, illustrated for calculation of PBE energy on LDA density
import os
import cmr
# set True in order to use cmr in parallel jobs!
cmr.set_ase_parallel(enable=True)
from ase.structure import molecule
from ase.io import read, wri... |
"""Trace support for automation."""
from __future__ import annotations
from contextlib import contextmanager
from typing import Any
from homeassistant.components.trace import ActionTrace, async_store_trace
from homeassistant.components.trace.const import CONF_STORED_TRACES
from homeassistant.core import Context
# my... |
"""
Make sure that Pipe and Pipeline classes work
TODO: Make below code work
if not len_pipe.has_next():
break
"""
from django.test import override_settings
from django.test import TestCase
from ozpcenter.scripts import sample_data_generator as data_gen
from ozpcenter.recommend import recommend_utils
from ozpcent... |
""" Joblib is a set of tools to provide **lightweight pipelining in
Python**. In particular, joblib offers:
1. transparent disk-caching of the output values and lazy re-evaluation
(memoize pattern)
2. easy simple parallel computing
3. logging and tracing of the execution
Joblib is optimized to be **fast*... |
import sys
import unittest2
from PyQt5.Qt import QApplication
from alignak_app.utils.config import settings
from alignak_app.backend.datamanager import data_manager
from alignak_app.items.service import Service
from alignak_app.qobjects.service.tree_item import ServiceTreeItem
class TestServiceTreeItem(unittest2.T... |
"""
http://arxiv.org/pdf/0710.1435.pdf
"""
import numpy as np
from scipy.linalg import hadamard
def sampling_matrix(n, r):
sample_indices = np.random.choice(n, r)
S = np.zeros((n, r))
scaling_factor = np.sqrt(n/r)
for i, index in enumerate(sample_indices):
S[index][i] = scaling_factor
retu... |
# -*- coding: utf-8 -*-
"""The UserAssist Windows Registry event formatter."""
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class UserAssistWindowsRegistryEventFormatter(
interface.ConditionalEventFormatter):
"""Formatter for an UserAssist Windows Reg... |
import csv
import json
from datetime import datetime
from pkg_resources import resource_filename
from nupic.engine import Network
from nupic.encoders import DateEncoder
def createNetwork():
network = Network()
#
# Sensors
#
# C++
consumptionSensor = network.addRegion('consumptionSensor', 'ScalarSensor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('latest_tweets', '0007_tweet_html'),
]
operations = [
migrations.CreateModel(
name='Photo',
fields=[
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
# NB(zundel): these definitions are a part of the source from https://github.com/pantsbuild/pants
from pants.backend.jvm.targets.exportable_j... |
from __future__ import absolute_import
from django.db import router, transaction, DataError, connections
from sentry.db.models import (
Model,
BoundedPositiveIntegerField,
BoundedBigIntegerField,
FlexibleForeignKey,
sane_repr,
)
from sentry.tagstore.query import TagStoreManager
class GroupTagKey... |
"""Tests for Estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.estimators._sklearn import mean_squared_error
def boston_input_fn():
bosto... |
"""
lora_gateway
=====
Simulates a LoraWAN gateway (e.g. from The Things Network)
Configurable parameters::
{
}
Device properties created::
{
}
"""
import random
import logging
import time
from .device import Device
import device_factory
MINUTES = 60
HOURS = MINUTES * 60
DAYS = HOURS * 24
NETWOR... |
from subprocess import call
from os import path
import hitchpostgres
import hitchselenium
import hitchpython
import hitchserve
import hitchredis
import hitchtest
import hitchsmtp
# Get directory above this file
PROJECT_DIRECTORY = path.abspath(path.join(path.dirname(__file__), '..'))
class ExecutionEngine(hitchtest... |
# -*- coding: utf-8 -*-
# legacy distutils
from distutils.core import setup
# try the new one
try:
from setuptools import setup
except:
pass
long_description = open('README.md').read()
setup(name='docker-links-python',
version='0.1.0',
description='A helper for parsing Docker link environment var... |
# -*- coding: utf-8 -*-
import re
from pyload.core.utils import seconds
from ..base.multi_downloader import MultiDownloader
class HighWayMe(MultiDownloader):
__name__ = "HighWayMe"
__type__ = "downloader"
__version__ = "0.24"
__status__ = "testing"
__pyload_version__ = "0.5"
__pattern__ =... |
from datacompressor import DataCompressor
from imageeditor import ImageEditor
from graphicbank import GraphicBank
from level import LevelHeader, Level
class LevelEditor():
TILE_WIDTH = 8
TILE_HEIGHT = 8
EDITORTILESET_WIDTH = 16 * TILE_WIDTH
EDITORTILESET_HEIGHT = 64 * TILE_HEIGHT
EDITORCANVAS_WIDTH... |
"""A streaming word-counting workflow.
"""
from __future__ import absolute_import
import argparse
import logging
from past.builtins import unicode
import apache_beam as beam
import apache_beam.transforms.window as window
from apache_beam.examples.wordcount import WordExtractingDoFn
from apache_beam.options.pipeline... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @file generators
# @author kaka_ace <<EMAIL>>
# @date Mar 04 2015
# @breif
#
import sys
if sys.version_info < (3, 0):
range = xrange
else:
from functools import reduce
import math
from contextlib import contextmanager
def _fibonacci_formula(... |
from __future__ import unicode_literals
from flask import render_template
from indico.modules.admin.views import WPAdmin
class WPRoomBookingAdminBase(WPAdmin):
subtitle = u''
def getJSFiles(self):
return WPAdmin.getJSFiles(self) + self._includeJSPackage('Management')
def _getPageContent(self, ... |
class Clinkgw:
"""Class to define the linkgw category structure"""
def __init__( self,name,intercloudGW,account,gwsrc,gwdst,tunnelproto,addressgresrc,addressgredst,prefix,authenticationkey,endpointsrc,endpointdst,state ):
"""Constructor of the class"""
self.name = name
self.intercloudGW = intercloudGW
self.ac... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from rango.models import Category, Page
from rango.forms import CategoryForm, PageForm, UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpRespo... |
# -*- coding: utf-8 -*-
""" Setup for development db """
def setup():
records = 0
tables = 0
# TODO: General app setup
accounts = list()
return dict(message=T("Done"), records = records, tables = tables)
def options():
the_options = db(db.option).select()
return dict(options = the_optio... |
import re
def merge_configuration_spaces(*args, **kwargs):
"""
Convenience function to merge several algorithms with their respective config spaces into a single one.
Using pySMAC to optimize the parameters of a single function/algorithm
is a very important usecase, but finding the best algorithm and its
config... |
import pytest
import uuid
from django.core.exceptions import ValidationError
from django.test.utils import override_settings
from unittest import mock
from olympia.amo.tests import TestCase, addon_factory
from olympia.constants.scanners import (
ABORTED,
ABORTING,
COMPLETED,
CUSTOMS,
FALSE_POSITIV... |
import traceback
import logging
import signal
import random
from time import time
from .utils import RunFlag, task_fmt
log = logging.getLogger(__name__)
class StopWorker(Exception):
pass
class Worker(object):
def __init__(self, manager, lifetime=None, task_timeout=None):
self.manager = manager
... |
"""Example dataflow pipeline for preparing image training data.
The tool requires two main input files:
'input' - URI to csv file, using format:
gs://image_uri1,labela,labelb,labelc
gs://image_uri2,labela,labeld
...
'input_dict' - URI to a text file listing all labels (one label per line):
labela
labelb
labelc
The ... |
# -*- coding: utf-8
from __future__ import unicode_literals
from decimal import Decimal, getcontext
import math
try:
import cPickle as pickle
except ImportError:
import pickle
import json
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.utils.six import text_type... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.