code stringlengths 1 199k |
|---|
import os
import sys
import unittest
from coalib.misc.Shell import (prepare_string_argument,
escape_path_argument,
run_interactive_shell_command,
run_shell_command)
class EscapePathArgumentTest(unittest.TestCase):
def test_... |
"""
Test user retirement methods
"""
import json
import ddt
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import TestCase
import pytest
from student.models import (
_get_all_retired_emails_by_email,
_get... |
"""distutils.archive_util
Utility functions for creating archive files (tarballs, zip files,
that sort of thing)."""
import os
from warnings import warn
import sys
try:
import zipfile
except ImportError:
zipfile = None
from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
from distut... |
"""
Test MUC support.
"""
import dbus
from twisted.words.xish import domish, xpath
from gabbletest import exec_test
from servicetest import (
EventPattern, assertEquals, assertLength, assertContains,
assertDoesNotContain,
)
import constants as cs
import ns
from mucutil import join_muc_and_check
def test(q, ... |
import os
import platform
import shutil
import sys
from spack import *
class Charm(Package):
"""Charm++ is a parallel programming framework in C++ supported by
an adaptive runtime system, which enhances user productivity and
allows programs to run portably from small multicore computers
(your laptop) to... |
import pymzml
import plot as pfac
import pprint
fac = pfac.Factory()
print ('made new Plot')
fac.newPlot(header='headerTest')
print('add peaks')
fac.add([(x,y) for x,y in zip(range(0,1000, 100), range(0, 1000, 100))], name='data', color=(255,0,0), style='sticks')
fac.add([(1363.56, 1417.56, 20000,'TEST'),(1100, 1200, 1... |
class Usecase:
def __init__(self, file, **settings):
self.file = file
self.settings = {"profile": None}
for key, value in settings.items():
self.settings[key] = value
def execute(self):
self.file.remove(self.settings["profile"])
# TODO: deep purge |
"""
AE Node
"""
import abc
import random
import tensorflow as tf
import numpy as np
import rospy
from tensorflow_node import SummaryWriter
class AutoEncoderNode(object):
__metaclass__ = abc.ABCMeta
# Initialization
def __init__(self,
session,
name="ae",
hid... |
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import socket
import sys
import... |
import struct
from ryu.lib.pack_utils import msg_pack_into
from ryu.ofproto.ofproto_parser import StringifyMixin, MsgBase, msg_str_attr
import ryu.ofproto.ofproto_v1_3_parser as ofproto_parser
import ryu.ofproto.ofproto_v1_3 as ofproto
import ryu.ofproto.openstate_v1_0 as osproto
def OFPExpActionSetState(state, table_i... |
"""
This Module performs Unit Tests for the randomUtils methods
"""
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default',DeprecationWarning)
import os,sys
import numpy as np
frameworkDir = os.path.normpath(os.path.join(os.path.dirname(os.pa... |
"""Tests for PCI request."""
import mock
from oslo_utils.fixture import uuidsentinel
from nova import context
from nova import exception
from nova.network import model
from nova import objects
from nova.objects import fields
from nova.pci import request
from nova import test
from nova.tests.unit.api.openstack import fa... |
import xml.etree.ElementTree as ET
import xml.dom.minidom as pxml
import os
def convert(tree,fileName=None):
"""
Converts input files to be compatible with merge request #269 (wangc/nd_dist_dev). Removes the <data_filename> and <workingDir> node
from the <MultivariateNormal> block, add <covariance> child nod... |
from .. import unittest
from synapse.util.caches.lrucache import LruCache
class LruCacheTestCase(unittest.TestCase):
def test_get_set(self):
cache = LruCache(1)
cache["key"] = "value"
self.assertEquals(cache.get("key"), "value")
self.assertEquals(cache["key"], "value")
def test_e... |
"""
Django settings for simpleform project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
BAS... |
from urllib import parse
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import strutils
from tacker._i18n import _
from tacker.vnfm.monitor_drivers.token import Token
from tacker import wsgi
LOG = logging.getLogger(__name__)
OPTS = [
cfg.StrO... |
import os
import sys
import subprocess
msg = (
"WARNING!\n\n"
"The Scalr Python components have been recently updated,\n"
"and running `python setup.py install` is no longer required.\n\n"
"If you are installing Scalr for the first time, you shouldn't be running this script.\n"
"Please double check ... |
from keystoneclient.contrib.ec2 import utils as ec2_utils
from oslo_config import cfg
from oslo_log import log as logging
from six.moves.urllib import parse as urlparse
from heat.common.i18n import _LW
from heat.engine.resources import stack_user
LOG = logging.getLogger(__name__)
SIGNAL_TYPES = (
WAITCONDITION, SIG... |
import webob.exc
from neutron_lib.api.definitions import portbindings
from neutron.db import db_base_plugin_v2
from neutron.db import subnet_service_type_mixin
from neutron.extensions import subnet_service_types
from neutron.tests.unit.db import test_db_base_plugin_v2
class SubnetServiceTypesExtensionManager(object):
... |
import os
import get_model_evaluation_slice_sample
PROJECT_ID = os.getenv("BUILD_SPECIFIC_GCLOUD_PROJECT")
MODEL_ID = "3512561418744365056" # permanent_safe_driver_model
EVALUATION_ID = "9035588644970168320" # permanent_safe_driver_model Evaluation
SLICE_ID = "6481571820677004173" # permanent_safe_driver_model Eval ... |
from pathlib import PurePath
import pytest
from pants.backend.terraform.hcl2_parser import resolve_pure_path
def test_resolve_pure_path() -> None:
assert resolve_pure_path(PurePath("foo/bar/hello/world"), PurePath("../../grok")) == PurePath(
"foo/bar/grok"
)
assert resolve_pure_path(
PurePat... |
import secrets
import time
from typing import Dict, List, Tuple, Type
from unittest import mock
from zerver.lib.rate_limiter import (
RateLimitedObject,
RateLimitedUser,
RateLimiterBackend,
RedisRateLimiterBackend,
TornadoInMemoryRateLimiterBackend,
add_ratelimit_rule,
remove_ratelimit_rule,... |
"""Add the root execution ID to the workflow execution model
Revision ID: 023
Revises: 022
Create Date: 2017-07-26 14:51:02.384729
"""
revision = '023'
down_revision = '022'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'workflow_executions_v2',
sa.Column('root_executi... |
from __future__ import print_function
import numpy as np
import unittest
import paddle.fluid as fluid
import paddle.fluid.initializer as initializer
from paddle.fluid import Program, program_guard
from op_test import OpTest
def nce(input, weight, bias, sample_weight, labels, num_classes,
num_sample_class):
... |
class ChangeDetectorError(Exception):
pass
class ChangeDetectorInitializeError(ChangeDetectorError):
pass |
import paddle
import paddle.fluid as fluid
import numpy as np
import time
import six
import unittest
from paddle.fluid.reader import DataLoaderBase
EPOCH_NUM = 20
BATCH_SIZE = 32
BATCH_NUM = 20
CLASS_NUM = 10
def random_reader():
np.random.seed(1)
for i in range(BATCH_SIZE * BATCH_NUM):
image = np.rando... |
'''
====================================================================
Copyright (c) 2003-2016 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
========================================================... |
import unittest
import webob
from swift.common.middleware import keystoneauth
class FakeApp(object):
def __init__(self, status_headers_body_iter=None):
self.calls = 0
self.status_headers_body_iter = status_headers_body_iter
if not self.status_headers_body_iter:
self.status_header... |
"""Implementation of gcloud bigquery tables add-rows.
"""
import sys
from googlecloudapis.apitools.base import py as apitools_base
from googlecloudsdk.bigquery import commands
from googlecloudsdk.bigquery.lib import bigquery
from googlecloudsdk.bigquery.lib import bigquery_json_object_messages
from googlecloudsdk.bigqu... |
import datetime
from threading import Thread, current_thread
from modules.databridge.agent import *
from config import Config
from exception import DataPublisherException
import constants
import urllib2
import json
import base64
import traceback
class HttpLogPublisher(Thread):
def __init__(self, file_path, tenant_i... |
"""Tests for the serializer object implementation using JSON."""
import json
import os
import unittest
from dfvfs.path import os_path_spec
from dfvfs.path import qcow_path_spec
from dfvfs.path import tsk_path_spec
from dfvfs.path import vshadow_path_spec
from dfvfs.serializer import json_serializer as serializer
class ... |
__all__ = [
"Provider",
"State",
"LibcloudLBError",
"LibcloudLBImmutableError",
"OLD_CONSTANT_TO_NEW_MAPPING",
]
from libcloud.common.types import LibcloudError
class LibcloudLBError(LibcloudError):
pass
class LibcloudLBImmutableError(LibcloudLBError):
pass
class Provider(object):
"""
... |
from ...core.memory_map import (FlashRegion, RamRegion, MemoryMap)
from ...debug.svd.loader import SVDFile
from ..family.target_nRF52 import NRF52
FLASH_ALGO = { 'load_address' : 0x20000000,
'instructions' : [
0xE00ABE00, 0x062D780D, 0x24084068, 0xD3000040, 0x1E644058, 0x1... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2015-2017 ARM Limited
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 required by applicable law... |
"""Controllers for the admin view."""
import logging
import jinja2
from core import counters
from core import jobs
from core import jobs_registry
from core.controllers import base
from core.controllers import editor
from core.domain import collection_services
from core.domain import config_domain
from core.domain impor... |
# 18.
print_log('\n18. Prover gets Credentials for Proof Request\n')
proof_request = {
'nonce': '123432421212',
'name': 'proof_req_1',
'version': '0.1',
'requested_attributes': {
'attr1_referent': {
'name': 'name... |
from yabgp.tlv import TLV
from ..linkstate import LinkState
@LinkState.register()
class NodeName(TLV):
"""
node name
"""
TYPE = 1026
TYPE_STR = 'node_name'
@classmethod
def unpack(cls, data):
return cls(value=data.decode('ascii')) |
"""
bucket.py
Contains the Bucket class, which provides several useful functions
over an s3 bucket.
"""
import pathlib
from .data_transfer import (
copy_file,
delete_object,
list_object_versions,
list_objects,
select,
)
from .search_util import search_api
from .util import PhysicalKey, QuiltExce... |
"""Evaluates an InfoGAN TFGAN trained MNIST model.
The image visualizations, as in https://arxiv.org/abs/1606.03657, show the
effect of varying a specific latent variable on the image. Each visualization
focuses on one of the three structured variables. Columns have two of the three
variables fixed, while the third one... |
__author__ = 'Shoval' |
import hashlib
import hmac
import posixpath
import httplib2
from oslo_cache import core as cache_core
from oslo_config import cfg
from oslo_log import log as logging
import six
import six.moves.urllib.parse as urlparse
import webob
from ec2api import context as ec2_context
from ec2api import exception
from ec2api.i18n ... |
import os
from django.views.generic.edit import BaseDetailView
from django.http import HttpResponse, Http404
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.utils.decorators import method... |
import numpy as np
from .utils import lazy_property
def primitiveToLattice(primitiveVectors, Ns):
# 2D output should be [N1, N2, 2]
# 3D output should be [N1, N2, N3, 3]
# and so on...
ns = []
for d in np.arange(len(Ns)):
ns.append(np.arange(-(Ns[d]//2), -(-Ns[d]//2)))
ns = np.meshgrid(*... |
"""Model class for flood realtime."""
from builtins import object
from django.contrib.gis.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from realtime.models.mixins import BaseEventModel
from realtime.models.report import BaseEventReportModel
class ... |
"""
This module contains the views associated with the Facebook
administration.
For example in order to use many of the facebook integrated
features of the website, the website must have access to a valid
facebook account that has access to the desired objects.
The views in this module will allow the administrators of ... |
"""Test the Nuclear method in cclib"""
import sys
import os
import re
import logging
import unittest
import numpy as np
from cclib.method import Nuclear
from cclib.parser import ccData
from cclib.parser import DALTON
from cclib.parser import Gaussian
from cclib.parser import QChem
from cclib.parser import utils
sys.pat... |
from itertools import chain
import warnings
from django.core.exceptions import FieldError
from django.db.backends.utils import truncate_name
from django.db.models.constants import LOOKUP_SEP
from django.db.models.query_utils import select_related_descend, QueryWrapper
from django.db.models.sql.constants import (CURSOR,... |
import boto
import json
import os
import pytest
from boto import sts
from boto.s3.connection import Location
from wal_e.blobstore import s3
from wal_e.blobstore.s3 import calling_format
def bucket_name_mangle(bn, delimiter='-'):
return bn + delimiter + os.getenv('AWS_ACCESS_KEY_ID').lower()
def no_real_s3_credentia... |
import itertools
from functools import partial
from toolz.compatibility import Queue, map
identity = lambda x: x
def remove(predicate, coll):
""" Return those items of collection for which predicate(item) is true.
>>> def iseven(x):
... return x % 2 == 0
>>> list(remove(iseven, [1, 2, 3, 4]))
[1... |
from casexml.apps.phone.exceptions import BadVersionException
V1 = "1.0"
V2 = "2.0"
V3 = "3.0"
DEFAULT_VERSION = V1
LEGAL_VERSIONS = [V1, V2, V3]
V2_NAMESPACE = "http://commcarehq.org/case/transaction/v2"
NS_VERSION_MAP = {
V2: V2_NAMESPACE,
}
NS_REVERSE_LOOKUP_MAP = dict((v, k) for k, v in NS_VERSION_MAP.items())
... |
import sqlite3
import os
try:
import json
except ImportError:
import simplejson as json
import sys
import xml.sax
import binascii
from vincenty import vincenty
from struct import pack, unpack
from rtree import Rtree
def cons(ary):
for i in range(len(ary)-1):
yield (ary[i], ary[i+1])
def pack_coords(... |
"""
Display ROI Labels
==================
Using PySurfer you can plot Freesurfer cortical labels on the surface
with a large amount of control over the visual representation.
"""
import os
from surfer import Brain
print(__doc__)
subject_id = "fsaverage"
hemi = "lh"
surf = "smoothwm"
brain = Brain(subject_id, hemi, surf... |
import os
from measurements import smoothness_controller
from measurements import timeline_controller
from telemetry import benchmark
from telemetry.core.platform import tracing_category_filter
from telemetry.core.platform import tracing_options
from telemetry.page import action_runner
from telemetry.page import page_t... |
from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas import Categorical
from pandas.util import testing as tm
def test_cast_1d_array_like_from_scalar_categorical():
# see gh-19565
#
# Categorical result from scalar did not ... |
try:
from setuptools import setup
except (ImportError, err):
from distutils.core import setup
from ahem import VERSION
setup(
name='Ahem',
version='.'.join(map(str,VERSION)),
description='Simple, but rich, declarative notification framework for Django',
packages=['ahem'],
include_package_dat... |
import unittest
import IECore
class TestReader(unittest.TestCase):
def testSupportedExtensions( self ) :
self.assertEqual( set( IECore.Reader.supportedExtensions() ), { "cob" } )
def test( self ) :
"""
check if we can create a reader from a blank file.
this should definitely NOT create a valid reader
"""
... |
""" path.py - An object representing a path to a file or directory.
Example:
from path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
This module requires Python 2.2 or later.
URL: http://www.jorendorff.com/articles/python/path
Author: Jason Orendorff <jason.orendorff\x40gmail\... |
""" Test functions for stats module
"""
from __future__ import division, print_function, absolute_import
import warnings
import re
import sys
import pickle
import os
from numpy.testing import (assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal,
... |
"""
Expand Hypergeometric (and Meijer G) functions into named
special functions.
The algorithm for doing this uses a collection of lookup tables of
hypergeometric functions, and various of their properties, to expand
many hypergeometric functions in terms of special functions.
It is based on the following paper:
... |
from vistrails.db.domain import DBWorkflow
from vistrails.db.services.action_chain import getActionChain, getCurrentOperationDict, \
getCurrentOperations
def getNewObjId(operation):
if operation.vtType == 'change':
return operation.db_newObjId
return operation.db_objectId
def update_id_scope(vistrai... |
"""Mie cylinder with unevenly spaced angles
Angular weighting can significantly improve reconstruction quality
when the angular projections are sampled at non-equidistant
intervals :cite:`Tam1981`. The *in silico* data set was created with
the softare `miefield <https://github.com/RI-imaging/miefield>`_.
The data are ... |
import urllib
from lxml import etree
NSMAP = {'wadl': 'http://research.sun.com/wadl/2006/10'}
class WADLMethod(object):
def __init__(self, id, name, api):
self.id = id
self.api = api
self.name = name
self.url = u'/'.join(self.api.doc.xpath(
'//wadl:method[@id="%s"]//ances... |
from cms.tests.admin import AdminTestCase
from cms.tests.apphooks import ApphooksTestCase
from cms.tests.docs import DocsTestCase
from cms.tests.forms import FormsTestCase
from cms.tests.mail import MailTestCase
from cms.tests.middleware import MiddlewareTestCase
from cms.tests.multilingual import MultilingualTestCase
... |
import datetime, pickle
from south.db import db
from south.v2 import DataMigration
from django.db import models
class PackedDBobject(object):
"""
Attribute helper class.
A container for storing and easily identifying database objects in
the database (which doesn't suppport storing db_objects directly).
... |
from __future__ import absolute_import
PUSH_EVENT_EXAMPLE = r"""{
"ref": "refs/heads/changes",
"before": "9049f1265b7d61be4a8904a9a27120d2064dab3b",
"after": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
"created": false,
"deleted": false,
"forced": false,
"base_ref": null,
"compare": "https://github.com/... |
"""This script generates Slicer Interfaces based on the CLI modules XML. CLI
modules are selected from the hardcoded list below and generated code is placed
in the cli_modules.py file (and imported in __init__.py). For this to work
correctly you must have your CLI executabes in $PATH"""
from __future__ import print_fun... |
"""
Port used by Airplayer.
You should only need to change this in case port 6002 is already
in use on your machine by other software.
"""
AIRPLAYER_PORT = 6002
"""
Set your media backend.
Supported media backends are XBMC, Plex and Boxee.
"""
MEDIA_BACKEND = 'XBMC'
"""
Default ports:
XBMC: 8080
Plex: 3000
Boxee: 8800
... |
import sys
from metrics import Metric
from telemetry.value import scalar
class IOMetric(Metric):
"""IO-related metrics, obtained via telemetry.core.Browser."""
@classmethod
def CustomizeBrowserOptions(cls, options):
# TODO(tonyg): This is the host platform, so not totally correct.
if sys.platform != 'darw... |
FILE_CONFIG = """
[server]
ip = 0.0.0.0
port = 8080
web_root = /var/www/html
list_directories = True
"""
FILE_SYSTEMD_SERVICE_UNIT = """
[Unit]
Description=Python Advanced HTTP Server
After=network.target
[Service]
Type=simple
ExecStart=/sbin/runuser -l nobody -c "/usr/bin/python -m AdvancedHTTPServer -c /etc/pyhttpd.c... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("contacts", "0009_contact_suspended_groups")]
operations = [
migrations.AddField(
model_name="group",
name="suspend_from",
field=mo... |
from django.db.models.signals import post_delete, post_save
from wagtail.search import index
def post_save_signal_handler(instance, update_fields=None, **kwargs):
if update_fields is not None:
# fetch a fresh copy of instance from the database to ensure
# that we're not indexing any of the unsaved d... |
import numpy as np
import scipy.sparse as sp
import array
from . import check_random_state
from ._random import sample_without_replacement
__all__ = ['sample_without_replacement']
def _random_choice_csc(n_samples, classes, class_probability=None,
random_state=None):
"""Generate a sparse rando... |
from __future__ import absolute_import
from opbeat.utils.lru import LRUCache
from tests.utils.compat import TestCase
class LRUTest(TestCase):
def test_insert_overflow(self):
lru = LRUCache(4)
for x in range(6):
lru.set(x)
self.assertFalse(lru.has_key(1))
for x in range(2,... |
'Define categories of Action and their consequences in the World.'
__author__ = 'Nick Montfort'
__copyright__ = 'Copyright 2011 Nick Montfort'
__license__ = 'ISC'
__version__ = '0.5.0.0'
__status__ = 'Development'
import copy
import re
def generator(num):
'Provides unique, increasing integers.'
while 1:
... |
from distutils.core import setup
from coil import __version__ as VERSION
setup(
name = 'coil',
version = VERSION,
author = 'Michael Marineau',
author_email = 'mike@marineau.org',
description = 'A powerful configuration language',
license = 'MIT',
packages = ['coil', 'coil.test'],
package... |
"""
This module contains the DoodleWindow class which is a window that you
can do simple drawings upon.
"""
import wx # This module uses the new wx namespace
class DoodleWindow(wx.Window):
menuColours = { 100 : 'Black',
101 : 'Yellow',
102 : 'Red',
... |
import re
import logging
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout
from duniterpy.documents.constants import pubkey_regex
from duniterpy.documents import CRCPubkey
from sakia.data.processors import ConnectionsProcessor
from sakia.decorators import as... |
"""
Flood Alerts Module - Model
@author: Fran Boon
@see: http://eden.sahanafoundation.org/wiki/Pakistan
"""
module = "flood"
if deployment_settings.has_module(module):
# -----------------------------------------------------------------------------
# Rivers
resourcename = "river"
tablename = ... |
''' Example showing how to use almath with python and send the results to
the robot by using a proxy to ALMotion '''
import sys
import time
from naoqi import ALProxy
import almath
def main(IP):
PORT = 9559
# Create a proxy to ALMotion.
try:
motionProxy = ALProxy("ALMotion", IP, PORT)
except ... |
"""
.. warning::
The classes in this file are internal and may well be removed to an
external kivy-pytest package or similar in the future. Use at your own
risk.
"""
import random
import time
import math
import os
from collections import deque
from kivy.tests import UnitTestTouch
__all__ = ('UnitKivyApp', )... |
from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incoming ... |
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map = Basemap(projection='ortho',
lat_0=0, lon_0=0)
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()
plt.show() |
"""
***************************************************************************
classification.py
---------------------
Date : July 2015
Copyright : (C) 2015 by Arnaud Morvan
Email : arnaud dot morvan at camptocamp dot com
***********************************... |
"""Minimal Flask application example for development.
Run example development server:
.. code-block:: console
$ cd examples
$ flask -a app.py --debug run
"""
from __future__ import absolute_import, print_function
import os
from flask import Flask
from flask_cli import FlaskCLI
from invenio_db import InvenioDB
fro... |
import re
import markdown
import datetime
from flask import Markup
from ..ext import keywords_split
__all__ = ['register_filters', 'markdown_filter']
def markdown_filter(text, codehilite=True):
"""
代码高亮可选,有的场合不需要高亮,高亮会生成很多代码
但是fenced_code生成的代码是<pre><code>~~~</code></code>包围的
"""
exts = [
'ab... |
from contextlib import contextmanager
from pathlib import Path
import os
import tempfile
@contextmanager
def make_dict(tmp_path, contents, extension=None, name=None):
kwargs = {'dir': str(tmp_path)}
if name is not None:
kwargs['prefix'] = name + '_'
if extension is not None:
kwargs['suffix']... |
import cPickle, os, logging
try:
import autotest.common as common
except ImportError:
import common
from autotest.scheduler import drone_utility, email_manager
from autotest.client.shared.settings import settings
AUTOTEST_INSTALL_DIR = settings.get_value('SCHEDULER',
'd... |
from __future__ import absolute_import
from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(name='patch_tags')
def patch_tags(patch, tag):
count = getattr(patch, tag.attr_name)
count_str =... |
from __future__ import print_function, division, unicode_literals, absolute_import
import os
import tempfile
import unittest
import json
from monty.tempfile import ScratchDir
from fireworks import Workflow, Firework
from fireworks.core.rocket_launcher import rapidfire
from abiflows.core.testing import AbiflowsTest, has... |
"""BibFormat element - QR code generator """
from invenio.config import CFG_SITE_SECURE_URL, CFG_WEBDIR, CFG_SITE_RECORD
from invenio.hashutils import md5
import os
try:
import qrcode
from PIL import Image
HAS_QR = True
except ImportError:
HAS_QR = False
if not HAS_QR:
from warnings import warn
... |
import logging
import time
import os
from virttest import utils_misc, aexpect, utils_net, openvswitch, ovs_utils
from virttest import versionable_class, data_dir
from autotest.client.shared import error
def allow_iperf_firewall(machine):
machine.cmd("iptables -I INPUT -p tcp --dport 5001 --j ACCEPT")
machine.cm... |
import re
from gi.repository import GObject, Gtk
from ubuntutweak.modules import TweakModule
from ubuntutweak.gui.containers import GridPack
from ubuntutweak.factory import WidgetFactory
from ubuntutweak.settings.gconfsettings import GconfSetting
from ubuntutweak.settings.gsettings import GSetting
from ubuntutweak imp... |
import requests
import socket
import time
import json
import mmap
from test_helper import ApiTestCase
class TestBasics(ApiTestCase):
def test_unauth(self):
r = requests.get(self.url("/?command=stats"))
self.assertEquals(r.status_code, requests.codes.unauthorized)
def test_auth_stats(self):
... |
import unittest
from sample import OnlyCopy, FriendOfOnlyCopy
class ClassWithOnlyCopyCtorTest(unittest.TestCase):
def testGetOne(self):
obj = FriendOfOnlyCopy.createOnlyCopy(123)
self.assertEqual(type(obj), OnlyCopy)
self.assertEqual(obj.value(), 123)
def testGetMany(self):
objs ... |
"""
Automatic concatenation of multiple cubes over one or more existing dimensions.
.. warning::
This functionality has now been moved to
:meth:`iris.cube.CubeList.concatenate`.
"""
def concatenate(cubes):
"""
Concatenate the provided cubes over common existing dimensions.
.. warning::
This ... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import specest_swig as specest
class qa_arfmcov_vcc (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self):
# set up fg
self.tb.run ()
... |
"""Code used by ``horton-atomdb.py``"""
from glob import glob
import os
import re
import stat
from string import Template as BaseTemplate
import numpy as np
import matplotlib.pyplot as pt
from horton.io.iodata import IOData
from horton.log import log
from horton.periodic import periodic
from horton.scripts.common impor... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import errno
import fcntl
import os
import pty
import select
import subprocess
import time
from ansible import constants as C
from ansible.compat.six import PY3, text_type, binary_type
from ansible.compat.six.moves import shlex_quot... |
import math
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QWidget, QGridLayout, QSizePolicy, qApp
from sortedcontainers import SortedDict
class PageWidget(QWidget):
move_drop_event = pyqtSignal(object, int, int)
copy_drop_event = pyqtSignal(object, int, int)
DRAG_MAGIC = 'LiSP_Drag&Dro... |
import codecs
import os
import random
import re
from cloudbot import hook
@hook.on_start()
def load_kenm(bot):
"""
:type bot: cloudbot.bot.Cloudbot
"""
global kenm
with codecs.open(os.path.join(bot.data_dir, "kenm.txt"), encoding="utf-8") as f:
kenm = [line.strip() for line in f.readlines() ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.