code
stringlengths
1
199k
import atexit import importlib import os.path import shutil import sys import tempfile import traceback from pkg_resources import resource_filename from mako.lookup import TemplateLookup from django.conf import settings def mkdtemp_clean(suffix="", prefix="tmp", dir=None): """Just like mkdtemp, but the directory wi...
"""Tests for static_replace""" import re from six import BytesIO from six.moves.urllib.parse import parse_qsl, urlparse, urlunparse import ddt import pytest from django.test import override_settings from django.utils.http import urlencode, urlquote from mock import Mock, patch from opaque_keys.edx.keys import CourseKey...
from hera import api from hera import apimiddleware from hera import models from hera import settings from hera import util import bottle import base64 from django.db.models import Q from django.core.exceptions import PermissionDenied from bottle import request, response, default_app default_app.push() @bottle.get('/cl...
from django.contrib import admin from moveon.models import * admin.site.register(Company) admin.site.register(Transport) admin.site.register(Line) admin.site.register(Route) admin.site.register(RoutePoint) admin.site.register(TimeTable) admin.site.register(Time) admin.site.register(Stretch) admin.site.register(Node) ad...
from openerp.osv import orm, fields class Purchase(orm.Model): _inherit = 'purchase.order' _columns = { 'department_id': fields.many2one('hr.department', 'Department'), } def _get_department(self, cr, uid, ids, context=None): employee_obj = self.pool.get('hr.employee') depart...
"""Information. + Module versions. + Help descriptions. + Check for update function. """ __author__ = "Yuan Chang" __copyright__ = "Copyright (C) 2016-2019" __license__ = "AGPL" __email__ = "pyslvs@gmail.com" from sys import version_info as _vi from platform import system, release, machine, python_compiler from argpars...
""" Test the hot dependencies arbiter module. """ import os, time from shinken_test import unittest, ShinkenTest, time_hacker time_hacker.set_real_time() from shinken.objects.module import Module from shinken.modulesctx import modulesctx hot_dependencies_arbiter = modulesctx.get_module('hot_dependencies') Hot_dependenc...
""" Tests for Course Blocks forms """ from urllib import urlencode import ddt from django.http import Http404, QueryDict from opaque_keys.edx.locator import CourseLocator from rest_framework.exceptions import PermissionDenied from openedx.core.djangoapps.util.test_forms import FormTestMixin from student.models import C...
""" Minimal Django settings for tests of common/lib. Required in Django 1.9+ due to imports of models in stock Django apps. """ import sys import tempfile from django.utils.translation import ugettext_lazy as _ from path import Path REPO_ROOT = Path(__file__).abspath().dirname().dirname().dirname() # /edx-platform/ sy...
"""Testing the backwards-compatibility shims.""" from django.test import TestCase from apps.subtitles.compat import ( subtitlelanguage_is_translation, subtitlelanguage_original_language_code ) from apps.subtitles.tests.utils import make_video, make_sl class TestTranslationShims(TestCase): def setUp(self): ...
from __future__ import unicode_literals from django.db import migrations from reference.migrations.utils.uuid import set_uuid_field class Migration(migrations.Migration): dependencies = [ ('reference', '0006_add_uuid_field'), ] operations = [ migrations.RunPython(set_uuid_field), ]
workflow = context.portal_workflow if workflow.getInfoFor(context, 'cancellation_state', 'active') == "cancelled": return False if context.portal_type in ("Analysis", "ReferenceAnalysis", "DuplicateAnalysis"): if not context.getAttachment(): service ...
""" This module provide object serialization for Alignak objects. It basically converts objects to json """ import sys import json try: from collections.abc import Callable except ImportError: from collections import Callable from alignak.property import NONE_OBJECT def default_serialize(obj): """JSON seria...
from unipath import Path from lino.utils.pythontest import TestCase class LinoTestCase(TestCase): django_settings_module = "lino_book.projects.min9.settings" project_root = Path(__file__).parent.parent class BlogTests(LinoTestCase): def test_all(self): self.run_simple_doctests(""" docs/blog/...
""" https://www.shadowserver.org/wiki/pmwiki.php/Services/Botnet-Drone-Hadoop Timestamp Timestamp the IP was seen in UTC+0 ip The IP of the device in question port Source port of the IP connection asn ASN where the drone resides geo Country where the drone resides region State or province from the Geo city City ...
import copy from ereuse_devicehub.resources.event.device.settings import place, EventWithDevices, \ EventSubSettingsMultipleDevices, materialized_components class Locate(EventWithDevices): place = place components = materialized_components Locate.geo = copy.deepcopy(Locate.geo) Locate.geo['excludes'] = 'pla...
""" Views for the announcements app. """ from django.http.response import Http404 from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext_lazy as _ from django.template.response import TemplateResponse from apps.paginator.shortcut import (update_context_for_pagination, ...
from tag_base import TagBase class TagDestinatario(TagBase): def __init__(self, nome, endereco, telefone=False, celular=False, email=''): self.nome = nome self.endereco = endereco self.celular = celular self.email = email if telefone: telefone = telefone.replace('...
import json from inbox.models import Namespace from inbox.sqlalchemy_ext.util import generate_public_id from inbox.api.validation import noop_event_update from tests.util.base import db, api_client, calendar, add_fake_event def test_namespace_id_validation(api_client, db, default_namespace): actual_namespace_id, = ...
""" General utility functions. """ import os, sys import shutil import time, re from subprocess import Popen, PIPE from urllib2 import urlopen, HTTPError import htmlentitydefs from objavi import config def init_log(logname='objavi'): """Try to redirect stderr to the log file. If it doesn't work, leave stderr a...
from jchart import Chart from jchart.config import Axes, DataSet, rgba, ScaleLabel, Legend, Title import seaborn as sns from math import * from .models import * import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def Command_String_from_Chart(chart): try: html = chart.as_html...
""" Instance app models - Open EdX Instance and AppServer models """ import logging from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.functional impo...
"""pdf_print_service URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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') ...
from openerp.osv import fields, orm class program_result_country_role(orm.Model): _name = 'program.result.country.role' _description = 'Target Country Role' _columns = { 'name': fields.char('Name', required=True, select=True), 'active': fields.boolean('Active'), } _defaults = { ...
from odoo import models, fields class EventTrack(models.Model): _inherit = 'event.track' address_id = fields.Many2one( string='Location', comodel_name='res.partner') second_responsible_id = fields.Many2one( string='Assistant', comodel_name='res.partner') def name_get(self): resul...
import sys import numpy as np import essentia.standard as es from essentia import array as esarr sys.path.insert(0, './') from qa_test import * from qa_testevents import QaTestEvents sampleRate = 44100. frameSize = 512 hopSize = 256 minimumDuration = 0.005 # ms idx = 0 previousRegion = None class EssentiaWrap(QaWrappe...
from response_frames import ResponseFrame, response_frame @response_frame(0x08) class CompileInfoFrame(ResponseFrame): @classmethod def matches(cls, payload): return True def decode(self): self.message = self.payload() def __str__(self): return 'CompileInfo({})'.format(''.join(ma...
import json import pytest import subprocess docker_id = subprocess.check_output(["docker-compose", "ps", "-q", "django"]).rstrip() testinfra_hosts = ["docker://{}".format(docker_id.decode('utf-8'))] PSHTT_CLI_...
from openerp import models, api, fields, _ class MgmtsystemNonconformity(models.Model): _name = "mgmtsystem.nonconformity" _description = "Nonconformity" _rec_name = "description" _inherit = ['mail.thread', 'ir.needaction_mixin'] _order = "create_date desc" def _default_stage(self): """R...
from unittest import TestCase import ddt from track import contexts @ddt.ddt class TestContexts(TestCase): COURSE_ID = 'test/course_name/course_run' SPLIT_COURSE_ID = 'course-v1:test+course_name+course_run' ORG_ID = 'test' @ddt.data( (COURSE_ID, ''), (COURSE_ID, '/more/stuff'), (...
""" This module provides date summary blocks for the Course Info page. Each block gives information about a particular course-run-specific date which will be displayed to the user. """ import crum import datetime from babel.dates import format_timedelta from django.conf import settings from django.urls import reverse f...
""" APIs for retrieving, updating, creating, and deleting Individual records """ import logging from seqr.models import Sample, IgvSample, Individual from seqr.views.utils.pedigree_image_utils import update_pedigree_images logger = logging.getLogger(__name__) _SEX_TO_EXPORTED_VALUE = dict(Individual.SEX_LOOKUP) _SEX_TO...
''' Search Architecture: - Have a list of accounts - Create an "overseer" thread - Search Overseer: - Tracks incoming new location values - Tracks "paused state" - During pause or new location will clears current search queue - Starts search_worker threads - Search Worker Threads each: - Have a uniqu...
from unittest import skip from django.test.client import Client from django.core.urlresolvers import reverse from django_fixmystreet.fixmystreet.models import Report, ReportCategory, OrganisationEntity, FMSUser, UserOrganisationMembership, GroupMailConfig from django_fixmystreet.fixmystreet.tests import FMSTestCase fro...
from datetime import datetime import ckan.logic as l from ckanext.meerbusch.helpers import get_date_format def package_create(context, data_dict): temporal_from = data_dict['temporal_coverage-temporal_coverage_from'] temporal_to = data_dict['temporal_coverage-temporal_coverage_to'] role_date_1 = data_dict['...
import unittest import subprocess import os import select import time import json from openerp import sql_db, tools def _exc_info_to_string(err, test): return err class Stream: def __init__(self, file_descriptor): self._file_descriptor = file_descriptor self._buffer = '' def fileno(self): ...
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import UserAccount @admin.register(UserAccount) class UserAccountAdmin(admin.ModelAdmin): def get_user_first_name(self, obj): return obj.user.first_name get_user_first_name.short_description = _(u'first...
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.auth.views import login, password_change from techtips.tips.feeds import TechTipsFeed from techtips.tips.views import (TipListView, TipDetailView, add_tip, profile, edit...
from django.core.management.base import BaseCommand, CommandError from stationspinner.accounting.models import APIUpdate, APICall from stationspinner.character.models import CharacterSheet from stationspinner.corporation.models import CorporationSheet import sys class Command(BaseCommand): args = '<character/corpor...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^planning/(?P<pk>\d+)/?$', views.planning, name='planning'), ]
from logging import getLogger from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from django_geoip.models import IpRange from libs.models import CreateUpdate, ActiveState, ActiveManager logger = getLogger(__name__) class Request(CreateUpdate, ActiveState): """Customers...
MAINTENANCE_HTML = """ <!DOCTYPE html> <html> <head> <title> Maintenance Mode </title> <style> body { background-color:#0F0F0F; padding-top:200px; } .box { margin-left:auto; margin-right:auto; ...
import webapp2 import webapp2_extras.jinja2 import os import logging class Defaults: """ Default configuration values to use in the event that the private configuration module is not available. """ # Default session cookie key. session_cookie_key = '' # Default salt value. salt = '' ...
import Adafruit_BBIO.GPIO as GPIO import sys import os import ProBotConstantsFile import SabertoothFile import PWMFile PWM = PWMFile.PWMClass() Pconst = ProBotConstantsFile.Constants() Sabertooth = SabertoothFile.SabertoothClass() GPIO.setup(Pconst.RedLED, GPIO.OUT) class RestartProgramClass(): def RestartProgramRo...
""" Tests for classes extending Field. """ from mock import Mock import unittest import datetime as dt import pytz import warnings import math import textwrap import itertools from contextlib import contextmanager import ddt from xblock.core import XBlock, Scope from xblock.field_data import DictFieldData from xblock.f...
class MalformedPacketError(ValueError): pass class InsufficientBytesReadError(ValueError): pass
''' magento-integration :copyright: (c) 2013 by Openlabs Technologies & Consulting (P) LTD :license: AGPLv3, see LICENSE for more details ''' import magento_ import country import product import partner import bom import account import sale import currency import wizard
import py.test import hype as he def test_docid(): db = he.Database(str(py.test.ensuretemp('test.db'))) try: doc = he.Document(u'uri') assert doc.is_empty() assert doc.id == -1 db.put_doc(doc) assert doc.id != -1 doc_copy = doc.copy() assert doc_copy.id ==...
"""Unit tests for smartcard.utils This test case can be executed individually, or with all other test cases thru testsuite_framework.py. __author__ = "http://www.gemalto.com" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com This file is part of pyscard. pyscard is free softw...
import sys, subprocess, ConfigParser, platform, os import os import re import time import sys import signal from subprocess import Popen from threading import Thread from subprocess import PIPE import subprocess import platform def DebugN( l, m ): pass def windowskill( pid ): """ replace os.kill on Windows, where ...
import errno import os import re import time from _stbt.config import ConfigurationError def uri_to_power_outlet(uri): remotes = [ (r'none', _NoOutlet), (r'file:(?P<filename>[^:]+)', _FileOutlet), (r'aten:(?P<hostname>[^: ]+):(?P<outlet>[^: ]+)', _ATEN_PE6108G), (r'(?P<model>pdu|ipp|...
import logging from PySide2 import QtCore, QtGui, QtWidgets from urllib.request import urlopen from hyo2.abc.lib.helper import Helper from hyo2.abc.app.web_renderer import WebRenderer from hyo2.ssm_sis import app_info, lib_info from hyo2.ssm_sis.controlpanel import ControlPanel logger = logging.getLogger(__name__) clas...
from distutils.core import setup setup(name='axigen-api', version='1.0.0-1', description='Python module to interface with Axigen\'s CLI API', author='Vedran Krivokuca', author_email='dev@krivokuca.net', url='https://github.com/casastorta/axigen-pyton-api', packages=['axigenapi'], license='LG...
import __builtin__ import maps import subprocess from mock import patch from tendrl.commons.objects.cluster.atoms.configure_monitoring import \ ConfigureMonitoring def init(): setattr(__builtin__, "NS", maps.NamedDict()) NS.config = maps.NamedDict() NS.config.data = maps.NamedDict() NS.node_context ...
"""autogenerated by genmsg_py from raven_jointmove.msg. Do not edit.""" import roslib.message import struct import std_msgs.msg class raven_jointmove(roslib.message.Message): _md5sum = "c77744b32e84ca2df946f65f29601eb9" _type = "raven_2/raven_jointmove" _has_header = False #flag to mark the presence of a Header o...
from ovsylib import datastruct import os import pickle environ_name = ".ovs_staging" def topdir(root): if root[len(root) - 1] == "\\" or root[len(root) - 1] == "/": root = root[:-1] return os.path.basename(root) def listrecursive(root, wholedir=False): allfiles = {} for rootfolder, dirs, files i...
''' Created on 21 kwi 2013 @author: jurek ''' from hra_core.special import ImportErrorMessage try: from PyQt4.QtGui import * # @UnusedWildImport from PyQt4.QtCore import * # @UnusedWildImport from hra_gui.qt.widgets.commons import Common from hra_gui.qt.widgets.commons import prepareWidget except Impo...
from UM.Workspace.WorkspaceReader import WorkspaceReader from UM.Application import Application from UM.Logger import Logger from UM.i18n import i18nCatalog from UM.Settings.ContainerStack import ContainerStack from UM.Settings.DefinitionContainer import DefinitionContainer from UM.Settings.InstanceContainer import Ins...
""" Convert the X11 locale.alias file into a mapping dictionary suitable for locale.py. Written by Marc-Andre Lemburg <mal@genix.com>, 2004-12-10. """ import locale import sys LOCALE_ALIAS = '/usr/share/X11/locale/locale.alias' def parse(filename): with open(filename, encoding='latin1') as f: li...
""" Copyright (C) 2014, 申瑞珉 (Ruimin Shen) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in ...
from mdt import CompartmentTemplate __author__ = 'Robbert Harms' __date__ = '2018-09-07' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class NODDI_EC(CompartmentTemplate): """The Extra-Cellular compartment of the NODDI-Watson model. This is the compartment as described i...
""" Gets the current version number. If in a git repository, it is the current git tag. Otherwise it is the one contained in the PKG-INFO file. To use this script, simply import it in your setup.py file and use the results of get_version() as your package version: from version import * setup( ... ...
import logging as PandaLogger from threading import local class pmObject(object): _topObject = local() #________________________________________________________________________________________ @classmethod def setTopObject(cls,top): if isinstance(top,pmObject): cls._topObject._top = top ...
import iris def convert_montly(): mon = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] yr1 = 2040 yrn = 2101 for year in range(yr1, yrn): for month in mon: name = 'bh456a.p5' + str(year) + month ppfile = name + '.pp' data = iris.load_cube(ppfil...
""" Contains the utility functions for editing objects and Phobos models. """ import bpy import mathutils import math from phobos.phoboslog import log import phobos.utils.selection as sUtils import phobos.utils.naming as nUtils import phobos.utils.blender as bUtils import phobos.utils.io as ioUtils import phobos.defs a...
import json import uuid from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt, pyqtSignal from tribler_common.simpledefs import CHANNELS_VIEW_UUID from tribler_core.modules.metadata_store.orm_bindings.channel_node import NEW from tribler_core.modules.metadata_store.serialization import CHANNEL_TORRENT, COLLECTI...
import os, sys, logging logging.basicConfig() from tnefparse import TNEF datadir = os.path.dirname(os.path.realpath(__file__)) + os.sep + "examples" SPECS = ( ("body.tnef", 0x1125, [], [0x9006, 0x9007, 0x800d, 0x8005, 0x8020, 0x8009, 0x9004, 0x9003] ), ("two-files.tnef", 0x237, ["AUTHORS", "README"], ...
from server import db, utils, errors, session, conf, securitykey from server import forcePost, forceSSL, exposed, internalExposed from server.prototypes import BasicApplication from server.bones import baseBone, keyBone, numericBone from server.skeleton import Skeleton, skeletonByKind from server.tasks import callDefer...
import frenetic from frenetic.syntax import * def policy(ps): vs = 0 for dst in range(1,ps+1): ip4 = '10.0.0.' + str(dst) f = Filter(Test(IP4Dst(ip4))) both = f >> Mod(Location(Physical(dst))) if vs == 0: vs = both else: vs = vs | both return v...
import datetime as dt from datetime import datetime import functools import logging import uuid from aiohttp import web import aiohttp_cors import aioredlock import aiotools import sqlalchemy as sa import trafaret as t from typing import Any, Tuple, MutableMapping from ai.backend.common import validators as tx from ai....
from pilasengine.actores.deslizador_horizontal import DeslizadorHorizontal from pilasengine import colores class ManejadorPropiedad(DeslizadorHorizontal): def __init__(self, pilas, x, y, actor, propiedad, min, max): valor_inicial = getattr(actor, propiedad) DeslizadorHorizontal.__init__(self, pilas,...
""" Created on Wed Aug 31 15:25:01 2016 @author: rarossi """ import sys from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) window = QtGui.QMainWindow() window.setGeometry(0, 0, 400, 200) pic = QtGui.QLabel(window) pic.setGeometry(10, 10, 400, 200) pixmap = QtGui.QPixmap('maze.bmp') pixmap = pixmap.scaledToHeigh...
''' Script to create truthData for tests. For output it expects the command in the form of: python3 makeOutput.py test where test is the cmake name for the unit or app test To check in truth data the command should be in the form of: python makeOutput.py -t test The -t option checks in truth data The unit tests...
import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ inFile = open(WORDLIST_FILENAME, 'r', 0) line = inFil...
import re from collections import Counter fo = open("text.txt", "r+") test_pr = fo.read() test_low = test_pr.lower() c = Counter(re.split('\W', test_low)) c_list = c.values() c_list.sort() print c_list[-10:]
""" Python Character Mapping Codec iso8859_15 generated from 'MAPPINGS/ISO8859/8859-15.TXT' with gencodec.py. """ import codecs class Codec(codecs.Codec): def encode(self, input, errors='strict'): return codecs.charmap_encode(input, errors, encoding_table) def decode(self, input, errors='strict'): ...
import getopt import os import math import sys import time import mpmath import numpy as np from nzmath.arith1 import modsqrt from sympy import sieve from sympy.matrices import SparseMatrix def legendre(a,p): # i know i saw this as a library function in nzmath return pow(a, (p - 1) // 2, p) % p def gcd(a, b):#t...
import tinkerbell.domain.point as tbdpt import tinkerbell.app.make as tbamk import tinkerbell.app.rcparams as tbarc import tinkerbell.app.plot as tbapl import pandas as pd import numpy as np if __name__ == '__main__': y0 = tbarc.rcparams['shale.lstm.y0_mean'] d = tbarc.rcparams['shale.lstm_stage.d'] xmax = ...
""" This signature containts test to see if the site is running on Liferay. """ __author__ = "Seth Gottlieb" __copyright__ = "CM Fieldguide" __credits__ = ["Seth Gottlieb"] __license__ = "Unlicense" __version__ = "0.1" __maintainer__ = "Seth Gottlieb" __email__ = "sgottlieb@alumni.duke.edu" __status__ = "Experimental" ...
import os, sys, logging from flask import Flask, request, render_template, jsonify, url_for import json, copy app = Flask(__name__) basePath = os.path.dirname(os.path.realpath(__file__)) @app.route('/') @app.route('/index') @app.route('/index.html') def index(): #return os.path.join(basePath, 'static/playersData.js...
import os class Console(): def write_title(self,title): self.write_header(title,1) def write_header(self,msg,level=1): output=msg if level==1: output= "*" * 50 + "\n" + "*" * 50 + "\n" + " " + msg + "\n" + "*" * 50 + "\n" + "*" * 50 + "\n" if level==2: ...
from testing_helpers import wrap @wrap def format_consts(): return '%d %d %s' % (100, 100, "Hello") @wrap def format_args(a,b): return "%s %d" % (a,b) def test_format(): format_consts() format_args(1.0, 2.0) format_args({3:2},2)
from django.db.models import F from rest_framework import generics from rest_framework import permissions as drf_permissions from rest_framework import exceptions from rest_framework import status from rest_framework.response import Response from framework.auth.oauth_scopes import CoreScopes from osf.models import OSFU...
import unittest import numpy as np from op_test import OpTest def bilinear_interp_np(input, out_h, out_w, out_size): if out_size is not None: out_h = out_size[0] out_w = out_size[1] batch_size, channel, in_h, in_w = input.shape if out_h > 1: ratio_h = (in_h - 1.0) / (out_h - 1.0) ...
""" Admin views for managing volumes. """ from collections import OrderedDict from django.urls import reverse from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import tables from horizon.utils import memoized...
import base64 import json import os import sys import unittest from pprint import pprint sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../') from google_api_clients.pubsub import PubSub from google_api_clients.pubsub.errors import AcknowledgeError from google_api_clients.pubsub.errors import NotFoun...
import uuid import svc_monitor.services.loadbalancer.drivers.abstract_driver as abstract_driver from vnc_api.vnc_api import InstanceIp from vnc_api.vnc_api import FloatingIp from vnc_api.vnc_api import PortMap, PortMappings from vnc_api.vnc_api import ServiceHealthCheck, ServiceHealthCheckType from vnc_api.vnc_api impo...
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): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
import unittest class DumbLogger(object): def __getattr__(self, n): return self.foo def foo(self, *a, **kw): pass class Mocker(object): def __init__(self): self._dict = {} def __call__(self, obj, name, value): try: self._dict[(obj, name)] = getattr(obj, name) ...
from .base import * from ._ci import * from ._admin import *
import six import collections import logging import grpc from opencensus.ext import grpc as oc_grpc from opencensus.ext.grpc import utils as grpc_utils from opencensus.trace import attributes_helper, execution_context from opencensus.trace import span as span_module from opencensus.trace import time_event from opencens...
class Solution(object): def optimalDivision(self, nums): """ :type nums: List[int] :rtype: str """ if len(nums) <= 2: return '/'.join(str(n) for n in nums) return str(nums[0]) + '/(' + '/'.join(str(n) for n in nums[1:]) + ')'
from collections import defaultdict lexical_order = lambda x: ''.join(sorted(str(x))) d = defaultdict(list) def cube_permute_search(n_start=5, n_len=1000): cube_lst = map(lambda x: x**3, range(n_start, n_start+n_len)) for num in cube_lst: lex_map = lexical_order(num) if len(d[lex_map]) < 4: ...
import os import socket import subprocess import time from urllib.error import HTTPError from urllib.error import URLError from urllib.request import Request from urllib.request import urlopen class VcsClientBase(object): type = None def __init__(self, path): self.path = path def __getattribute__(se...
import unittest import datetime as dt import ocw.data_source.dap as dap from ocw.dataset import Dataset class TestDap(unittest.TestCase): @classmethod def setUpClass(cls): cls.url = 'http://test.opendap.org/opendap/data/ncml/agg/dated/CG2006158_120000h_usfc.nc' cls.name = 'foo' cls.datas...
import os import sys import sqlalchemy sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import legendary_waffle db = legendary_waffle.inmem_db() legendary_waffle.preload_database(db, file_list_prefix="../legendary_waffle/fixtures/{}")
''' Utilities for creating, managing, etc. resources Recommended to use bibframe.util.resource_id from pybibframe for creating new resource IDs '''
from must import MustHavePatterns from hearthstone_deck import HearthstoneDeck from mock import call class TestHearthsoneDeck(object): def setup(self): test_patterns = MustHavePatterns(HearthstoneDeck) self.mock_decklist, self.mock_shuffler, self.mock_fatigue_factory = test_patterns.mock_dependencie...
import urllib2 import json def get_json_from_url(url): json_result = None try: req = urllib2.Request(url) response = urllib2.urlopen(req) the_page = response.read() #print the_page json_result = json.loads(the_page) except: print 'get data error,url:',url ...
"""Http views to control the config manager.""" import aiohttp.web_exceptions import voluptuous as vol from homeassistant import config_entries, data_entry_flow from homeassistant.auth.permissions.const import CAT_CONFIG_ENTRIES, POLICY_EDIT from homeassistant.components import websocket_api from homeassistant.componen...