content string |
|---|
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
from ..parameters import parse_token_response, prepare_token_request
from .ba... |
from oslo_serialization import jsonutils as json
from six.moves.urllib import parse as urllib
from tempest.lib.common import rest_client
from tempest.lib import exceptions as lib_exc
from tempest.lib.services.volume import base_client
class BackupsClient(base_client.BaseClient):
"""Volume V2 Backups client"""
... |
import click
from click_repl import register_repl
class CmdGlobal(object):
def __init__(self):
self.current_resource_type = None
self.current_resource = None
def __str__(self):
return 'CmdGlobal(current_resource_type={}, current_resource={})'.format(self.current_resource_type, self.cu... |
#-*- coding: utf-8 -*-
""" Last.FM scrobbling module """
import sys
from voiceplay.datasources.lastfm import VoicePlayLastFm
from voiceplay.logger import logger
from voiceplay.utils.helpers import debug_traceback
from .basehook import BasePlayerHook
class TrackScrobble(object):
"""
Save track history for Las... |
"""TCP socket state data for TSDB"""
#
# Read /proc/net/tcp, which gives netstat -a type
# data for all TCP sockets.
# Note this collector generates a lot of lines, given that there are
# lots of tcp states and given the number of subcollections we do.
# We rely heavily on tcollector's deduping. We could be lazy an... |
import json
import unittest
from base64 import b64encode, b64decode
from unittest.mock import patch, MagicMock
from spresso.model.authentication.tag import Tag, TagBase
from spresso.model.base import Composition
from spresso.utils.base import create_nonce
from spresso.utils.crypto import decrypt_aes_gcm
class TagBa... |
# Import Python module(s)
import logging
from django import forms
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.edit import CreateView
from django.contrib.auth import authenticate, login
from social.apps.django_app.utils import psa
from .form... |
# -*- coding: utf-8 -*-
'''
Created on 01-Dec-2014
@author: 3cky
'''
import os
from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.web.resource import Resource
from twisted.web import server
from... |
import glob
import os
import datetime
import time
import subprocess
import lib.pushdata
import lib.puylogger
import lib.record_rate
import lib.getconfig
sh_home=os.path.split(os.path.dirname(__file__))[0]+'/scripts_enabled'
shell_scripts=glob.glob(sh_home+"/check_*")
cluster_name = lib.getconfig.getparam('SelfConfig... |
from __future__ import unicode_literals
import re
import sys
import time
import xbmc
import xbmcplugin
import add
import lib.plugin as plugin
import lib.string as string
import lib.urls as urls
plugin_info = plugin.PluginInfo()
plugin_handle = int(sys.argv[1])
def channels(connect_handle, id_number):
url = ur... |
import pathlib
from django.conf import settings
from django.core.cache import DEFAULT_CACHE_ALIAS, caches
from django.core.cache.backends.filebased import FileBasedCache
from . import Error, Tags, Warning, register
E001 = Error(
"You must define a '%s' cache in your CACHES setting." % DEFAULT_CACHE_ALIAS,
id... |
#!/usr/bin/env python
"""
<Program Name>
test_exceptions.py
<Author>
Vladimir Diaz
<Started>
December 20, 2016.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test cases for exceptions.py (mainly the exceptions defined there).
"""
# Help with Python 3 compatibility, where the print stateme... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# Vladimír Slávik 2012
# Python 3.2
#
# for Simutrans
# http://www.simutrans.com
#
# code is public domain
#
# read all dat files in all subfolders
# reformat pictures and save aside
import os, math, sys
import simutools
#-----
Data = []
paksize = 128
outdir = ... |
import logging
from odoo import api, SUPERUSER_ID
_logger = logging.getLogger(__name__)
__name__ = "Upgrade to 11.0.2.0.0"
def _migrate_product_to_product_mrp_area(env):
_logger.info("Migrating product parameters to Product MRP Areas")
env.cr.execute("""
SELECT DISTINCT mrp_area.id, pr.id, pr.mrp_ap... |
# coding=utf-8
from unittest2 import TestCase
from syntaxnet_wrapper.src.utils.pos_aggregation import pos_aggregate
class TestPostAggregation(TestCase):
def test_pos_aggregate(self):
test_values = [
([{u'1': {u'index': 1, u'token': u'il', u'pos': u'_',
u'feats':... |
import unittest
import itertools
import numpy as np
from pyscf.lib import finger
from pyscf.pbc import gto as pbcgto
from pyscf.pbc import scf as pbcscf
from pyscf.pbc import df as pbc_df
import pyscf.cc
import pyscf.pbc.cc as pbcc
import pyscf.pbc.tools.make_test_cell as make_test_cell
from pyscf.pbc.lib import kpts... |
#!/usr/bin/env python
# pxf_manual_failover.py
# This python script will adapt the PXF external tables to the new NameNode in case
# of High Availability manual failover.
# The script receives as input the new namenode host and then goes over each external
# table entry in the catalog table pg_exttable and updates th... |
"""Class for display on tft using linuxfb."""
import asyncio
import cairocffi as cairo
from cairotft import linuxfb
class TftDisplay():
"""Display class for the tft display.
:ivar fb_interface: (:py:class:`str`) framebuffer interface
name (ex: /dev/fb0)
:ivar cairo_format: (:py:class:`int`) cai... |
import numpy as np
import pandas as pd
def get_precip_data():
return pd.read_csv('precipitation.csv', parse_dates=[2])
def date_to_month(d):
return '%04i-%02i' % (d.year, d.month)
def pivot_months_pandas(data):
"""
Create monthly precipitation totals for each station in the data set.
This... |
'''
SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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, either version 3 of the License, or
(at your option) any later version.
... |
def new(num_buckets=256):
"""Initializes a Map with the given number of buckets."""
aMap = []
for i in range(0, num_buckets):
# Append an empty list to each list index between 0 and 256
aMap.append([])
return aMap
def hash_key(aMap, key):
"""Given a key this will create a number and... |
# -*- coding: utf-8 -*-
# import csv
import csv
from os import path
from promrep.models import (
DateInformation, DateType, Person, Praenomen, SecondarySource, Sex
)
ICSV_COLUMNS = [
"person_id",
"praenomen",
"nomen",
"re",
"cognomen",
"other_names",
"date_1",
"date_1_uncertain",
... |
from six.moves.urllib import parse
from oslo_log import log as logging
from oslo_config import cfg
from designate.objects.adapters import base
from designate.objects import base as obj_base
from designate import exceptions
LOG = logging.getLogger(__name__)
cfg.CONF.import_opt('api_base_uri', 'designate.api', group='... |
#!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatib... |
import logging
import time
# Allow some request objects to be imported from here instead of requests
import warnings
from datetime import datetime, timedelta
from typing import Dict, Optional, Union
from urllib.parse import urlparse
from urllib.request import urlopen
import requests
from loguru import logger
from req... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0002_auto_20150524_1148'),
]
operations = [
migrations.AlterModelOptions(
... |
#!/usr/bin/env python3
"""This script provides a RESTful remote endpoint to the detection pipeline.
An image is sent to the server, which sends back the requested results.
"""
import inspect
import io
import json
from tempfile import NamedTemporaryFile
from urllib import parse
import cachetools
import msgpack
import ... |
'''
Simple Service listening
'''
import logging
import pprint
from lofar.messaging import RPCService, ServiceMessageHandler
from lofar.sas.resourceassignment.resourceassignmentestimator.resource_estimators import \
ObservationResourceEstimator, \
LongBaselinePipelineResourceEstimator, \
CalibrationPipelin... |
import inflection
class FieldsMixin(object):
fields = dict()
related_fields = dict()
def get_fields(self):
return self.fields
def get_related_fields(self):
return self.related_fields
def get_fieldsets(self, related=None):
fields = dict()
if related:
... |
from constraint_handler import *
from rated_statistic_storage import *
import rospy
from arni_msgs.msg import RatedStatistics
from arni_core.host_lookup import *
from std_srvs.srv import Empty
import helper
import time
class CountermeasureNode(object):
"""A ROS node.
Evaluates incoming rated statistics with ... |
#!/usr/bin/env python
import time
from apps.webdriver_testing.pages.site_pages import UnisubsPage
from search_page import SearchPage
class DjangoAdminPage(UnisubsPage):
"""Sequences the require objects from multiple pages.
"""
_URL = "admin"
_ADMIN_LINK = "div#admin_controls a span"
_DJANGO_LOGIN... |
"""
Unit tests for PrettyExpression class
"""
from prettymath.prettyexpression import PrettyExpression
import unittest
class Key(object):
def __init__(self, keysym=None, char=None, state=0):
self.keysym = keysym
if char is None and keysym is not None:
self.char = self.keysym
e... |
# -*- coding: utf-8 -*-
#歧視無邊,回頭是岸。鍵起鍵落,情真情幻。
## Loading datasets
import pyCHNadm1 as CHN
## Loading seaborn and other scientific analysis and visualization modules
## More: http://stanford.edu/~mwaskom/software/seaborn/tutorial/axis_grids.html
import numpy as np
import pandas as pd
import seaborn as sns
from scipy i... |
#!/usr/bin/env python
# Using netvlad tensorflow-v1 implementation from https://github.com/uzh-rpg/netvlad_tf_open/
# For ROS melodic, follow the following instructions to rebuild cv_bridge with Python3
# https://medium.com/@beta_b0t/how-to-setup-ros-with-python-3-44a69ca36674
# On Jetpack 4.4 (18.04 and OpenCV4), use... |
import math
import constants
class Pathfinding:
def find_path_to_point(self, robot_position, point):
delta_x = float(point[0] - robot_position.position[0])
delta_y = float(point[1] - robot_position.position[1])
# We assume 0 degree is when the robot is facing away from the kinect, 90 degre... |
from buildbot.data import properties
from buildbot.test.fake import fakedb
from buildbot.test.util import endpoint
from twisted.trial import unittest
class BuildsetPropertiesEndpoint(endpoint.EndpointMixin, unittest.TestCase):
endpointClass = properties.BuildsetPropertiesEndpoint
resourceTypeClass = properti... |
import uuid
from openstack.network.v2 import router
from openstack.tests.functional import base
class TestDVRRouter(base.BaseFunctionalTest):
NAME = uuid.uuid4().hex
UPDATE_NAME = uuid.uuid4().hex
ID = None
@classmethod
def setUpClass(cls):
super(TestDVRRouter, cls).setUpClass()
... |
# -*- coding: utf-8 -*-
import ragendja
from ragendja.settings_pre import *
# Increase this when you update your media on the production site, so users
# don't have to refresh their cache. By setting this your MEDIA_URL
# automatically becomes /media/MEDIA_VERSION/
MEDIA_VERSION = 1
# Make this unique, and don't shar... |
"""A source of audio signal that connects to the
:py:class:`~pyfmodex.channel_group.ChannelGroup` mixing
hierarchy.
"""
from ctypes import *
from .channel_control import ChannelControl
from .fmodobject import _dll
from .globalvars import get_class
from .utils import check_type, ckresult
class Channel(ChannelControl)... |
from . import config # noqa
from . import mock # noqa
from .assertions import assert_raises # noqa
from .assertions import assert_raises_context_ok # noqa
from .assertions import assert_raises_message # noqa
from .assertions import assert_raises_message_context_ok # noqa
from .assertions import assert_raises_retu... |
import pytest
from datadog_checks.nginx import VTS_METRIC_MAP
from .common import TAGS, USING_VTS
pytestmark = pytest.mark.skipif(not USING_VTS, reason='Not using VTS')
@pytest.mark.usefixtures('dd_environment')
def test_vts(check, instance_vts, aggregator):
check = check(instance_vts)
check.check(instance... |
from django.contrib import admin
from .models import *
class GestionInternaInline(admin.TabularInline):
model = GestionInterna
extra = 1
max_num = 4
class OperacionesInline(admin.TabularInline):
model = Operaciones
extra = 1
max_num = 4
class SostenibilidadInline(admin.TabularInline):
mod... |
import optparse
import sys
import subprocess
import m5
from m5.objects import *
from m5.util import addToPath
addToPath('../common')
import MemConfig
import HMC
parser = optparse.OptionParser()
# Use a HMC_2500_x32 by default
parser.add_option("--mem-type", type = "choice", default = "HMC_2500_x32",
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
generate_application_descriptors.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******... |
from testframework import *
# << Select tests >> (1 of 5)
test_string = """
a = %d
Select Case a
Case 1
b = 10
Case 2
b = 20
Case 3
b = 30
Case Else
b = 40
End Select
"""
for aval, result in ((1,10), (2,20), (3,30)... |
import random
from player import Bot
class LogicalBot(Bot):
def onGameRevealed(self, players, spies):
self.players = players
self.spies = spies
self.team = None
self.taboo = []
def select(self, players, count):
me = [p for p in players if p.index == self.index]
... |
import json
class PropertiesObject(object):
"""Simple object which provides nice repr, to_dict, etc. for attributes and properties"""
def to_dict(self):
d = self._properties()
d.update(self._attributes())
return d
def to_json(self):
return json.dumps(self.to_dict())
... |
from oslo_config import cfg
from oslo_log import log as logging
from sahara import conductor as cond
from sahara import context
from sahara.i18n import _LI
from sahara.i18n import _LW
from sahara.plugins import provisioning as common_configs
from sahara.utils import cluster as c_u
CONF = cfg.CONF
LOG = logging.getL... |
"""
============================
Clipping images with patches
============================
Demo of image that's been clipped by a circular patch.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook
# nodebox section
if __name__ == '__builtin__':
# were in node... |
# coding: utf-8
import os
import re
import copy
import mistune
root = os.path.dirname(__file__)
class MathBlockGrammar(mistune.BlockGrammar):
block_math = re.compile("^\$\$(.*?)\$\$", re.DOTALL)
latex_environment = re.compile(
r"^\\begin\{([a-z]*\*?)\}(.*?)\\end\{\1\}",
re.DOTALL
)
cla... |
import tools
def logout():
'''
Logs out of the current user
'''
return tools.term('pkill -u $USER')
def get_cpu_percent():
'''
Gets the current CPU percent
'''
return tools.term("vmstat 1 2 | tail -1 | awk '{print 100-$15}'")
def get_cpu_temp():
'''
Gets the current CPU tem... |
''' Manage route53 hosted zones '''
# Copyright 2016 CityGrid Media, LLC
#
# 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/LICENSE-2.0
#
# Unless req... |
# Simulated Computer with a 6502 CPU
# https://github.com/wynand1004/6502_Assembly_Simulator
# By wynand1004 & 18melissa40
# Python 2 Compatibility
try:
import Tkinter as tkinter
except:
import tkinter
import random
from cpu_6502 import CPU
root = tkinter.Tk()
root.title("6502 Assembler Simulator")
class Displa... |
import os, shutil, subprocess
from optparse import OptionParser
parser = OptionParser()
parser.add_option(
"--use-as-ds-source",
action = "store",
dest = "ds_source",
default = None,
help = """\
When given, use this as the source for the Debian package instead. Default \
%default."""
)
pa... |
#coding=utf-8
'''
Created on 2014年6月21日
@author: JianMing Song
'''
import numpy as np
from nnet import sigm
def sigmrnd(x):
return np.array(1/(1+np.exp(-x))>np.random.random_sample(x.shape),dtype=np.float)
class rbm(object):
#初始化rbm
#n_in 输出的样本的维度
#n_out 输出的数据的维度
#momentum 动量
#alpha alpha
... |
"""Utilities to convert imagery protobufs to other formats."""
import numpy as np
from pybullet_envs.minitaur.vision import imagery_pb2
# TODO(b/123306148): Support the conversion from image array to the proto.
def convert_image_to_array(image):
"""Converts an Image proto into a numpy array.
Args:
image: A... |
import logging
from django.http import HttpResponse
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import View, FormView
from django.utils import timezone
from django.utils.decorators import method_decorator
from oauthlib.oauth2 import Server
from braces.views import Lo... |
from __future__ import unicode_literals
import datetime
from django.forms.utils import flatatt, pretty_name
from django.forms.widgets import Textarea, TextInput
from django.utils import six
from django.utils.encoding import (
force_text, python_2_unicode_compatible, smart_text,
)
from django.utils.functional impo... |
"""Leetcode 12. Integer to Roman
Medium
URL: https://leetcode.com/problems/integer-to-roman/
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
... |
"""Main functions/coroutines that fire directory walking, song uploads, file/dir deletion, and retry logic."""
import asyncio
import logging
import time
from flash_air_music.configuration import GLOBAL_MUTABLE_CONFIG
from flash_air_music.exceptions import FlashAirError, FlashAirNetworkError, FlashAirURLTooLong
from f... |
from . import dropbox
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import mock
import unittest
from hpOneView.connection import connection
from hpOneView.resources.settings.versions import Versions
from hpOneView.resources.resource import ResourceClient
class VersionsTest(unittest.TestCase):
def setUp(self):
self.host = '127.0.0.1'
self.connection = connection(s... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time, unittest
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class 111(unittest.TestCas... |
TYPE_DOCUMENT = 'document'
TYPE_RECORD = 'record'
TYPE_ENTITY = 'entity'
TYPE_LINK = 'link'
TYPE_LEAD = 'lead'
DOCUMENT_MAPPING = {
"_all": {
"enabled": True
},
"dynamic_templates": [
{
"text": {
"match": "parent.*",
"mapping": {
... |
from datetime import datetime as dt, timedelta
from .. import const
from .case_type import CaseType
from .milestone import Milestone
from .model_base import ModelBase
from .posters import Addable, Deleteable, Updatable
from .priority import Priority
from .section import Section
from .suite import Suite
from .template ... |
"""Functions for reading and writing graphs in the *graph6* format.
The *graph6* file format is suitable for small graphs or large dense
graphs. For large sparse graphs, use the *sparse6* format.
For more information, see the `graph6`_ homepage.
.. _graph6: http://users.cecs.anu.edu.au/~bdm/data/formats.html
"""
fr... |
from .views import MainView, ViewFactory, load_css
from gi.repository import Gtk, Gio, Gdk
from .controllers import MainController
from .models import Configuration
class App(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self, application_id='TLP.Configuration')
self.window ... |
#! /usr/bin/python
import serial, time, sys, string
import os
import re
import crcmod
from binascii import unhexlify
#Commands with CRC cheats
#QPI # Device protocol ID inquiry
#QID # The device serial number inquiry
#QVFW # Main CPU Firmware version inquiry
#QVFW2 # Another C... |
import os
from buildbot.status import builder
from buildbot.status import master
from buildbot.test.fake import fakemaster
from twisted.trial import unittest
class TestBuildStepStatus(unittest.TestCase):
# that buildstep.BuildStepStatus is never instantiated here should tell you
# that these classes are not... |
import sys
import setuptools
from version import __version__ as version
requirements = ['tornado', 'praw>=3.3.0', 'six', 'requests', 'kitchen']
# Python 2: add required concurrent.futures backport from Python 3.2
if sys.version_info.major <= 2:
requirements.append('futures')
setuptools.setup(
name='rtv',
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import copy
import re
import sys
from ansible import constants as C
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection
from ansible.plugins.action.normal import ActionModule as _A... |
#!/usr/bin/env python
from __future__ import print_function
import unittest, sys, threading, struct, logging, os
from vpp_papi import VPP
from ipaddress import *
import glob, json
papi_event = threading.Event()
import glob
import fnmatch
import os
jsonfiles = []
for root, dirnames, filenames in os.walk('../../../bu... |
"""Greedy distributions with respect to a set of preferences."""
import chex
from distrax._src.distributions import categorical
import jax.numpy as jnp
Array = chex.Array
def _argmax_with_random_tie_breaking(preferences: Array) -> Array:
"""Compute probabilities greedily with respect to a set of preferences."""
... |
#!/usr/bin/env python
# Dexter Industries line sensor basic example
#
# This example shows a bsic example to read sensor data from the line sensor
#
# Have a question about this example? Ask on the forums here: http://www.dexterindustries.com/forum/?forum=grovepi
#
# Karan Nayan
# Initial Date: 13 Dec 2015
# Last Upd... |
"""
guitarscalefinder.py:
Handler for GuitarScaleFinder
* Author: Mitchell Bowden <mitchellbowden AT gmail DOT com>
* License: MIT License: http://creativecommons.org/licenses/MIT/
"""
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp
from google.appengine.... |
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidget... |
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) Th... |
#!/usr/bin/python
# coding: utf-8
import os
import argparse
import getpass
from deploy import (
prompt, confirm, config_path,
create_virtualenv, install_requirements,
create_env_file, create_user_config_file,
delete_common_files, logger,
setup_npm_tools,
)
from deploy.settings import ENV_FILE, PR... |
import os
import sys
import locale
import gettext
# Python 2/3 compatibility.
from six import PY2
import pkg_resources
from plover import log
# Mark some strings for localization.
def _unused():
# Machines.
_('Keyboard')
# States.
_('stopped')
_('initializing')
_('connected')
_('disconn... |
# coding: utf-8
from django.conf import settings
from django.core.files import File
from django.template import Library, Node, Variable, VariableDoesNotExist, TemplateSyntaxError
from filebrowser.settings import VERSIONS, PLACEHOLDER, SHOW_PLACEHOLDER, FORCE_PLACEHOLDER
from filebrowser.base import FileObject
from fi... |
import uuid
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateKey,
RSAPrivateNumbers,
RSAPublicNumbers,
generate_private_key,
rsa_crt_dmp1,
rsa_crt_dmq1,
rsa_crt... |
from .activity import Activity
from .data_type import DataType
from .desirability import Desirability
class User(DataType):
def __init__(self, id, name):
self.id = int(id)
self.name = unicode(name)
def deflate(self):
return {
'_id': self.id,
'name': self.name
}
@staticmethod
def inflate(do... |
from collections import namedtuple
from cStringIO import StringIO
import logging
import gzip
import select
import socket
import struct
import zlib
from .codec import gzip_encode, gzip_decode
log = logging.getLogger("kafka")
error_codes = {
-1: "UnknownError",
0: None,
1: "OffsetOutOfRange",
2: "Invali... |
from __future__ import division, print_function, unicode_literals
from .converter import Comment, Assignment
class Outputter(object):
_groups = {
'io_devices': 'I/O Devices',
'variables': 'Variables',
'sounds': 'Sounds',
'stimuli': 'Stimuli',
'filters': 'Filters',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See http://doc.qt.io/qt-5/qdatetimeedit.html#details
import sys
import datetime
from PyQt5.QtWidgets import QApplication, QWidget, QDateTimeEdit, QPushButton, QVBoxLayout
class Window(QWidget):
def __init__(self):
super().__init__()
# Make widge... |
import midi
import sys
def get_instr_stats(filename):
"""Get a set of instruments used by the specified MIDI file."""
result = set()
midfile = midi.read_midifile(filename)
for track in midfile:
for event in track:
if isinstance(event, midi.ProgramChangeEvent) \
and event.channel != 9:
instr = event... |
#
# Loop transformation submodule that enables pragma directive insertions.
#
import sys
import module.loop.submodule.submodule, transformator
#---------------------------------------------------------------------
class Pragma(module.loop.submodule.submodule.SubModule):
'''The pragma directive insertion submodul... |
GL_VERSION_1_1 = 1
GL_ACCUM = 0x0100
GL_LOAD = 0x0101
GL_RETURN = 0x0102
GL_MULT = 0x0103
GL_ADD = 0x0104
GL_NEVER = 0x0200
GL_LESS = 0x0201
GL_EQUAL = 0x0202
GL_LEQUAL = 0x0203
GL_GREATER = 0x0204
GL_NOTEQUAL = 0x0205
GL_GEQUAL = 0x0206
GL_ALWAYS = 0x0207
GL_CURRENT_BIT = 0x00000001
GL_POINT_BIT = 0x00000002
GL_LINE_B... |
""" Tests for manage_existing TaskFlow """
import mock
from cinder import context
from cinder import test
from cinder.tests.unit import fake_constants as fakes
from cinder.tests.unit import fake_volume
from cinder.tests.unit.volume.flows import fake_volume_api
from cinder.volume.flows.api import manage_existing
from ... |
from __future__ import absolute_import
import re
from bs4 import BeautifulSoup
from six import StringIO
from six import PY3
from fulltext.util import BaseBackend
class Backend(BaseBackend):
def setup(self):
self.bs = None
def is_visible(self, elem):
if elem.parent.name in ['style', 'scri... |
import unittest
import ocw.data_source.dap as dap
from ocw.dataset import Dataset
import datetime as dt
class TestDap(unittest.TestCase):
@classmethod
def setup_class(self):
self.url = 'http://test.opendap.org/dap/data/nc/sst.mnmean.nc.gz'
self.name = 'foo'
self.dataset = dap.load(self.... |
from django.db import models
from django.contrib.auth.models import User
from base.models import Lexicon
# Create your models here.
class GenericTableGameModel(models.Model):
WORDWALLS_GAMETYPE = 1
WORDGRIDS_GAMETYPE = 2
SINGLEPLAYER_GAME = 1
MULTIPLAYER_GAME = 2
GAME_TYPES = (
(WORDWALL... |
from unittest import TestCase
from neo.VM.InteropService import StackItem, Array, Map
from neo.VM.ExecutionEngine import ExecutionEngine
from neo.VM.ExecutionEngine import ExecutionContext
from neo.VM.Script import Script
from neo.SmartContract.Iterable import KeysWrapper, ValuesWrapper
from neo.SmartContract.Iterable.... |
import abc
import copy
import httplib
import time
import eventlet
from oslo_utils import excutils
import six
import six.moves.urllib.parse as urlparse
from neutron.i18n import _LI, _LW
from neutron.openstack.common import log as logging
from neutron.plugins.vmware import api_client
LOG = logging.getLogger(__name__)
... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 the Software without restriction, including without limitation
the rights to u... |
import pathlib
import shutil
import sys
import pytest
import uqbar.apis
from uqbar.strings import normalize
@pytest.fixture
def test_path():
test_path = pathlib.Path(__file__).parent
docs_path = test_path / "docs"
if str(test_path) not in sys.path:
sys.path.insert(0, str(test_path))
if docs_... |
from __future__ import print_function
from datetime import datetime
import re
import urllib2
from six import u
from wtframework.wtf._devtools_.filetemplates import _page_object_template_
def _process_input_tag(html):
html = html.lower()
# find name property expression, used is varous input types.
name_... |
#!/usr/bin/python2
import ctypes
import ctypes.util
import sys
class Magic(object):
''' Magic wrapper '''
def __init__(self, flags=None):
self.NONE = 0x000000 # No flags
self.DEBUG = 0x000001 # Turn on debugging
self.SYMLINK = 0x000002 # Follow symlinks
... |
import unittest
import rpy2.robjects as robjects
ri = robjects.rinterface
import array, time, sys
import rpy2.rlike.container as rlc
IS_PYTHON3 = sys.version_info[0] == 3
rlist = robjects.baseenv["list"]
class VectorTestCase(unittest.TestCase):
def testNew(self):
identical = ri.baseenv["identical"]
... |
'''
Modules: hmtk.strain.regionalisation.kreemer_regionalisation implements the
class KreemerRegionalisation, which assigns a strain model to a tectonic
region according to the classification of Kreemer, Holt and Haines (2003)
'''
import os
import numpy as np
from linecache import getlines
KREEMER_GLOBAL_0506 = os.pat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.