content string |
|---|
import os
from distutils import log
import itertools
from setuptools.extern.six.moves import map
flatten = itertools.chain.from_iterable
class Installer:
nspkg_ext = '-nspkg.pth'
def install_namespaces(self):
nsp = self._get_all_ns_packages()
if not nsp:
return
filenam... |
import fnmatch
from conans.errors import ConanException
class BuildMode(object):
""" build_mode => ["*"] if user wrote "--build"
=> ["hello*", "bye*"] if user wrote "--build hello --build bye"
=> ["hello/0.1@foo/bar"] if user wrote "--build hello/0.1@foo/bar"
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import boto3
from botocore.exceptions import ClientError, NoC... |
"""
Unit tests for hxl-proxy dao module
David Megginson
February 2016
License: Public Domain
"""
import unittest, os
from hxl_proxy import app, dao
from . import base
class AbstractDAOTest(base.AbstractDBTest):
"""Abstract base class for DAO tests."""
def setUp(self):
super().setUp()
def t... |
import numpy as np
import timeit
from concurrent.futures import ThreadPoolExecutor, wait
from .common import Benchmark, safe_import
with safe_import():
from scipy.signal import (lfilter, firwin, decimate, butter, sosfilt,
medfilt2d)
class Decimate(Benchmark):
param_names = ['q'... |
import gc
import sys
import types
import unittest
import weakref
from test import support
class ClearTest(unittest.TestCase):
"""
Tests for frame.clear().
"""
def inner(self, x=5, **kwargs):
1/0
def outer(self, **kwargs):
try:
self.inner(**kwargs)
... |
import os
import re
from subprocess import (
check_call,
check_output,
)
##################################################
# loopback device helpers.
##################################################
def loopback_devices():
'''
Parse through 'losetup -a' output to determine currently mapped
loo... |
data = (
'kax', # 0x00
'ka', # 0x01
'kap', # 0x02
'kuox', # 0x03
'kuo', # 0x04
'kuop', # 0x05
'kot', # 0x06
'kox', # 0x07
'ko', # 0x08
'kop', # 0x09
'ket', # 0x0a
'kex', # 0x0b
'ke', # 0x0c
'kep', # 0x0d
'kut', # 0x0e
'kux', # 0x0f
'ku', # 0x10
'kup', # 0x11
'kurx',... |
"""Utilities for the functionalities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
def check_positive_integer(value, name):
"""Checks whether `value` is a positive integer."""
if not isinstance(value, six.integer_types):
raise Typ... |
"""
A tiny, minimal protobuf2 parser that's able to extract enough information
to be useful.
"""
import cStringIO as StringIO
def parse_protobuf(data, schema=None):
"""
Do a simple parse of a protobuf2 given minimal type information.
Args:
data: a string containing the encoded protocol buffer.
... |
import contextlib
import os
import tempfile
import questionary
from commitizen import factory, git, out
from commitizen.config import BaseConfig
from commitizen.cz.exceptions import CzException
from commitizen.exceptions import (
CommitError,
CustomError,
DryRunExit,
NoAnswersError,
NoCommitBackup... |
"""
Tests of the encryption and decryption utilities in the ssencrypt module.
"""
import base64
from lms.djangoapps.verify_student.ssencrypt import (
aes_decrypt,
aes_encrypt,
decode_and_decrypt,
encrypt_and_encode,
rsa_decrypt,
rsa_encrypt
)
AES_KEY_BYTES = b'32fe72aaf2abb44de9e161131b5435c8... |
"""
Module containing class to create an ion
"""
__author__ = "Sai Jayaraman"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.0"
__maintainer__ = "Sai Jayaraman"
__email__ = "<EMAIL>"
__status__ = "Production"
__date__ = "Dec 10, 2012"
import re
import numpy as np
from pymatgen.core.composit... |
import sys
from scipy.stats.stats import pearsonr
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
def main(f):
fh = open(f, 'r')
zic1_expression = []
other_expression = {}
for line in fh:... |
"""Presubmit script for Chromium UI resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl/git cl, and see
http://www.chromium.org/developers/web-development-style-guide for the rules
we're checking against here.
"""
def CheckCha... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite
~~~~~~~~~~~~~~~~
All the unittests of Jinja2. These tests can be executed by
either running run-tests.py using multiple Python versions at
the same time.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
i... |
"""VectorClockRev helper class."""
class VectorClockRev(object):
"""Track vector clocks for multiple replica ids.
This allows simple comparison to determine if one VectorClockRev is
newer/older/in-conflict-with another VectorClockRev without having to
examine history. Every replica has a strictly inc... |
"""
Convert use of sys.exitfunc to use the atexit module.
"""
from lib2to3 import pytree, fixer_base
from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms
class FixExitfunc(fixer_base.BaseFix):
keep_line_order = True
BM_compatible = True
PATTERN = """
(
s... |
#!/usr/bin/env python
# encoding: utf-8
"""
process.py
Copyright (c) 2011 Adam Cohen
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 t... |
import elexio
import mailchimp
import log
import sys
debug = False
adds = []
deletes = []
def sync():
global adds
global deletes
egroups = elexio.get_groups()
mcgroups = mailchimp.get_groups()
# Iterate through all groups found in elexio. If any groups are missing
# from MailChimp, add it ... |
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.contrib.gis.maps.google.overlays import GPolygon, GPolyline, GMarker
class GoogleMapException(Exception):
pass
# The default Google Maps URL (for the API javascript)
# T... |
#@PydevCodeAnalysisIgnore
"""create and manipulate C data types in Python"""
import os as _os, sys as _sys
from itertools import chain as _chain
# special developer support to use ctypes from the CVS sandbox,
# without installing it
# XXX Remove this for the python core version
_magicfile = _os.path.join(_os.path.dir... |
from __future__ import print_function
import os
import platform
import re
import sys
import cv2
import numpy as np
from PIL import Image
class IkaUtils(object):
@staticmethod
def isWindows():
try:
os.uname()
except AttributeError:
return True
return False
... |
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import PublishOptions, SubscribeOptions
from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.wamp import ApplicationRunner
from autobahn.twisted.util import sleep
class MyComponent(A... |
__revision__ = "$Id: HarmonicMean.py,v 1.8 2009-10-27 20:06:27 rliebscher Exp $"
from fuzzy.norm.Norm import Norm, sum
class HarmonicMean(Norm):
def __init__(self):
super(HarmonicMean, self).__init__(Norm.UNKNOWN)
def __call__(self, *args):
args = self.checkArgsN(args)
if 0. in args:... |
from django.db.backends import BaseDatabaseIntrospection
import cx_Oracle
import re
foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
class DatabaseIntrospection(BaseDatabaseIntrospection):
# Maps type objects to Django Field types.
data_types_re... |
import requests.packages.urllib3
import hmac
import base64
from hashlib import sha256
import sys
import datetime
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
class SigV2Auth(object):
"""
Sign an Query Signature V2 request.
"""
def __init__(self, credentials... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_data_labels03.xls... |
from msrest.serialization import Model
class VerificationIPFlowParameters(Model):
"""Parameters that define the IP flow to be verified.
:param target_resource_id: The ID of the target resource to perform
next-hop on.
:type target_resource_id: str
:param direction: The direction of the packet rep... |
from django.conf.urls import url
from haystack.views import search_view_factory
from oscar.core.application import Application
from oscar.core.loading import get_class
from oscar.apps.search import facets
class SearchApplication(Application):
name = 'search'
search_view = get_class('search.views', 'FacetedSe... |
"""Test configs for elu."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1 as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip... |
import os, sys
from soup.utils.pluginloader import PluginLoader
class EnvironmentWrapper(object):
@classmethod
def enabled(cls, opts):
return True
def prepare_environment(self):
""" Modify the environment that the tests are running in """
pass
def decorate_test(self, test):
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pytest
from ansible.modules import pip
pytestmark = pytest.mark.usefixtures('patch_ansible_module')
@pytest.mark.parametrize('patch_ansible_module', [{'name': 'six'}], indirect=['patch_ansible_module'])
def... |
"""
Bibcheck plugin to move (rename) a subfield if
pattern matches and complement == False or
pattern does not match and complement = True,
depending on subfield_filter
Example:
[mvtexkey_withSpace]
check = rename_subfield_filter
filter_collection = HEP
check.source_field = "035__a"
check.new_code = "z"
check.pattern ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (<EMAIL>)
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, e... |
#!/usr/bin/env python
import mimetypes
import glob
import os
import os.path
# Initialize the mimetypes database
mimetypes.init()
# Create the package.opf file
package = open('package.opf', 'w')
# The glob below should encompass everything under
# OEBPS. Right now I'm trying to remove empty directories
# and the pac... |
"""Latex filters.
Module of useful filters for processing Latex within Jinja latex templates.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in th... |
"""Util functions for running Mask RCNN model using TPU low level APIs.
"""
import tensorflow as tf
def wrap_computation_in_while_loop(op_fn, n, parallel_iterations=1):
"""Wraps the ops generated by `op_fn` in tf.while_loop."""
def computation(i):
ops = op_fn()
if not isinstance(ops, list):
ops = ... |
from ._baseclass import ArtBaseClass
import numpy as np
from opc.colors import BLACK
from opc.hue import hsvToRgb
from math import fmod, sin, cos, sqrt
class ClearTrain(object):
def __init__(self, length):
self.length = length
self.points = [(0, 0) for i in range(length)]
self.head = 0
... |
import sys
import base64
import json
import subprocess
import traceback
from functools import wraps
try:
import ssl
except ImportError:
ssl = False
PY2 = sys.version_info < (3, 0)
try:
import __builtin__
str_instances = (str, __builtin__.basestring)
except Exception:
str_instances = (str, )
try... |
"""Tests for distutils.command.build_clib."""
import unittest
import os
import sys
from test.support import run_unittest
from distutils.command.build_clib import build_clib
from distutils.errors import DistutilsSetupError
from distutils.tests import support
from distutils.spawn import find_executable
class BuildCLib... |
import numpy as np
from scipy import linalg
from sklearn.decomposition import nmf
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import raises
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_gr... |
"""A PyQT4 class to load a page image from a ComicArchive in a background thread"""
# Copyright 2012-2014 Anthony Beville
# 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.apa... |
import shutil, os
from autosign import config
"""
Helper functions for performing tests
"""
def newFile(fName):
"""
Touch a new file
"""
with open(fName, 'a'):
pass
def testArea(obj):
obj.testArea = os.path.join(obj.dire, 'testArea')
os.mkdir(obj.testArea)
obj.unsigned1 = os.path.... |
'''OpenGL extension ARB.internalformat_query
This module customises the behaviour of the
OpenGL.raw.GL.ARB.internalformat_query to provide a more
Python-friendly API
Overview (from the spec)
OpenGL 4.1 has a number of queries to indicate the maximum number of
samples available for different formats. These give ... |
import sys, time
import pygame
class Run():
def __init__(self, fona):
#Stuff to follow app protocol
self.exit = False
self.blit_one_surface = {'surface':[], 'rects':[]}
self.blit = {'surfaces':[], 'rects':[]}
self.next_app = None
#Get list of installed apps
... |
"""
Tests to ensure all attributes of L{twisted.internet.gtkreactor} are
deprecated.
"""
import sys
from twisted.trial.unittest import TestCase
class GtkReactorDeprecation(TestCase):
"""
Tests to ensure all attributes of L{twisted.internet.gtkreactor} are
deprecated.
"""
class StubGTK:
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
HAS_KEYRING = True
from ansible.errors import AnsibleError
from ansible.utils.display import Display
try:
import keyring
except ImportError:
HAS_KEYRING = False
from ansible.plugins.lookup import LookupBase
display = Di... |
from __future__ import absolute_import
from datetime import timedelta
from functools import wraps
from apscheduler.schedulers.base import BaseScheduler
from apscheduler.util import maybe_ref
try:
from tornado.ioloop import IOLoop
except ImportError: # pragma: nocover
raise ImportError('TornadoScheduler requi... |
import inspect
import collections
from contextlib import contextmanager
from functools import wraps # Used in exec statement
import re
class Events(object):
"""
Events container.
All available events are attributes of this class.
"""
def __init__(self):
self._events = {}
@contex... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.ansible_tower import tower_argument_spec, tower_auth_config, towe... |
"""This module is deprecated. Please use `airflow.providers.apache.spark.hooks.spark_submit`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.apache.spark.hooks.spark_submit import SparkSubmitHook # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.apache.sp... |
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.translation import ugettext_lazy as _
from django_comments_xtd.conf import settings as comments_settings
from django_comments_xtd.forms import CommentForm
from django_comments_xtd.models import TmpXtdComment
from .model... |
"""Fixer for 'raise E, V, T'
raise -> raise
raise E -> raise E
raise E, V -> raise E(V)
raise E, V, T -> raise E(V).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)
raise (((E, E'), E''), E'''), V -> raise E(V)
raise "foo", V, T -> warns about string exceptions
CAVEATS:... |
# coding=utf8
"""
asl.py - Willie Freies Labor Activity Streams Lite Module
Licensed under a Mozilla Public License 2.0.
"""
from willie.module import commands, interval
import urllib2, json, os, pickle
from datetime import datetime, timedelta
ASL_QUERY = '-wiki.*&-sensor.traffic-light&-sensor.mate-o-meter&-twitter.re... |
"""
EasyBuild support for building and installing netcdf4-python, implemented as an easyblock.
@author: Kenneth Hoste (Ghent University)
"""
import os
import easybuild.tools.environment as env
from easybuild.easyblocks.generic.pythonpackage import PythonPackage
from easybuild.tools.modules import get_software_root
... |
from uaitrain.api.base_op import BaseUAITrainAPIOp
class ModifyUAITrainJobMemoApiOp(BaseUAITrainAPIOp):
"""
ModifyUAITrainJobMemoAPI
Identical with UAI Train ModifyUAITrainJobMemo API func
Input:
TrainJobId string(required) the id of train job
Trai... |
from . import test_access_rights
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.compiler.mlir.tensorflow.tests.tf_saved_model import common_v1
# Verify that the tf.versions attribute exists. It is difficult to enforce
# contents, since the... |
from essentia_test import *
class TestIntensity(TestCase):
def testEmpty(self):
self.assertComputeFails(Intensity(), [])
def testSilence(self):
audio = [0]*(44100*10) # 10 sec silence
self.assertEqual(Intensity()(audio), -1) # silence is relaxing isn't it
def testDif... |
from __future__ import print_function, division
from sympy.core import S, sympify, Expr, Rational, Symbol, Dummy
from sympy.core import Add, Mul, expand_power_base, expand_log
from sympy.core.cache import cacheit
from sympy.core.compatibility import default_sort_key, is_sequence
from sympy.core.containers import Tuple... |
#!/usr/bin/env python
import json
import os.path
from time import time
from pysnap.utils import (encrypt, decrypt, decrypt_story,
make_media_id, request)
MEDIA_IMAGE = 0
MEDIA_VIDEO = 1
MEDIA_VIDEO_NOAUDIO = 2
FRIEND_CONFIRMED = 0
FRIEND_UNCONFIRMED = 1
FRIEND_BLOCKED = 2
PRIVACY_EVERYONE ... |
import time
import datetime
from openerp import pooler
from openerp.report import report_sxw
class analytic_account_budget_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(analytic_account_budget_report, self).__init__(cr, uid, name, context=context)
self.localcontex... |
"""The 'gcloud test android devices' command group."""
from googlecloudsdk.calliope import base
class Devices(base.Group):
"""Explore Android devices available in the Test Environment catalog."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To list all Android devices... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
# NOQA
try:
import boto
import botocore
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
try:
import boto3
HAS_BOTO3 = True
except ImportError:
H... |
import mock
from nova import exception
from nova.objects import agent as agent_obj
from nova.tests.unit.objects import test_objects
fake_agent = {
'id': 1,
'hypervisor': 'novavm',
'os': 'linux',
'architecture': 'DISC',
'version': '1.0',
'url': 'http://openstack.org/novavm/agents/novavm_agent_... |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable
import operator
import struct
class table_C_O_L_R_(DefaultTable.DefaultTable):
""" This table is structured so that you can treat it like a dict... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
"""
Various complex queries that have been problematic in the past.
"""
import threading
from django.db import models
class DumbCategory(models.Model):
pass
class NamedCategory(DumbCategory):
name = models.CharField(max_length=10)
class Tag(models.Model):
name = models.CharField(max_length=10)
par... |
"""
Distance and Area objects to allow for sensible and convenient calculation
and conversions.
Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio
Inspired by GeoPy (https://github.com/geopy/geopy)
and Geoff Biggs' PhD work on dimensioned units for robotics.
"""
from decimal import Decimal
from functools import... |
from operator import add, sub
import sys
#image stuff
from PIL import Image, ImageDraw
#Read in the directions
with open(sys.argv[1]) as f:
directions = f.read()[:-1]
directions.strip()
directions = directions.split(', ')
compass = 0
# Compass directions:
# 0 : north
# 1 : east
# 2 : south
# 3 : west
# turning R... |
"""Ops and modules related to batch.
@@batch_function
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.batching.python.ops.batch_ops import batch_function
from tensorflow.python.util.all_util import remove_undocumented
remove_und... |
"""
flask_oauthlib.contrib.apps
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The bundle of remote app factories for famous third platforms.
Usage::
from flask import Flask
from flask_oauthlib.client import OAuth
from flask_oauthlib.contrib.apps import github
app = Flask(__name__)
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.graph_info.tasks.cloc import CountLinesOfCode
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.python.targets.pytho... |
import warnings
from .. import widgets
from .core import StringField, BooleanField
__all__ = (
'BooleanField', 'TextAreaField', 'PasswordField', 'FileField',
'HiddenField', 'SubmitField', 'TextField'
)
class TextField(StringField):
"""
Legacy alias for StringField
.. deprecated:: 2.0
"""
... |
from __future__ import unicode_literals
from django.contrib.gis import admin
from django.contrib.gis.geos import Point
from django.test import TestCase, override_settings, skipUnlessDBFeature
from .admin import UnmodifiableAdmin
from .models import City, site
@skipUnlessDBFeature("gis_enabled")
@override_settings(R... |
import MySQLdb
import dump_table
from optparse import OptionParser
import db_config
#calculate the ship attribute tables.
def dumpAttribute(conn,query,attrNum):
cursor = conn.cursor()
cursor.execute(query)
rowcount = int(cursor.rowcount)
conn.query("BEGIN;");
for i in range (0,rowcount):
... |
"""
A script to convert the drosophila connectome into SpineML
This build upon the pure data to add in the required infered network components:
# Install libSpineML from source
# https://github.com/AdamRTomkins/libSpineML
"""
from __future__ import division
from libSpineML import smlExperiment as exp
from libSpine... |
#
# shift_jisx0213.py: Python Unicode Codec for SHIFT_JISX0213
#
# Written by Hye-Shik Chang <<EMAIL>>
#
import _codecs_jp, codecs
import _multibytecodec as mbc
codec = _codecs_jp.getcodec('shift_jisx0213')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.M... |
import re
import traceback
from bs4 import BeautifulSoup
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.media._base.providers.torrent.base import TorrentMagnetProvider
import six
log = CPLog(... |
# -*- coding: utf8 -*-
############################
# imports
import time
import datetime
import urllib2
import re
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
############################
# defining the parameters
currentPriceRegex = re.compile(r'(?<=\<td\ align\=\"center\"\ bgcolor\... |
from openerp.osv import osv
class account_journal_select(osv.osv_memory):
"""
Account Journal Select
"""
_name = "account.journal.select"
_description = "Account Journal Select"
def action_open_window(self, cr, uid, ids, context=None):
mod_obj = self.pool.get('ir.model.data')
... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
import gc
import locale # system locale module, not tornado.locale
import logging
import operator
import textwrap
import sys
from tornado.httpclient import AsyncHTTPClient
from tornado.httpserver import HTTPServer
f... |
# -*- coding: utf-8 -*-
"""
@author: QQ:412319433
"""
import requests
from bs4 import BeautifulSoup
import sqlite3
import time
s = time.clock()
def htmlparse(bs, tag, attr = None, attrs= None):
'''
bs : BeautifulSoup对象
tag : 要处理的标签名
attr : 要获取属性值的属性名
attrs : 要查找的属性值对
'''
content ... |
#encoding=utf-8
from __future__ import print_function
import sys
sys.path.append("../../")
import jieba
jieba.enable_parallel(4)
import jieba.posseg as pseg
def cuttest(test_sent):
result = pseg.cut(test_sent)
for w in result:
print(w.word, "/", w.flag, ", ", end=' ')
print("")
if __name__ == "... |
# -*- coding: utf-8 -*-
# (c) 2017-2019, ETH Zurich, Institut fuer Theoretische Physik
"""
Defines the data container for eigenvalue data (bandstructures).
"""
import types
import numpy as np
from fsc.export import export
from fsc.hdf5_io import HDF5Enabled, subscribe_hdf5
from .kpoints import KpointsExplicit, Kpoi... |
"""
Verifies file copies using an explicit build target of 'all'.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('copies.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('copies.gyp', test.ALL, chdir='relocate/src')
test.must_match(['relocate', 'src', 'copies-out', 'file1'], 'file1 con... |
import re
# Section-title regexes
title_content = " (.*?)(?:\{(.*?)\})? "
title1 = re.compile("^=%s=$" % title_content)
title2 = re.compile("^==%s==$" % title_content)
title3 = re.compile("^===%s===$" % title_content)
# Comment to end of line
re_comment = re.compile(r'#.*')
# Summary of a page
re_summary... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_regmerge
version_added: "2.1"
short_description: Merges the contents of a registry file into the windows registry
description:
- Wraps the... |
import json
import base64
class Mail(object):
"""
An object that represents a single email to be sent via Apostle.io
Arbitrary attributes can be added at runtime and will be sent as
the 'data' key to Apostle.io
"""
# The template slug to be sent
template_id = None
# The email address to be sent to
email =... |
import superdesk
import subprocess
import json
from superdesk.commands.data_updates import BaseDataUpdate
from os.path import realpath, join, dirname
node_script_path = join(dirname(realpath(superdesk.__file__)), "data_updates", "00007_20180321-092824_archive.dist.js")
def get_updated_editor_state(editor_state):
... |
# -*- coding: utf-8 -*-
"""
pygments.styles.autumn
~~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
:copyright: 2006-2007 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from pygments.style import Style
from pygments.token import Keyword, N... |
import os
import sys
import time
import types
import atexit
import logging
import operator
import textwrap
import traceback
import supybot.ansi as ansi
import supybot.conf as conf
import supybot.utils as utils
import supybot.registry as registry
import supybot.ircutils as ircutils
deadlyExceptions = [KeyboardInterru... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import string_types
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
... |
# -*- coding: utf-8 -*-
"""
OnionShare | https://onionshare.org/
Copyright (C) 2014 Micah Lee <<EMAIL>>
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 o... |
from __future__ import unicode_literals
import os
import re
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import postgis
from django.test import TestCase
from django.utils._os import upath
if HAS_GEOS:
... |
"""Tests for slim.data.prefetch_queue."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.slim.python.slim.data import prefetch_queue
from tensorflow.python.framework import constant_op
from tensorflow.python.fram... |
import gevent
from gevent import monkey; monkey.patch_all()
from pysandesh.sandesh_base import *
from gen_py.generator_msg.ttypes import *
from pysandesh_example.gen_py.vn.ttypes import *
from pysandesh_example.gen_py.vm.ttypes import *
import sandesh_req_impl
import socket
class generator(object):
def __init__(se... |
# -*- coding: utf-8 -*-
"""
pygments.cmdline
~~~~~~~~~~~~~~~~
Command line interface.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import getopt
from textwrap import dedent
from pygments import __version__, highlight
fro... |
# pylint: disable=C0111
# pylint: disable=W0621
from lettuce import world, step
from terrain.steps import reload_the_page
from selenium.webdriver.common.keys import Keys
from common import type_in_codemirror, upload_file
from django.conf import settings
from nose.tools import assert_true, assert_false, assert_equal ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.