content stringlengths 4 20k |
|---|
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import time
import json
from itertools import chain
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_text
from ansible.module_utils.network.common.config import dumps
from an... |
# Since this package contains a "django" module, this is required on Python 2.
from __future__ import absolute_import
import io
import string
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import TemplateDoesNotExist
from django.utils.html import conditio... |
from PIL import Image
from laspy.file import File
import numpy as np
import sys, os
m_file = "mdt_data.txt"
o_file = "orto_data.txt"
l_file = "lidar_data.txt"
a_file = "areas_interest.txt"
laszip = "/home/pablo/Documentos/LAStools/bin/laszip"
def load_mdt_info(png_directory):
print("Loading MDTs data...")
f = open... |
import os
from django import template
from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
register = template.Library()
class OverExtendsNode(ExtendsNode):
"""
Allows the template ``foo/bar.html`` to extend ``foo/bar.html``,
... |
from collections import defaultdict
def GetChildPids(processes, pid):
"""Returns all child processes of |pid| from the given |processes| list.
Args:
processes: A tuple of (pid, ppid, state) as generated by ps.
pid: The pid for which to get children.
Returns:
A list of child pids.
"""
child_dic... |
import time
from django import forms
from django.forms.util import ErrorDict
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
from django.utils.crypto import salted_hmac, constant_time_compare
from django.utils.encoding import... |
from browser import doc,markdown,html
def keydown(ev,path,zone,page):
if ev.keyCode in [39,40]: # key right or down : next page
show(path,zone,page+1)
ev.preventDefault()
elif ev.keyCode in [37,38]: #key left or up: previous page
show(path,zone,page-1)
ev.preventDefault()
d... |
"""Tests for mxnet_benchmark."""
import os
import unittest
from perfkitbenchmarker import test_util
from perfkitbenchmarker.linux_benchmarks import mxnet_benchmark
class MxnetBenchmarkTestCase(unittest.TestCase,
test_util.SamplesTestMixin):
def setUp(self):
path = os.path.join(os.... |
from spack import *
class PySphinxRtdTheme(PythonPackage):
"""ReadTheDocs.org theme for Sphinx."""
homepage = "https://github.com/rtfd/sphinx_rtd_theme/"
url = "https://pypi.io/packages/source/s/sphinx_rtd_theme/sphinx_rtd_theme-0.1.10a0.tar.gz"
import_modules = ['sphinx_rtd_theme']
versio... |
import random
import re
import string
import datetime
from streamlink.plugin import Plugin, PluginError, PluginOptions
from streamlink.plugin.api import http, validate
from streamlink.stream import HLSStream
API_URL = "https://api.crunchyroll.com/{0}.0.json"
API_DEFAULT_LOCALE = "en_US"
API_USER_AGENT = "Mozilla/5.0 ... |
from __future__ import print_function
import os, sys, time, urllib2
startTime = time.time()
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse
op = vcoptparse.OptParser()
scenario_common.prepare_option_parser_mode_fla... |
from functools import partial
from kivy.animation import Animation
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.bubble import Bubble, BubbleButton
from kivy.properties import ListProperty
from kivy.uix.widget import Widget
from electrum_vtc_gui.i18n import _
class ContextMenuItem(Wi... |
import sys
import numpy as np
import matplotlib.pyplot as plt
import FitsUtils
trimming = {
21: [0, 576.3],
22: [582.6, 9e9],
23: [583.45, 9e9],
37: [0, 680.15]}
class Trimmer:
def __init__(self, data=None):
if data != None:
self.data = data.copy()
self.clicks = []
... |
#!/usr/bin/env python
import argparse
from celery import Celery
from celery.bin.beat import beat
from celery import maybe_patch_concurrency
from up.headliner.utils import read_config_file, setup_basic_logger
from up.headliner import Application
def get_scheduler_config():
"""
Read configuration from multipl... |
from __future__ import print_function
from wordcloud import create_cloud
try:
from gensim import corpora, models, matutils
except:
print("import gensim failed.")
print()
print("Please install it")
raise
import matplotlib.pyplot as plt
import numpy as np
from os import path
NUM_TOPICS = 100
# Chec... |
from common import *
from selenium.common.exceptions import NoSuchElementException
def find_current_mail(context):
print 'searching for mail [%s]' % context.current_mail_id
return find_element_by_id(context, '%s' % context.current_mail_id)
def check_current_mail_is_visible(context):
find_current_mail(co... |
#!/usr/bin/env python
"""Search for certain files, filter them by given criteria and do something."""
import stat
from grr.lib import aff4
from grr.lib import flow
from grr.lib import utils
from grr.lib.flows.general import filesystem
from grr.lib.flows.general import fingerprint
from grr.lib.flows.general import t... |
from django.utils.translation import ugettext_lazy as _
from horizon import browsers
from openstack_dashboard.dashboards.project.containers import tables
class ContainerBrowser(browsers.ResourceBrowser):
name = "swift"
verbose_name = _("Swift")
navigation_table_class = tables.ContainersTable
content... |
import time
from openerp import pooler
from openerp.report import report_sxw
class account_inverted_analytic_balance(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_inverted_analytic_balance, self).__init__(cr, uid, name, context=context)
self.localcontext.update( ... |
"""
ApplicationVersion models for atmosphere.
"""
import uuid
from django.db import models, IntegrityError
from django.db.models import Q
from django.utils import timezone
from django.contrib.auth.models import AnonymousUser
from threepio import logger
from django.core.exceptions import ObjectDoesNotExist as DoesNot... |
import ctypes
from . import win32
from .serialutil import *
def device(portnum):
"""Turn a port number into a device name"""
return 'COM%d' % (portnum+1) # numbers are transformed to a string
class Win32Serial(SerialBase):
"""Serial port implementation for Win32 based on ctypes."""
BAUDRATES = (50... |
import datetime
from django import forms
from django.forms import CheckboxSelectMultiple
from django.test import override_settings
from .base import WidgetTest
class CheckboxSelectMultipleTest(WidgetTest):
widget = CheckboxSelectMultiple
def test_render_value(self):
self.check_html(self.widget(choi... |
data = (
'Ti ', # 0x00
'Li ', # 0x01
'Bin ', # 0x02
'Zong ', # 0x03
'Ti ', # 0x04
'Peng ', # 0x05
'Song ', # 0x06
'Zheng ', # 0x07
'Quan ', # 0x08
'Zong ', # 0x09
'Shun ', # 0x0a
'Jian ', # 0x0b
'Duo ', # 0x0c
'Hu ', # 0x0d
'La ', # 0x0e
'Jiu ', # 0x0f
'Qi ', # 0x10
'L... |
"""
Autopsy Forensic Browser
Copyright 2016-2018 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses... |
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase
from django.core import signing
class SessionStore(SessionBase):
def load(self):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_sess... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import topology.data as td
def run_coffee_mug_pca_example():
X, y = td.coffee_mug(bottom_label=0, side_label=0, handle_label=1)
c = ['r' if l else 'b' for l in y]
# Nontrivial rotation around the x-axis
angle = ... |
import tensorflow as tf # neural network for function approximation
import gym # environment
import numpy as np # matrix operation and math functions
from gym import wrappers
import gym_morph # customized environment for cart-pole
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
star... |
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python
Docs and examples: http://code.google.com/p/fantasm/
Copyright 2010 VendAsta Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may ob... |
'''
Native support of Wacom tablet from linuxwacom driver
=====================================================
To configure LinuxWacom, add this to your configuration::
[input]
pen = linuxwacom,/dev/input/event2,mode=pen
finger = linuxwacom,/dev/input/event3,mode=touch
.. note::
You must have read a... |
#!/usr/bin/env python
# encoding=utf-8
import os
import os.path as osp
import random
import unittest
import socket
from inner_rpc import utils, ir_exceptions
class ClientTestCase(unittest.TestCase):
def setUp(self):
self.__server_socket = None
self.__client_socket = None
self.__unix_pat... |
#!/usr/bin/python
from distutils.core import setup, Extension
import os
scriptDir = os.path.dirname(os.path.realpath(__file__))
buildDir = os.path.join(scriptDir, '../../build')
includeDirs = [buildDir, os.path.join(scriptDir, '../../src')]
libraryDirs = [buildDir]
module = Extension('bamboo',
include_dirs = incl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image as Img
from io import BytesIO
import uuid
from django.db import models
from django.core.files.uploadedfile import InMemoryUploadedFile
class School(models.Model):
school_id = models.AutoField(primary_key=True)
title = models.TextField()
... |
"""
csv.py - read/write/investigate CSV files
"""
import re
from functools import reduce
from _csv import Error, __version__, writer, reader, register_dialect, \
unregister_dialect, get_dialect, list_dialects, \
field_size_limit, \
QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONN... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('urlrewriter')
class UrlRewritingError(Exception):
def __init__(se... |
# prerequisites imports
from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException
from django.contrib.gis.gdal.prototypes import ds as capi
from django.utils import six
from django.utils.encoding import force_bytes
# For more information, see... |
from openerp.osv import fields,osv,orm
class crm_segmentation(osv.osv):
'''
A segmentation is a tool to automatically assign categories on partners.
These assignations are based on criterions.
'''
_name = "crm.segmentation"
_description = "Partner Segmentation"
_columns = {
... |
"""Stateless random ops which take seed as a tensor input."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import gen_stateless_random_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ... |
from collections import OrderedDict
import simplejson as json
import asyncio
import sys
import time
import os
class ExpiringDict(OrderedDict):
def __init__(self, max_len, max_age_seconds):
OrderedDict.__init__(self)
self.max_len = max_len
self.max_age = max_age_seconds
def __contains_... |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout, authenticate, login
from django.shortcuts import redirect
from django.contrib.auth.models import User
from .models import UserInfo, Place, Comment, Booking
from datetime import datetime, date... |
import mxnet as mx
class Config(object):
def __init__(self, args):
# Default training settings
self.ctx = mx.gpu(0) if args.gpu else mx.cpu()
self.init_func = mx.init.Xavier(rnd_type='uniform', factor_type="in",
magnitude=1)
self.learning_rat... |
from odoo import api, fields, models
class BaseConfigSettings(models.TransientModel):
_name = 'base.config.settings'
_inherit = 'res.config.settings'
group_multi_company = fields.Boolean(string='Manage multiple companies',
help='Work in multi-company environments, with appropriate security acces... |
"""
Given a linked list where every node represents a linked list and contains two pointers of its type:
(i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
(ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).
All linked lists are sorted. See ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'manuskript/ui/search_ui.ui'
#
# Created by: PyQt5 UI code generator 5.4.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_search(object):
def setupUi(self, search):
s... |
"""
Module :mod:`openquake.hazardlib.geo.surface.complex_fault` defines
:class:`ComplexFaultSurface`.
"""
import numpy
import shapely
from openquake.hazardlib.geo.line import Line
from openquake.hazardlib.geo.point import Point
from openquake.hazardlib.geo.surface.base import BaseQuadrilateralSurface
from openquake.ha... |
import ctypes
from ctypes import windll
from ctypes import wintypes
class CryptoAPIException(Exception):
def __init__(self):
message = self._get_windows_error()
super(CryptoAPIException, self).__init__(message)
def _get_windows_error(self):
err_code = GetLastError()
return "C... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Refrescador automatico de clines
#Creado por Dagger - https://github.com/gavazquez
import ReloadCam_Main, ReloadCam_Helper
def GetVersion():
return 7
#Filename must start with Server, classname and argument must be the same!
class Cccam4you(ReloadCam_Main.Server):... |
from django.contrib import admin
from taiga.projects.notifications.admin import WatchedInline
from taiga.projects.votes.admin import VoteInline
from . import models
class MilestoneInline(admin.TabularInline):
model = models.Milestone
extra = 0
class MilestoneAdmin(admin.ModelAdmin):
list_display = ["na... |
import json
import copy
from util.json_request import JsonResponse
from django.http import HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import ensure_csrf_cookie
from edxmako.shortcuts im... |
from pytz import common_timezones
from openerp.osv import fields, orm
class policy_ot(orm.Model):
_name = 'hr.policy.ot'
_columns = {
'name': fields.char('Name', size=128, required=True),
'date': fields.date('Effective Date', required=True),
'line_ids': fields.one2many(
'... |
"""
Utilities for manipulating map-annotations used as metadata
"""
import logging
from omero.model import NamedValue
from omero.rtypes import rstring, unwrap
# For complicated reasons `from omero.sys import ParametersI` doesn't work
from omero_sys_ParametersI import ParametersI
log = logging.getLogger("omero.util.me... |
import sys
import datetime
import collections
import concurrent.futures
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
print('''
ERROR: You must have the boto3 package installed in your python environment to run
this script! You can install it by running:
... |
"""SCons.Tool.tlib
XXX
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in th... |
"""Test the vtk.mutable() type and test pass-by-reference.
Created on Sept 19, 2010 by David Gobbi
"""
import sys
import vtk
from vtk.test import Testing
class TestMutable(Testing.vtkTest):
def testFloatMutable(self):
m = vtk.mutable(3.0)
n = vtk.mutable(4.0)
m *= 2
self.assertEqu... |
#!/usr/bin/python
'''
Upload Cosmic S19 file via STM8 bootloader
'''
# required modules
import os
import platform
# set path of s19 file
HEXFILE = './Release/STM8_Template.s19'
#HEXFILE = './Debug/STM8_Template.s19'
# set tool path
ROOT_DIR = '../../../../'
TOOL_DIR = ROOT_DIR + 'Tools/'
# determine operating sy... |
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class VerbatimTagTests(SimpleTestCase):
@setup({'verbatim-tag01': '{% verbatim %}{{bare }}{% endverbatim %}'})
def test_verbatim_tag01(self):
output = self.engine.render_to_string('verb... |
#!/usr/bin/python
N_MOTES = 10
DBG_CHANNELS = "default error"
SIM_TIME = 300
TOPO_FILE = "linkgain.out"
#NOISE_FILE = "/opt/tinyos-2.1.0/tos/lib/tossim/noise/casino-lab.txt"
NOISE_FILE = "/home/mgianello/tinyos-main/tos/lib/tossim/noise/meyer-heavy.txt"
from TOSSIM import *
from tinyos.tossim.TossimApp import *
from ... |
"""Implementing pooling of connections to MySQL servers.
"""
import re
from uuid import uuid4
# pylint: disable=F0401
try:
import queue
except ImportError:
# Python v2
import Queue as queue
# pylint: enable=F0401
import threading
from . import errors
from .connection import MySQLConnection
CONNECTION_POO... |
import delivery
import partner
import sale
import stock
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Compatibility namespace for sqlalchemy.sql.schema and related.
"""
from .sql.base import (
SchemaVisitor
)
from .sql.schema import (
CheckConstraint,
Column,
ColumnDefault,
Constraint,
DefaultClause,
DefaultGenerator,
FetchedValue,
ForeignKey,
ForeignKeyConstraint,
... |
from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_users(osv.Model):
_name = 'res.users'
_inherit = 'res.users'
def _get_employee_id(self, cr, uid, ids, name, arg, context=None):
"""
This extends the base user to look up for a matching employee
@r... |
#!/usr/bin/env python3
"""
Note: This only runs with Python3!
Demo: Find unlinked or unknown words.
These demo is extremely simplified.
It can only work with link-grammar library version >= 5.3.10.
Input: English sentences, one per line.
Output: If there are any []-marked words in the linkage results,
the output conta... |
from ansible.module_utils.gcp import gcp_connect
from ansible.module_utils.gcp import unexpected_error_msg as gcp_error
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
HAS_LIBCLOUD_BASE = True
except ImportError:
HAS_LIBCLOUD_BASE = False
USER_AGENT_P... |
"""MobileNet v1 models for Keras.
MobileNet is a general architecture and can be used for multiple use cases.
Depending on the use case, it can use different input layer size and
different width factors. This allows different width models to reduce
the number of multiply-adds and thereby
reduce inference cost on mobil... |
# -*- coding: utf-8 -*-
from django.http import Http404
from django.shortcuts import get_object_or_404
from cms.models import Page, Title, CMSPlugin, Placeholder
def revert_plugins(request, version_id, obj):
from cms.utils.reversion_hacks import Version
version = get_object_or_404(Version, pk=version_id)
... |
import os
from flask import Blueprint, jsonify, render_template, request, current_app, redirect, url_for, flash, abort
from flask_login import login_required
from bson.objectid import ObjectId
distributive = Blueprint('distributive', __name__)
@distributive.route('/distributive/list/<environment_name>')
@login_requi... |
#!/usr/bin/python
from flask import Flask, render_template, send_from_directory, request, jsonify
import os
app = Flask(__name__)
''' Channel Config 1-5. Chan 0 fuer alle 5 Channels gleichzeitig
Mode 1 HOCH - Mode 2 Runter - Mode 3 Stop '''
config = {'chan0mode1': '', 'chan0mode2': '', 'chan0mode3': '', 'chan1mode1... |
import os
import subprocess
from git_remote_helpers.util import check_call, check_output
class GitImporter(object):
"""An importer for testgit repositories.
This importer simply delegates to git fast-import.
"""
def __init__(self, repo):
"""Creates a new importer for the specified repo.
... |
from xen.util.xmlrpcclient import ServerProxy
import os
import sys
XML_RPC_SOCKET = "/var/run/xend/xmlrpc.sock"
XEN_API_SOCKET = "/var/run/xend/xen-api.sock"
ERROR_INTERNAL = 1
ERROR_GENERIC = 2
ERROR_INVALID_DOMAIN = 3
uri = 'httpu:///var/run/xend/xmlrpc.sock'
if os.environ.has_key('XM_SERVER'):
uri = os.enviro... |
import logging
from src.packet import EVENT
from src.packet import FLAGS
__version__ = "0.1"
__applic__ = "Live F1 Web"
__author__ = "Marc Bertens"
log = logging.getLogger('live-f1')
class F1TrackStatus(object):
statusFlags = { 1: "Green", 2: "Yellow", 3: "Yellow",
4: "Yel... |
######################################################################
# Cloud Routes Web Application
# -------------------------------------------------------------------
# Reaction - Forms Class
######################################################################
from wtforms import TextField, SelectField
from wtf... |
import simplejson
import twill
from twisted.application.internet import TimerService
from twisted.python import log
from canarydrop import Canarydrop
from channel import InputChannel
from queries import get_canarydrop, get_all_imgur_tokens, save_imgur_token,\
get_imgur_count, get_all_linkedin_acco... |
import rdflib
from nose import SkipTest
from nose.tools import assert_raises
data = '''<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:http="http://www.w3.org/2011/http#">
<http:HeaderElement rdf:about="#he0">
<http:params>
<htt... |
#!/usr/env/python
from __future__ import print_function
import platform
print(platform.platform())
import sys
print("Python", sys.version)
import numpy as np;
print("NumPy", np.__version__)
import scipy
print("SciPy", scipy.__version__)
import sklearn
print("Scikit-Learn", sklearn.__version__)
import rospy
import... |
"""
Support for Clementine Music Player as media player.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.clementine/
"""
import asyncio
from datetime import timedelta
import logging
import time
import voluptuous as vol
import homeassistant... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import subprocess
import sys
from collections import Mapping
from ansible import constants as C
from ansible.errors import *
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible... |
"""Chroot manager hypervisor
"""
import os
import os.path
import time
import logging
from ganeti import constants
from ganeti import errors # pylint: disable=W0611
from ganeti import utils
from ganeti import objects
from ganeti import pathutils
from ganeti.hypervisor import hv_base
from ganeti.errors import Hypervis... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
import base64
class showdiff(osv.osv_memory):
""" Disp[ay Difference for History """
_name = 'wizard.document.page.history.show_diff'
def get_diff(self, cr, uid, context=None):
if context is None:
context = {}
... |
"""
====================================
Outlier detection on a real data set
====================================
This example illustrates the need for robust covariance estimation
on a real data set. It is useful both for outlier detection and for
a better understanding of the data structure.
We selected two sets o... |
from kivy.base import runTouchApp
from kivy.lang import Builder
root = Builder.load_string("""
#:import MapSource mapview.MapSource
<Toolbar@BoxLayout>:
size_hint_y: None
height: '48dp'
padding: '4dp'
spacing: '4dp'
canvas:
Color:
rgba: .2, .2, .2, .6
Rectangle:
... |
"""Tests for remove_headers and force_header decorator. """
from django.http import HttpResponse, HttpRequest
from django.test import TestCase
from header_control.decorators import remove_headers, force_header
def fake_view(_request):
"""Fake view that returns an empty response."""
return HttpResponse()
cla... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
import pyconde.tagging
class Migration(migrations.Migration):
dependencies = [
('speakers', '__first__')... |
__author__ = 'bromix'
import hashlib
from . import utils
def create_item_hash(item):
m = hashlib.md5()
m.update(utils.strings.to_utf8(item['uri']))
return m.hexdigest()
def create_next_page_item(context, thumbnail=None, fanart=None):
if not fanart:
fanart = context.get_fanart()
pas... |
"""
YAML serializer.
Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
"""
import decimal
import sys
from io import StringIO
import yaml
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import (
Deserializer as PythonDeserializer, Serializ... |
"""
Tests for test case queryset-filtering by ID and with optional ID prefix.
"""
from tests import case
from moztrap.view.lists.cases import PrefixIDFilter
class PrefixIDFilterTest(case.DBTestCase):
"""Tests for PrefixIDFilter"""
def create_testdata(self):
testdata = {}
testdata["cv1"] = ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from ansible.modules.network.edgeswitch import edgeswitch_facts
from units.modules.utils import set_module_args
from .edgeswitch_module import TestEdgeswitchModule, load_fixture
cl... |
from pathlib import Path
import pytest
from unittest.mock import MagicMock, patch
from robot_server.service.protocol import errors
from robot_server.service.protocol.manager import ProtocolManager, UploadFile
from robot_server.service.protocol.protocol import UploadedProtocolMeta, \
UploadedProtocol
@pytest.fix... |
from boto.iam.connection import IAMConnection
from boto.regioninfo import RegionInfo, get_regions
class IAMRegionInfo(RegionInfo):
def connect(self, **kw_params):
"""
Connect to this Region's endpoint. Returns an connection
object pointing to the endpoint associated with this region.
... |
from PIL import Image, ImageDraw, ImageFont
import random
##
# Check createverbar, createhorbar arguments.
#
# @raise {ValueError} invalid arguments.
#
def checkbarargs(maxw, maxh, worh, barcolor, bgcolor):
maxw = int(maxw)
if maxw <= 0:
raise ValueError('invalid max width')
maxh = int(maxh)
if... |
"""The RequestHandler for /build URLs."""
import celery
import jsonschema
import handlers.base as hbase
import handlers.response as hresponse
import models
import taskqueue.tasks
import taskqueue.tasks.kcidb
import taskqueue.tasks.build as taskq
import utils.db
STEPS_SCHEMA = {
"type": "array",
"minItems": 1... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaebusiness.gaeutil import SaveCommand, ModelSearchCommand
from gaeforms.ndb.form import ModelForm
from gaegraph.business_base import UpdateNode
from destaque_app.model import Destaques
class DestaquesPublicForm(ModelForm):
"""
... |
"""
This module contains a base type which provides list-style mutations
without specific data storage methods.
See also http://static.aryehleib.com/oldsite/MutableLists.html
Author: Aryeh Leib Taurog.
"""
from functools import total_ordering
from django.utils import six
from django.utils.six.moves import range
@t... |
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import world, step
@step('I click on View Courseware')
def i_click_on_view_courseware(step):
world.css_click('a.enter-course')
@step('I click on the "([^"]*)" tab$')
def i_click_on_the_tab(... |
"""Benchmarks for polynomials over Galois fields. """
from __future__ import print_function, division
from sympy.polys.galoistools import gf_from_dict, gf_factor_sqf
from sympy.polys.domains import ZZ
from sympy import pi, nextprime
from sympy.core.compatibility import range
def gathen_poly(n, p, K):
return gf_... |
"""Tests for the GitHub Services."""
# pylint: disable=missing-docstring,protected-access
import unittest
import github_services
import issues
from issues_test import DEFAULT_USERNAME
from issues_test import SINGLE_ISSUE
from issues_test import COMMENT_ONE
from issues_test import COMMENT_TWO
from issues_test import... |
SERVICES = {
# Name namespace wsdl file binding name
'devicemgmt' : {'ns': 'http://www.onvif.org/ver10/device/wsdl', 'wsdl': 'devicemgmt.wsdl', 'binding' : 'DeviceBinding'},
'media' : {'ns': 'http://www.onvif... |
from js2py.base import *
def _get_conts(idl):
def is_valid(c):
try:
exec(c)
return 1
except:
pass
return '\n'.join(filter(is_valid, (' '.join(e.strip(' ;').split()[-3:]) for e in idl.splitlines())))
default_attrs = {'writable':True, 'enumerable':True, 'conf... |
#! /usr/bin/env python
"""Test script for the gzip module.
"""
import unittest
from test import test_support
import os
import io
import struct
gzip = test_support.import_module('gzip')
data1 = """ int length=DEFAULTALLOC, err = Z_OK;
PyObject *RetVal;
int flushmode = Z_FINISH;
unsigned long start_total_out;
"... |
import logging
import re
from airflow.hooks import HiveCliHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class HiveOperator(BaseOperator):
"""
Executes hql code in a specific Hive database.
:param hql: the hql to be executed
:type hql: string
:param hive_cl... |
"""
Flask RESTful fields, and WTForms input validators for validation and
marshaling
"""
import datetime
import re
from functools import reduce, wraps
from flask_restful import fields, inputs
from werkzeug.routing import BuildError
from dockci.util import gravatar_url
def value_path(obj, path):
"""
Get a ... |
'''
New Perf Test for expunging KVM VMs which were deleted.
The expunged number will depend on the environment variable: ZSTACK_TEST_NUM.
This case's max thread is 1000.
Before run this test, at least 1 VM is created, and at least 1 VM was destoryed.
@author: Liu Lei
'''
import zstackwoodpecker.test_lib as test_lib
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.