code
stringlengths
1
199k
''' Some tests for the documenting decorator and support functions ''' from __future__ import division, print_function, absolute_import import sys import pytest from numpy.testing import assert_equal from scipy.misc import doccer DOCSTRINGS_STRIPPED = sys.flags.optimize > 1 docstring = \ """Docstring %(strtest1)s ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: manageiq_alerts short_description: Configuration of alerts in Man...
class A(B): pass class A(object): pass class A(x.y()): pass class A(B, C): pass
from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.soft_extension_authorizer('compute', 'server_usage') class ServerUsageCo...
import pytest from tests.support.asserts import assert_success """ Tests that WebDriver can transcend site origins. Many modern browsers impose strict cross-origin checks, and WebDriver should be able to transcend these. Although an implementation detail, certain browsers also enforce process isolation based on site or...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcpubsub_info version_added: "2.3" short_description: List Topi...
import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( display_for_field, display_for_value, label_for_field, lookup_field, ) from django.contrib.admin.views.main import ( ALL_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR, ) from django.cor...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('email_marketing', '0003_auto_20160715_1145'), ] operations = [ migrations.AddField( model_name='emailmarketingconfiguration', nam...
import requests import sys import urllib from requests.auth import HTTPBasicAuth if len(sys.argv) != 5: print "usage: verify-topo-links onos-node cluster-id first-index last-index" sys.exit(1) node = sys.argv[1] cluster = sys.argv[2] first = int(sys.argv[3]) last = int(sys.argv[4]) found = 0 topoRequest = reque...
from __future__ import division, absolute_import, print_function import sys from itertools import product import numpy as np from numpy.core import zeros, float64 from numpy.testing import dec, TestCase, assert_almost_equal, assert_, \ assert_raises, assert_array_equal, assert_allclose, assert_equal from numpy.cor...
import datetime import logging from google.appengine.ext import db as models import appengine_django.models as aed_models from oauth import oauth from django.conf import settings from django.db import models as django_models from common import profile from common import properties from common import util import setting...
def execute(): import webnotes entries = webnotes.conn.sql("""select voucher_type, voucher_no from `tabGL Entry` group by voucher_type, voucher_no""", as_dict=1) for entry in entries: try: cancelled_voucher = webnotes.conn.sql("""select name from `tab%s` where name = %s and docstatus=2""" % (entry['vouche...
from __future__ import unicode_literals import webnotes def execute(): try: webnotes.conn.sql("""delete from `tabSearch Criteria` where ifnull(standard, 'No') = 'Yes'""") except Exception, e: pass
"""Mycroft AI notification platform.""" import logging from mycroftapi import MycroftAPI from homeassistant.components.notify import BaseNotificationService _LOGGER = logging.getLogger(__name__) def get_service(hass, config, discovery_info=None): """Get the Mycroft notification service.""" return MycroftNotific...
from compiled_file_system import CompiledFileSystem from file_system import FileNotFoundError class ChainedCompiledFileSystem(object): ''' A CompiledFileSystem implementation that fetches data from a chain of CompiledFileSystems that have different file systems and separate cache namespaces. The rules for the c...
from pox.core import core from pox.lib.revent import * topology = core.components['topology'] def autobinds_correctly(): topology.listenTo(core) return True if not autobinds_correctly(): raise AssertionError("Did no autobind correctly")
'''Demonstrates how to handle a platform-specific event not defined in pyglet by subclassing Window. This is not for the faint-hearted! A message will be printed to stdout when the following events are caught: - On Mac OS X, the window drag region is clicked. - On Windows, the display resolution is changed. - On Li...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: edgeos_facts version_added: "2.5" author: - Nathaniel Case ...
from __future__ import absolute_import from django import template from django.utils.unittest import TestCase from .templatetags import custom class CustomFilterTests(TestCase): def test_filter(self): t = template.Template("{% load custom %}{{ string|trim:5 }}") self.assertEqual( t.rende...
""" Generate artificial datasets for the multi-step prediction experiments """ import os import random import datetime from optparse import OptionParser from nupic.data.file_record_stream import FileRecordStream def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3, numRepeats=...
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.rl.learners.learner import Learner class MetaLearner(Learner): """ Learners that make use of other Learners, or learn how to learn. """
import random import string from samba.auth import system_session from samba.samdb import SamDB from cStringIO import StringIO from samba.netcmd.main import cmd_sambatool import samba.tests class SambaToolCmdTest(samba.tests.TestCaseInTempDir): def getSamDB(self, *argv): """a convenience function to get a s...
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from django.template imp...
import json import logging from lxml import etree from xmodule.capa_module import ComplexEncoder from xmodule.progress import Progress from xmodule.stringify import stringify_children import openendedchild from .combined_open_ended_rubric import CombinedOpenEndedRubric log = logging.getLogger("edx.courseware") class Se...
"""Custom op used by periodic_resample.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.periodic_resample.python.ops.periodic_resample_op import periodic_resample from tensorflow.python.util.all_util import remove_undocumented _allo...
from __future__ import unicode_literals from .common import InfoExtractor class HarkIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?hark\.com/clips/(?P<id>.+?)-.+' _TEST = { 'url': 'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-may-23-2013', ...
from ansible.modules.storage.netapp.netapp_e_auditlog import AuditLog from units.modules.utils import AnsibleFailJson, ModuleTestCase, set_module_args __metaclass__ = type from units.compat import mock class AuditLogTests(ModuleTestCase): REQUIRED_PARAMS = {'api_username': 'rw', 'api_password...
"""Utility to compare (Numpy) version strings. The NumpyVersion class allows properly comparing numpy version strings. The LooseVersion and StrictVersion classes that distutils provides don't work; they don't recognize anything like alpha/beta/rc/dev versions. """ import re from scipy._lib.six import string_types __all...
def foo(a): pass foo(1)
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_urllib_request class VideoMegaIE(InfoExtractor): _VALID_URL = r'(?:videomega:|https?://(?:www\.)?videomega\.tv/(?:(?:view|iframe|cdn)\.php)?\?ref=)(?P<id>[A-Za-z0-9]+)' _TESTS = [{ 'url': 'htt...
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_array_almost_equal from scipy.sparse.csgraph import breadth_first_tree, depth_first_tree,\ csgraph_to_dense, csgraph_from_dense def test_graph_breadth_first(): csgraph = np.array([[0, 1, 2, 0, 0]...
from test_support import * prove_all ()
""" An object that makes some of the attributes of your class persistent, pickling them and lazily writing them to a file. """ import os import cPickle as pickle import warnings import fileutil import nummedobj import twistedutil from twisted.python import log class PickleSaver(nummedobj.NummedObj): """ This ma...
from binascii import hexlify class HashAlgo: """A generic class for an abstract cryptographic hash algorithm. :undocumented: block_size """ #: The size of the resulting hash in bytes. digest_size = None #: The internal block size of the hash algorithm in bytes. block_size = None def __in...
"""Newton-CG trust-region optimization.""" from __future__ import division, print_function, absolute_import import math import numpy as np import scipy.linalg from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) __all__ = [] def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hessp=Non...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from nose import tools from ansible.compat.tests import unittest from ansible.parsing.splitter import unquote class TestUnquote: UNQUOTE_DATA = ( (u'1', u'1'), (u'\'1\'', u'1'), (u'"1"', u'1')...
""" werkzeug.contrib.wrappers ~~~~~~~~~~~~~~~~~~~~~~~~~ Extra wrappers or mixins contributed by the community. These wrappers can be mixed in into request objects to add extra functionality. Example:: from werkzeug.wrappers import Request as RequestBase from werkzeug.contrib.wrapper...
class Project(object): def __init__(self, name, start, end): self.name = name self.start = start self.end = end def __repr__(self): return "Project '%s from %s to %s" % ( self.name, self.start.isoformat(), self.end.isoformat() )
""" Performs management commands for the scheduler app """ import hashlib from flask.ext.script import Manager from sqlalchemy import exc from src import routes from src import models from src import scheduler scheduler.app.config.from_object(scheduler.ConfigDevelopment) manager = Manager(scheduler.app) def add_coaches...
""" Script to check recently uploaded files. This script checks if a file description is present and if there are other problems in the image's description. This script will have to be configured for each language. Please submit translations as addition to the Pywikibot framework. Everything that needs customisation is...
from django.db import connection from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.generics import RetrieveAPIView from jarbas.core.models import Company from jarbas.core.serializers import CompanySerializer from jarbas.chamber_of_deputies.serializers import format_...
""" Created on 17 Sep 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import time from scs_core.sys.timeout import Timeout timeout = Timeout(5) print(timeout) print("-") try: with timeout: time.sleep(10) print("slept") except TimeoutError: print("TimeoutError") finally: p...
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int O(logn) """ low = 0 high = len(nums) - 1 if target <= nums[low]: return low if target > nums[high]: ...
import os from carton.cart import Cart from django.contrib import messages from django.shortcuts import render, redirect from django.template.response import TemplateResponse from django.views.generic import View from authentication.views import LoginRequiredMixin from deals.models import Deal from .models import UserS...
from django.views.generic import ListView from django.http import HttpResponse from .models import Job from geoq.maps.models import FeatureType from django.shortcuts import get_object_or_404 from datetime import datetime from pytz import timezone from webcolors import name_to_hex, normalize_hex from xml.sax.saxutils im...
try: set except NameError: from sets import Set as set from django.core.paginator import Paginator, Page, InvalidPage from django.db.models import F from django.http import Http404 from coffin import template from jinja2 import nodes from jinja2.ext import Extension from jinja2.exceptions import TemplateSyntaxE...
""" General descrition of your module here. """ from functools import partial from maya import OpenMaya from maya import OpenMayaUI from maya import cmds from PySide import QtCore from PySide import QtGui from shiboken import wrapInstance from shiboken import getCppPointer class RbfSettings(object): """ ...
import cupy x = cupy.array([1, 3, 2]) expected = x.sort() cupy.cuda.Device().synchronize() stream = cupy.cuda.stream.Stream() with stream: y = x.sort() stream.synchronize() cupy.testing.assert_array_equal(y, expected) stream = cupy.cuda.stream.Stream() stream.use() y = x.sort() stream.synchronize() cupy.testing.ass...
__author__ = 'glow' import requests import json server = "http://fhir.careevolution.com/apitest/fhir" client = requests.Session() response = client.get(server + "/Patient?_id=23&_format=application/json+fhir") print(response) print(response.json())
from __future__ import with_statement import sys from xml.sax import saxutils from keyword import kwlist as PYTHON_KWORD_LIST is_py2 = sys.version[0] == '2' if is_py2: from StringIO import StringIO else: from io import StringIO __all__ = ['Builder', 'Element'] __license__ = 'BSD' __version__ = '0.2.1' __author_...
import matplotlib import matplotlib.pyplot as plt matplotlib.rc('text', usetex=True) def setfont(font): return r'\font\a %s at 14pt\a ' % font for y, font, text in zip(range(5), ['ptmr8r', 'ptmri8r', 'ptmro8r', 'ptmr8rn', 'ptmrr8re'], ['Nimbus Roman No9 L ' + x for ...
from typing import Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_straight_...
import logging import os import sys import tkinter from tkinter import ttk sys.path.append('../..') import cv2 from src.image.imnp import ImageNP from src.support.tkconvert import TkConverter from src.view.template import TkViewer from src.view.tkfonts import TkFonts from src.view.tkframe import TkFrame, TkLabelFrame f...
from utils.api_factory import ApiFactory api = ApiFactory.get_instance() if __name__ == '__main__': api.run(host='0.0.0.0', port=8000)
import json, io, re, requests from bs4 import BeautifulSoup from datetime import datetime def get_datasets(url): r = requests.get(url.format(0)) soup = BeautifulSoup(r.text) href = soup.select('#block-system-main a')[-1]['href'] last_page = int(re.match(r'.*page=(.*)', href).group(1)) for page in ra...
import os import socket import datetime import random import re from django import forms from django import urls from django.db import models from django.db.models.signals import pre_save from .unique_slugify import unique_slugify from .titlecase import titlecase from functools import reduce def time2s(time): """ g...
""" Created on Wed Nov 25 12:14:03 2015 @author: ktritz """ from __future__ import print_function from builtins import str, range import inspect import types from collections.abc import MutableMapping from .container import containerClassFactory class Shot(MutableMapping): # _modules = None _logbook = None ...
import unittest from pyparsing import ParseException from cwr.grammar.field import basic """ Tests for Table/List Lookup (L) fields. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestLookupName(unittest.TestCase): def test_name_default(self): """ T...
import numpy as np from numba import njit as jit @jit def _kepler_equation(E, M, ecc): return E_to_M(E, ecc) - M @jit def _kepler_equation_prime(E, M, ecc): return 1 - ecc * np.cos(E) @jit def _kepler_equation_hyper(F, M, ecc): return F_to_M(F, ecc) - M @jit def _kepler_equation_prime_hyper(F, M, ecc): ...
import numpy as np def e_greedy(estimates, epsilon): numBandits, numArms = estimates.shape explore = np.zeros(numBandits) explore[np.random.random(numBandits) <= epsilon] = 1 arm = np.argmax(estimates, axis=1) arm[explore == 1] = np.random.randint(0, numArms, np.count_nonzero(explore)) return ar...
import time from dbapi.DoubanAPI import DoubanAPI class GroupAPI: def __init__(self): self.api = DoubanAPI(flush=False) self._applied = {} self._users = {} def run(self): self.api.flush() groups = self.api.group.list_joined_groups()['results'] for group in groups:...
"""Various helpers for X-ray analysis that rely on CIAO tools. """ from __future__ import absolute_import, division, print_function, unicode_literals __all__ = str(''' get_region_area count_events compute_bgband simple_srcflux ''').split () def get_region_area (env, evtpath, region): with env.slurp (argv=['dmlist',...
from checkpy.assertlib.basic import *
import json, math, sys, string, random, subprocess, serial from time import localtime, strftime, clock, time # for timestamping packets import time import hashlib #for checksum purposes import mysql.connector # mysql database import getpass import urllib2 import requests sys.path.append('/usr/lib/python2.7/dist-package...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "anigma1.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is real...
from kivy.uix.floatlayout import FloatLayout from kivy.properties import NumericProperty, ObjectProperty, BoundedNumericProperty, ListProperty from .node import Node from math import sqrt class HexCanvas(FloatLayout): last_node = ObjectProperty(None, allownone=True) grid = ObjectProperty([]) row_count = Bou...
import os, sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.develop") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from mnist import MNIST import numpy as np from thirdparty import log_mvnpdf, log_mvnpdf_diag data = MNIST('./data/mnist') data.load_training() data.load_testing() train = np.array(data.train_images)/255.0 test = np.array(np.array(data.test_images)/255.0) dataset = {i: [] for i in range(10) } for it, x in enumerate(dat...
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns from provider import StackExchangeProvider urlpatterns = default_urlpatterns(StackExchangeProvider)
from __future__ import print_function from __future__ import unicode_literals import time from netmiko.ssh_connection import BaseSSHConnection from netmiko.netmiko_globals import MAX_BUFFER from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException import paramiko import socket class Cisc...
import threading import time from utils import fn_timer from multiprocessing.dummy import Pool import requests from utils import urls def music(name): print 'I am listening to music {0}'.format(name) time.sleep(1) def movie(name): print 'I am watching movie {0}'.format(name) time.sleep(5) @fn_timer def ...
import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plot import matplotlib.pylab from matplotlib.backends.backend_pdf import PdfPages import re def drawPlots(data,plotObj,name,yLabel,position): drawing = plotObj.add_subplot(position,1,position) drawing.set_ylabel(yLabel, fonts...
import argparse import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.feature_selection import RFECV from sklearn.ensemble import RandomForestClassifier from beveridge.models import ModelStorage import pickle parser = argparse.ArgumentParser(description="Create model from CSV stats data."...
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binne...
from test_framework.test_framework import StardustTestFramework from test_framework.util import * class MempoolSpendCoinbaseTest(StardustTestFramework): def __init__(self): super().__init__() self.num_nodes = 1 self.setup_clean_chain = False def setup_network(self): # Just need o...
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), ('product', '0009_auto_20170323_1823')...
import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file) def get_build(self): for segment in self.elffile.iter_segments(): ...
from urllib.parse import urlparse from django.conf import settings from django.core.files.storage import default_storage from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from api.applications.models import ShowApplicationSettings from api.shows.models import upload_to_show_cover...
from pygecko.multiprocessing import geckopy from pygecko.multiprocessing import GeckoSimpleProcess from pygecko.transport.protocols import MsgPack, MsgPackCustom import time from math import cos, pi def pub(**kwargs): geckopy.init_node(**kwargs) rate = geckopy.Rate(2) p = geckopy.pubBinderTCP("local", "bob"...
from shinymud.lib.world import World import json world = World.get_world() def to_bool(val): """Take a string representation of true or false and convert it to a boolean value. Returns a boolean value or None, if no corresponding boolean value exists. """ bool_states = {'true': True, 'false': False, ...
GPIO_HUB_RST_N = 30 GPIO_UBLOX_RST_N = 32 GPIO_UBLOX_SAFEBOOT_N = 33 GPIO_UBLOX_PWR_EN = 34 GPIO_STM_RST_N = 124 GPIO_STM_BOOT0 = 134 def gpio_init(pin, output): try: with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f: f.write(b"out" if output else b"in") except Exception as e: print(f"Faile...
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk import os from subprocess import call, Popen, PIPE, STDOUT class GtkPassWindow(Gtk.Window): def __init__(self): self.search_text = '' self.search_result_text = '' self.get_pass_path() self.build_gui() ...
import re from operator import itemgetter ref_file = open('../../../data/RNA-seq_miR-124_miR-155_transfected_HeLa/gene_exp_miR-155_overexpression_RefSeq_Rep_isoforms.diff','r') input_file = open('../../../result/mirage_output_rev_seed_miR-155_vs_RefSeq_NM_2015-07-30.txt','r') output_file = open('../../../result/mirage_...
""" Created on Tue Jul 11 20:47:53 2017 @author: fernando """ import pandas as pd import matplotlib import matplotlib.pyplot as plt plt.style.use('ggplot') df = pd.read_csv("/home/fernando/CoursePythonDS/DAT210x/Module3/Datasets/wheat.data") print df.describe() df[df.groove>5].asymmetry.plot.hist(alpha=0.3, normed=True...
import numpy as np from tfs.core.util import run_once_for_each_obj from tfs.core.initializer import DefaultInit from tfs.core.loss import DefaultLoss from tfs.core.regularizers import DefaultRegularizer from tfs.core.monitor import DefaultMonitor from tfs.core.optimizer import DefaultOptimizer from tfs.core.layer impor...
""" """ import unittest import arcpy from gsfarc.test import config class TestDataTypeStringArray(unittest.TestCase): """Tests the string array task datatype""" @classmethod def setUpClass(cls): config.setup_idl_toolbox('test_datatype_stringarray','qa_idltaskengine_datatype_stringarray') @classm...
import numpy as np from sklearn import datasets from sklearn.decomposition import PCA, RandomizedPCA import matplotlib.pyplot as plt digits = datasets.load_digits() print(digits) print(digits.keys) print(digits.data) print(digits.target) print(digits.DESCR) digits_data = digits.data print(digits_data.shape) digits_targ...
import os import datetime import logging ORDER = 999 POSTS_PATH = 'posts/' POSTS = [] from django.template import Context from django.template.loader import get_template from django.template.loader_tags import BlockNode, ExtendsNode def getNode(template, context=Context(), name='subject'): """ Get django block conten...
from __future__ import print_function import os import sys import json if __name__=='__main__': SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(SRC_ROOT) from datetime import datetime import requests from jinja2 import Template from jinja2 import Environment, PackageLoader...
import pile import matplotlib.pyplot as plt import time import random x,y = [],[] for i in range(0,10): p = 10 ** i print(i) start = time.time() pile.pile(p) final = time.time() delta = final - start x.append(p) y.append(delta) plt.plot(x,y) plt.ylabel("The time taken to compute the pile...
import os, sys PATH = os.path.join(os.path.dirname(__file__), '..') sys.path += [ os.path.join(PATH, 'project/apps'), os.path.join(PATH, 'project'), os.path.join(PATH, '..'), PATH] os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.production' import django.core.handlers.wsgi application = django.core.handler...
from django.core.urlresolvers import reverse from django.test import TestCase as DjangoTestCase from blognajd.models import Story, SiteSettings from blognajd.sitemaps import StaticSitemap, StoriesSitemap class StaticSitemap1TestCase(DjangoTestCase): fixtures = ['sitesettings_tests.json'] def test_staticsitemap_...
import subprocess import os import time import platform import glob import shutil import csbuild from csbuild import log csbuild.Toolchain("gcc").Compiler().SetCppStandard("c++11") csbuild.Toolchain("gcc").SetCxxCommand("clang++") csbuild.Toolchain("gcc").Compiler().AddWarnFlags("all", "extra", "ctor-dtor-privacy", "ov...
from __future__ import absolute_import, print_function, division import time import unittest from gruvi.http import HttpProtocol, HttpServer, HttpClient from support import PerformanceTest, MockTransport def hello_app(environ, start_response): headers = [('Content-Type', 'text/plain')] start_response('200 OK', ...
import tree_utils as tu import w_tree_utils as wtu import os import sys import numpy as np import random from math import sqrt __pid__ = 0 __prefix__ = "NNI_" def randNNIwalk(daf,size,steps,runs,seed,weighted = False): global __pid__ global __prefix__ #set the seed random.seed(seed) np.random.seed(s...
import cv2 # device number "0" cap = cv2.VideoCapture(0) while(True): # Capture a frame ret, frame = cap.read() # show on display cv2.imshow('frame',frame) # waiting for keyboard input key = cv2.waitKey(1) & 0xFF # Exit if "q" pressed if key == ord('q'): break # Save if "s" pressed if key == ord('s'): pa...
import importlib from django.conf import settings from django.views import View class BaseView(View): """后台管理基类""" def __init__(self): self.context = {} self.context["path"] = {} def dispatch(self,request,*args,**kwargs): _path = request.path_info.split("/")[1:] self.context[...
import _plotly_utils.basevalidators class SymmetricValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name="symmetric", parent_name="scatter3d.error_y", **kwargs ): super(SymmetricValidator, self).__init__( plotly_name=plotly_name, parent...
from flask import request, render_template from flask.ext.login import current_user, login_user from mysite.weibo import Client from mysite import app, db from mysite.models import Wuser, User from . import weibo @weibo.route('/oauthreturn') def oauthreturn(): code = request.args.get('code', '') if code: client = C...
""" WSGI config for billboards 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_APPLICATION`...