content stringlengths 4 20k |
|---|
import time
from math import pi, radians
from euclid import Point2
from triangula.chassis import DeadReckoning, Motion, Pose, rotate_point
from triangula.dynamics import MotionLimit
from triangula.navigation import TaskWaypoint
from triangula.task import Task, ExitTask, PauseTask
from triangula.util import IntervalChe... |
# -*- coding: utf-8 -*-
import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
... |
import BoostBuild
t = BoostBuild.Tester()
t.write("jamroot.jam", """
exe hello : hello.cpp ;
exe hello2 : hello.cpp ;
explicit hello2 ;
""")
t.write("hello.cpp", """
int main() {}
""")
t.run_build_system()
t.ignore("*.tds")
t.expect_addition(BoostBuild.List("bin/$toolset/debug/hello") * \
[".exe", ".obj"])
t.ex... |
from w3lib.http import headers_dict_to_raw
from scrapy.utils.datatypes import CaselessDict
class Headers(CaselessDict):
"""Case insensitive http headers dictionary"""
def __init__(self, seq=None, encoding='utf-8'):
self.encoding = encoding
super(Headers, self).__init__(seq)
def normkey(s... |
from cudamat_conv.cudamat_conv import _ConvNet as ConvNet
import gnumpy as g
imSizeX = 5
numImages = 2
filterSizeX = 3
numChannels = 3
numGroups = 1
assert numChannels % numGroups == 0
numFilterColors = numChannels / numGroups
numFilters = 16 * numGroups
moduleStride = 1
numModulesX = (imSizeX - filterSizeX + 1)
n... |
#!/usr/bin/env python
"""
basic plotting of Neo/Zyla sCMOS Andor Solis spool files,
to confirm you have settings correct.
ticks[-1]-ticks[-2] 2015-10-19
615517
>>> 615517/0.0153846
40008645.008645006
ticks[1]-ticks[0] 2017-04-05
1333372
>>> 1333372/0.0333248
40011402.9191473
>>>
"""
from datetime import datetime, ... |
import unittest
from mock import MagicMock, patch
from pgmpy.factors import Factor, TabularCPD, State
from pgmpy.inference.Sampling import BayesianModelSampling, GibbsSampling
from pgmpy.models import BayesianModel, MarkovModel
from pgmpy.extern import six
class TestBayesianModelSampling(unittest.TestCase):
def... |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from patients.models import Paciente
from exam.models import Exam
@login_required(login_url='/', redirect_field_name='')
def search_res... |
import sublime, sublime_plugin
def extract_lines(view,edit):
regions = [s for s in view.sel() if not s.empty]
if not regions:
regions = [sublime.Region(0,view.size())]
for region in regions:
text = view.substr(region)
lines = text.splitlines()
return lines
def get_line_value_pair(lines,duplicate_keys):
i ... |
""" Transform each word in the Book Genesis into a feature vector using word2vec and runs the MDI algorithm on the book to search for anomalous paragraphs. """
import sys
sys.path.append('../..')
import time
import numpy as np
from nltk.corpus import genesis
from maxdiv.maxdiv import maxdiv
import textutil... |
"""
BSON serialization and deserialization logic.
Specifications taken from: http://bsonspec.org/#/specification
The following types are unsupported, because for data exchange purposes, they're
over-engineered:
0x06 (Undefined)
0x07 (ObjectId)
0x0b (Regex - Exactly which flavor do you want? Better let higher level
... |
import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pyarrow as pa
class PandasConversionsBase(object):
def setup(self, n, dtype):
if dtype == 'float64_nans':
arr = np.arange(n).astype('float64')
arr[arr % 10 == 0] = np.nan
else:
arr =... |
# -*- coding: utf-8 -*-
"""Parser for Windows Restore Point (rp.log) files."""
from dfdatetime import filetime as dfdatetime_filetime
from dfdatetime import semantic_time as dfdatetime_semantic_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from pla... |
import ROOT
import sys
"""
simple progress bar
"""
def drawProgressBar(percent, barLen = 100):
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i < int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.1f%%" % (pro... |
"""Python console command to invoke TOCO from serialized protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.platform import app
FLAGS = None
def exec... |
import time
from contextlib import contextmanager
from distutils.version import StrictVersion as V
import serial
# pylint: disable=ungrouped-imports, wrong-import-position
import pexpect
if V(pexpect.__version__) < V('4.0.0'):
import fdpexpect # pylint: disable=import-error
else:
from pexpect import fdpexpec... |
# -*- coding:utf-8 -*-
import re
import time
import chardet
import HTMLParser
import datetime
from report_crawler.spiders.__Global_function import get_localtime
def sub_linefeed(text):
sub_text = ''
for line in text.splitlines():
line = line.rstrip()
if line != '':
line += '\n'
sub_text += line
return su... |
################################################################################
# Imports
# StdLib
import sys
import os
import re
import cgi
import cgitb
import time
import glob
import shutil
import traceback
# User Libs
import callproc
import config
import upload_results
from regexes import *
f... |
from . import Command
from math import floor
COMMANDS = {
'ON': (Command(0x42, wait=True), # All
Command(0x45, wait=True), # Group 1
Command(0x47, wait=True), # Group 2
Command(0x49, wait=True), # Group 3
Command(0x4B, wait=True)), # Group 4
'OFF': (Comm... |
""" T5 model configuration """
from ...configuration_utils import PretrainedConfig
from ...utils import logging
logger = logging.get_logger(__name__)
T5_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
"t5-base": "https://huggingface.co/t5-base/resolv... |
__description = \
"""
Create a call graph in the DOT format from execution profile dumps generated
with the cProfile module. The DOT file format is common for graph
visualization tools; it comes from the Graphviz package.
This script accepts several profile dumps as input and allows some aggregation
and grouping of t... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('silver', '0003_auto_20150417_0634'),
]
operations = [
migrations.AddField(
model_name='invoice',
name='series',
... |
import ConfigParser
import os
import socket
import warnings
from beaver.utils import eglob
class BeaverConfig():
def __init__(self, args, file_config=None, logger=None):
self._logger = logger
self._logger.debug('Processing beaver portion of config file %s' % args.config)
self._beaver_de... |
import xml.parsers.expat
data = """<?xml version="1.0" encoding="UTF-8"?>
<gml:FeatureCollection xmlns:fme="http://www.safe.com/gml/fme" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gml="http://www.opengis.net/gml" xsi:schemaLocation="http://www.safe.com/gml/fm... |
import unittest
import IECore
import Gaffer
import GafferTest
import GafferScene
import GafferSceneTest
class CustomOptionsTest( GafferSceneTest.SceneTestCase ) :
def test( self ) :
p = GafferScene.Plane()
options = GafferScene.CustomOptions()
options["in"].setInput( p["out"] )
# check that the scene hie... |
# -*- coding: utf-8 -*-
"""The data range file system implementation."""
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import data_range_path_spec
from dfvfs.vfs import data_range_file_entry
from dfvfs.vfs import root_only_file_system
class DataRangeFileSystem(root_only_file_system.R... |
"""
JSON AMP dialect.
This is a *huge* hack.
"""
from json import dumps, loads
from twisted.internet import defer, protocol
from twisted.protocols import amp, basic
from txampext import exposed
def _default(obj):
# TODO: Seriously? This? What the ugh.
try:
return list(obj)
except TypeError:
... |
"""Self-test suite for Cryptodome.Cipher.DES"""
import unittest
from Cryptodome.Cipher import DES
# This is a list of (plaintext, ciphertext, key, description) tuples.
SP800_17_B1_KEY = '01' * 8
SP800_17_B2_PT = '00' * 8
test_data = [
# Test vectors from Appendix A of NIST SP 800-17
# "Modes of Operation Val... |
from IPy import IP
from collections import namedtuple
from gi.repository import GLib
from pyanaconda import constants
from pyanaconda.threads import threadMgr, AnacondaThread
from pyanaconda.ui.gui import GUIObject
from pyanaconda.ui.gui.utils import escape_markup
from pyanaconda.i18n import _
from pyanaconda import n... |
"""Test Wallet encryption"""
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_raises_rpc_error,
assert_greater_than,
assert_greater_than_or_equal,
)
class WalletEncryptionTest(BitcoinTestFramework):
def set_test_params(self):
... |
from typing import List
from flask import url_for
from decksite.data.archetype import Archetype
from decksite.view import View
from magic.models import Deck
from shared.container import Container
# pylint: disable=no-self-use, too-many-instance-attributes, too-many-arguments
class EditRules(View):
def __init__(... |
import paho.mqtt.client as mqtt
import jetson_config_i as config
import ev3dev.ev3 as ev3
import ev3control.master as master
from ev3control.messages import *
"""
Motors A,D are motion motors
Motor B is lifting motor
Motor C is clamp motor
"""
def addActuatorDevices(client,topic):
#Use same names as in actuators_and... |
# encoding: utf-8
from expects import *
import json
from cetacean import Cetacean
with describe("Cetacean"):
with context("when fed a valid HAL document"):
with before.each:
self.subject = Cetacean(
json.dumps(
{
'_links': {
... |
"""
Message Handler is used to process a message received.
"""
from .errors import SimpleBusError
from .pipeline import PipelineStep
class InvokeHandlerStep(PipelineStep):
id = 'InvokeHandler'
def __init__(self, handlers):
self.__handlers = handlers
def execute(self, context, next_step):
... |
try:
import uzlib as zlib
import uio as io
except ImportError:
import sys
print("SKIP")
sys.exit()
# gzip bitstream
buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00')
inp = zlib.DecompIO(buf, 16 + 8)
print(buf.seek(0, 1))
print... |
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from solver import solve
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import random as rn
tf.logging.set_verbosity(tf.logging.ERROR)
# MAKE IT DETERMINISTIC
np.r... |
"""Test of Policy Engine For Nova"""
import os.path
import StringIO
import urllib2
from nova import context
from nova import exception
from nova import flags
from nova.openstack.common import policy as common_policy
from nova import policy
from nova import test
from nova import utils
FLAGS = flags.FLAGS
class Pol... |
__author__ = "Simone Campagna"
__all__ = [
'Parser',
'load_parser',
]
import collections
import configparser
import datetime
import inspect
import os
from . import conf
from .error import InvoiceDuplicatedLineError, InvoiceKeyConversionError
from .log import get_default_logger
from .files import create_file_d... |
import json
import six
from runtime.feature.field_desc import DataType, FieldDesc
class FeatureColumn(object):
"""
FeatureColumn corresponds to the COLUMN clause in the TO TRAIN statement.
It is the base class of all feature column classes.
"""
def get_field_desc(self):
"""
Get th... |
import argparse
import os
import sys
import unittest
import pyvshadow
class SupportFunctionsTests(unittest.TestCase):
"""Tests the support functions."""
def test_get_version(self):
"""Tests the get_version function."""
version = pyvshadow.get_version()
self.assertIsNotNone(version)
def test_check... |
import proto # type: ignore
from google.cloud.scheduler_v1beta1.types import job as gcs_job
from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.cloud.scheduler.v1beta1",
manifest={
"ListJobsRequest",
"ListJobsResponse",
"GetJobReque... |
"""
Utilities for e2e tests
"""
import os
import time
import unittest
from django.conf import settings
from django.test import LiveServerTestCase
from selenium.common.exceptions import WebDriverException
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.commo... |
from __future__ import print_function
import email
import getopt
import re
import sys
__errors = 0
__warnings = 0
def print_error(message, lineno=None):
global __errors
if lineno is not None:
print("E(%d): %s" % (lineno, message))
else:
print("E: %s" % (message))
__errors = __errors... |
import Image
import traceback, sys, string, os
MAXBLOCK = 65536
SAFEBLOCK = 1024*1024
ERRORS = {
-1: "image buffer overrun error",
-2: "decoding error",
-3: "unknown error",
-8: "bad configuration",
-9: "out of memory error"
}
#
# -----------------------------------------------------------------... |
import unittest
import random
from myhdl import *
from myhdl_lib.mem import rom, ram_sp_rf, ram_sp_wf, ram_sp_ar,ram_sdp_rf, ram_sdp_wf, ram_sdp_ar, ram_dp_rf, ram_dp_wf, ram_dp_ar
import myhdl_lib.simulation as sim
def mem_fill(clk, we, addr, di, content):
for a, d in enumerate(content):
we.next = 1
... |
from lunr.storage.helper.utils import execute, directio
from lunr.common.config import LunrConfig
from subprocess import call, check_output
from os import path
import unittest
import os
class IetTest(unittest.TestCase):
_ramdisk = None
vgname = 'iet-test'
@staticmethod
def sudo(cmd):
print "-... |
"""
Classes that deal with computing intervals from arrays of values based on
various criteria.
"""
from __future__ import division, print_function
import abc
import numpy as np
from ..extern import six
from ..utils.misc import InheritDocstrings
from .transform import BaseTransform
__all__ = ['BaseInterval', 'Manu... |
from __future__ import absolute_import, division, print_function
from dojson.contrib.marc21.utils import create_record
from inspirehep.dojson.experiments import experiments
from inspirehep.dojson.utils import clean_record
def test_contact_details_from_marcxml_270_single_p_single_m():
snippet = (
'<recor... |
try:
import _path
except NameError:
pass
import spyral
from functools import partial
SIZE = (640, 480)
def make_box(color):
return spyral.Image(size=(32,32)).fill(color)
class Game(spyral.Scene):
def __init__(self):
spyral.Scene.__init__(self)
self.add_style_function("make_box", make_... |
"""
add popups and image links to timeseries_analyses.html
requires two javascript libraries in the same directory:
https://raw.github.com/nhoening/popup.js/master/dist/nhpup_1.1.js
"""
import os
basedir=os.environ['MYCONNECTOME_DIR']
def add_timeseries_links():
infile=os.path.join(basedir,'timeseries/timeseri... |
import os
import cmd
import sys
import shlex
import pprint
import argparse
import synapse.neuron as s_neuron
import synapse.eventbus as s_eventbus
import synapse.datamodel as s_datamodel
class Cmd(cmd.Cmd,s_eventbus.EventBus):
def __init__(self, neu):
cmd.Cmd.__init__(self)
self.prompt = 'neu> '
... |
# -*- coding: utf-8 -*-
import gxf
@gxf.register()
class Heading(gxf.DataCommand):
'''
instruction trace thingy
'''
def setup(self, parser):
parser.add_argument("what", type=gxf.LocationType())
parser.add_argument("-c", "--count", type=int, default=10)
parser.add_argument("-b... |
"""Test Motor, an asynchronous driver for MongoDB and Tornado."""
import asyncio
import functools
import greenlet
import random
import unittest
import pymongo.errors
from test.asyncio_tests import asyncio_test, AsyncIOTestCase
import test
from test import assert_raises, SkipTest
from test.utils import delay, one
c... |
try:
from json import loads
except ImportError:
from simplejson import loads
from path import path
from dryice import plugins
thisdir = path(__file__).dirname()
plugindir = (thisdir / "plugindir").abspath()
pluginpath = [dict(name="testplugins", path=plugindir,
chop=len(plugindir))]
def ... |
import logging
from abstract import PluginException
_plugins = {}
class _ID(object):
"""
A wrapper class used to represent a plug-in as
an abstract entity which is always instantiated
(even if its respective plug-in does not exist)
and which can be asked for basic information
(name, exists?,... |
from __future__ import with_statement
import os
import sys
import re
import codecs
import py
import tox
from .config import DepConfig, hookimpl
class CreationConfig:
def __init__(self, md5, python, version, sitepackages,
usedevelop, deps):
self.md5 = md5
self.python = python
... |
"""
Common parameter types for validating request Body.
"""
import copy
import re
import unicodedata
import six
def _is_printable(char):
"""determine if a unicode code point is printable.
This checks if the character is either "other" (mostly control
codes), or a non-horizontal space. All characters th... |
from hone_lib import *
def query1():
q = (Select(['hostId','app','cpu','memory']) *
From('AppStatus') *
Every(1000))
return q
def query2():
q = (Select(['app',
'ThruOctetsReceived',
'OtherReductionsCM',
'OtherReductionsCV',
... |
# -*- coding: utf-8 -*-
#
# cx_Oracle documentation build configuration file
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically... |
import logging
import spotify
from mopidy_spotify import playlists, translator, utils, web
logger = logging.getLogger(__name__)
_VARIOUS_ARTISTS_URIS = [
"spotify:artist:0LyfQWJT6nXafLPZqxe9Of",
]
def lookup(config, session, web_client, uri):
try:
web_link = web.WebLink.from_uri(uri)
if web... |
# -*- encoding: utf-8 -*-
from supriya.tools.ugentools.PV_MagAbove import PV_MagAbove
class PV_LocalMax(PV_MagAbove):
r'''Passes bins which are local maxima.
::
>>> pv_chain = ugentools.FFT(
... source=ugentools.WhiteNoise.ar(),
... )
>>> pv_local_max = ugentools.PV_L... |
import re,string,operator,os
def process_file(filename, guten):
hist = dict()
fp = open(filename)
if guten:
header = True
if not guten:
header = False
for line in fp:
if line[:20] == "*** END OF THIS PROJ": # There must be a better way to escape the header and footer
... |
import dns
import os
from recursortests import RecursorTest
class DNS64RecursorTest(RecursorTest):
_auth_zones = {
'8': {'threads': 1,
'zones': ['ROOT']}
}
_confdir = 'DNS64'
_config_template = """
auth-zones=example.dns64=configs/%s/example.dns64.zone
auth-zones+=in-ad... |
from RGT.XML.SVG.baseStructuralNode import BaseStructuralNode
from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes
from RGT.XML.SVG.Attribs.positionAttributes import PositionAttributes
from RGT.XML.SVG.Attribs.sizeAttributes import SizeAttributes
from types import StringTy... |
import itertools
import codecs
import uncertainties
import fileinput
import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (
nominal_values as noms,
std_devs as stds,
)
from uncertainties import ufloat
def search_replace_within_file(filenameToSearch, textToSearch, textToReplace... |
# -*- coding: utf-8 -*-
"""Helper to the Dataset class for handling resources with filestores.
"""
from typing import List, Dict, Any
from hdx.utilities.dictandlist import merge_two_dictionaries
import hdx.data.resource
class FilestoreHelper(object):
temporary_url = 'updated_by_file_upload_step'
@staticmet... |
from __future__ import print_function
import argparse
import llnl.util.tty as tty
import spack
import spack.cmd
description = "print out locations of various directories used by Spack"
section = "environment"
level = "long"
def setup_parser(subparser):
global directories
directories = subparser.add_mutuall... |
import requests
from lxml import html
def _yield_tr_rows(trs):
rv = []
for tr in trs:
if 'style' in tr.keys():
yield rv
rv = []
else:
rv.append(tr)
if rv:
yield rv
def _scrape_from_string(s):
rv = []
t = html.fromstring(s)
trs = t.css... |
#===================================================================================================
# C L A S S
#===================================================================================================
import sys, os, subprocess, re, time, shutil, string, signal, glob
import datetime
class Alarm(Exception... |
#
# Example python script to generate a BOM from a KiCad generic netlist
#
# Example: Sorted and Grouped CSV BOM
#
# Import the KiCad python helper module and the csv formatter
import ky
import csv
import sys
# Generate an instance of a generic netlist, and load the netlist tree from
# the command line op... |
import time
from jinja2 import Environment
from jinja2 import PackageLoader
from paramiko import SSHClient, AutoAddPolicy
from oslo.config import cfg
from savanna.storage.models import Node, ServiceUrl
from savanna.storage.storage import DB
from savanna.utils.openstack.nova import novaclient
from savanna.openstack.com... |
import re
procCommands = open('generated/commands.h')
asm = open('generated/assembler_generated.c', 'w')
prevWord = ''
for line in procCommands:
words = re.split('[\s_+]', line)
if prevWord != words[1]:
if prevWord != '':
asm.write('}\n\n')
asm.write('IFCMD(' + words[1].lower() + ')... |
from swift import gettext_ as _
from urllib import unquote
from swift.account.utils import account_listing_response
from swift.common.request_helpers import get_listing_content_type
from swift.common.middleware.acl import parse_acl, format_acl
from swift.common.utils import public
from swift.common.constraints import ... |
from sense_emu import SenseHat
from time import sleep
sense = SenseHat()
sense.clear()
max_speed = 40 #total magnitude range of speed (double the max speed in one direction)
r = (255,0,0) #color of the walls
g = (0,255,0) #color of the target
b = (0,0,0) #color of the floor
orient_margin = 5 #the distance from absolut... |
#!/usr/bin/env python3
import re
def show_banner(test_type):
print('##'+'-'*100)
print('##',test_type)
print('##'+'-'*100)
text = 'This is some text -- with punctuation.'
pattern = r'\bT\w+'
with_case = re.compile(pattern)
without_case = re.compile(pattern, re.IGNORECASE)
show_banner('IGNORECASE')
print... |
# -*- coding: utf-8 -*-
import copy
import functools
from rest_framework import status as http_status
import json
import logging
import os
from flask import request, make_response
from mako.lookup import TemplateLookup
from mako.template import Template
import markupsafe
from werkzeug.exceptions import NotFound
impor... |
"""
Helpers to manipulate deferred DDL statements that might need to be adjusted or
discarded within when executing a migration.
"""
class Reference:
"""Base class that defines the reference interface."""
def references_table(self, table):
"""
Return whether or not this instance references th... |
import pytest
from pip.exceptions import CommandError
from pip.basecommand import ERROR, SUCCESS
from pip.commands.help import HelpCommand
from pip.commands import commands
from mock import Mock
def test_run_method_should_return_sucess_when_finds_command_name():
"""
Test HelpCommand.run for existing command
... |
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from past.utils import old_div
import sys,numpy
#
def main():
"""
NAME
unsquish.py
DESCRIPTION
takes dec/inc data and "unsquishes" with specified flattening factor, flt
using formula tan(If)=... |
"""Test module for file ui/commands.py
"""
from __future__ import division, absolute_import, print_function
import os
import shutil
from test import _common
from test._common import unittest
from beets import library
from beets import ui
from beets.ui import commands
class QueryTest(_common.TestCase):
def set... |
"""Tests for the flatsym module of pylinac."""
import enum
import io
import os.path as osp
from unittest import TestCase
from pylinac.core.exceptions import NotAnalyzed
from pylinac.core.io import retrieve_demo_file
from pylinac.core.profile import Edge, Normalization, Interpolation
from pylinac.field_analysis import ... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # ... |
#!/usr/bin/env python
"""This script simply renders a message as a pdf and saves it to a file
(out.pdf) in the working directory
"""
import requests
BASE_URL = "https://api.handwriting.io"
API_TOKEN = "<YOUR TOKEN>"
API_SECRET = "<YOUR SECRET>"
OUT_FILE = "out.pdf"
# this is the message we will turn into handwriting... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from contextlib import contextmanager
from textwrap import dedent
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import ... |
from django.contrib.admin import site
from django.apps import apps
from django.utils.text import capfirst
from django.core.urlresolvers import reverse, NoReverseMatch
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.conf import settings
from django import template
registe... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
extract_attributes,
get_element_by_attribute,
int_or_none,
)
class SampleFocusIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?samplefocus\.com/samples/(?P<id>[^/?&#]+)'
... |
"""
ldif - generate and parse LDIF data (see RFC 2849)
written by Michael Stroeder <<EMAIL>>
See http://python-ldap.sourceforge.net for details.
$Id: ldif.py,v 1.46 2007/05/23 22:04:15 stroeder Exp $
Python compability note:
Tested with Python 2.0+, but should work with Python 1.5.2+.
"""
__version__ = '0.5.5'
__a... |
class OSVersion(str):
def __new__(cls, friendly_name, sortable_name):
version = str.__new__(cls, friendly_name)
version._sortable_name = sortable_name
return version
def __lt__(self, other):
return self._sortable_name < other._sortable_name
def __gt__(self, other):
return self._sortable_name... |
import json
from moto.core import BaseBackend
from .parsing import ResourceMap
from .utils import generate_stack_id
class FakeStack(object):
def __init__(self, stack_id, name, template):
self.stack_id = stack_id
self.name = name
self.template = template
template_dict = json.load... |
# -*- coding: utf-8 -*-
'''
Deployment toolkit.
'''
import os, re
from datetime import datetime
from fabric.api import *
__author__ = 'Li Chenxi'
env.user = 'ubuntu'
env.sudo_user = 'root'
env.hosts = ['123.206.182.83']
db_user = 'root'
db_password = 'Qxsb19981005'
_TAR_FILE = 'dist-awesome.tar.gz'
_REMOTE_TMP_... |
from ..remote import RemoteModel
class AdvSettingDefRemote(RemoteModel):
"""
This table list out the advance setting definitions.
| ``allow_empty:`` A flag indicating if this setting can be empty.
| ``attribute type:`` bool
| ``category:`` The category of this setting.
| ``attribute typ... |
"""
Utility functions for DrParse
"""
import copy
import prettytable
from novaclient import utils
# lifted from glance/common/utils.py
def bool_from_string(subject):
"""
Interpret a string as a boolean.
Any string value in:
('True', 'true', 'On', 'on', '1')
is interpreted as a boolean True... |
from sklearn.externals import joblib
import util
import os
import ipdb
import Detectors
def get_anomaly_detector(
model_save_path,
state_amount,
anomaly_detection_metric,
):
model_group_by_state = {}
for state_no in range(1, state_amount+1):
model_group_by_state[state_no] = joblib.load(mo... |
#!/usr/bin/python
from __future__ import print_function
from common import *
import dbus.service
from gi.repository import GLib
import os
import shutil
gatt_services = set([
"00001800-0000-1000-8000-00805f9b34fb",
"00001801-0000-1000-8000-00805f9b34fb",
"00001802-0000-1000-8000-00805f9b34fb",
"00001803... |
from openerp import models, fields, api
from openerp.addons import decimal_precision as dp
class StockPicking(models.Model):
_inherit = 'stock.picking'
@api.one
@api.depends('package_totals', 'package_totals.quantity')
def _compute_num_packages(self):
self.num_packages = sum(x.quantity for x ... |
__all__ = ['to_osgb36', 'from_osgb36']
try:
import numpy as np
except ImportError:
print "Numpy not installed. Numpy comes with most scientific python packages."
import re
# Region codes for 100 km grid squares.
_regions=[['HL','HM','HN','HO','HP','JL','JM'],
['HQ','HR','HS','HT','HU','JQ','JR'],
... |
""" DIRAC Notification Client class encapsulates the methods exposed
by the Notification service.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import six
from DIRAC import gLogger, S_ERROR
from DIRAC.Core.Base.Client import Cli... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
SplitLinesWithLines.py
DEPRECATED, replaced by SplitWithLines.py
---------------------
Date : November 2014
Revised : November 2016
Copyright : (C) 201... |
import pytest
from mock import patch
from . placebo_fixtures import placeboify, maybe_sleep
from ansible.modules.cloud.amazon import cloudformation as cfn_module
basic_yaml_tpl = """
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Basic template that creates an S3 bucket'
Resources:
MyBucket:
Type: "AW... |
import matplotlib.pyplot as plot
import o2sclpy
import numpy
import math
p=o2sclpy.plotter()
p.fig_dict='fig_size_x=9.7,fig_size_y=6,left_margin=0.12,bottom_margin=0.16'
p.xlimits(0,2000)
p.ylimits(0,160)
p.font=28
p.xtitle(r'$ \mu_B = 3 \mu_Q~[\mathrm{MeV}]$')
p.ytitle(r'$ T~[\mathrm{MeV}]$')
nk=30
for k in range(0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.