code stringlengths 1 199k |
|---|
"""Utility functions used by memote and its tests."""
from __future__ import absolute_import
import json
import logging
from builtins import dict, str
from textwrap import TextWrapper
from depinfo import print_dependencies
from future.utils import raise_with_traceback
from numpy import isfinite
from numpydoc.docscrape ... |
"""Script to run mypy's test suite against this version of typeshed."""
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tempdir:
dirpath = Path(tempdir)
subprocess.run(["git", "clone", "--depth", "1"... |
def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
params.result = ""
args = params.tags.getValues(id="", width="800", height=400, title="", mod=100)
C = """
{{stats: id:$id start:-2h stop:-1h title:'$t1' width:$w height:$h mod:$mod}}
{{stats: id:$id... |
"""VFS Handler which provides access to the raw physical memory.
Memory access is provided by use of a special driver. Note that it is preferred
to use this VFS handler rather than directly access the raw handler since this
handler protects the system from access to unmapped memory regions such as DMA
regions. It is al... |
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.openstack.keystone import role_assignments
from heat.engine import support
class KeystoneUser(resource.Resource,
role_assignments.KeystoneR... |
import os
import sys
from datetime import datetime
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pretix.settings")
import django
django.setup()
from pretix.base.models import * # NOQA
from django.utils.timezone import now
if Organizer.objects.exists():
print("There already is data in your DB!")
sys.exit(0)
... |
"""@package src.clm.views.admin_cm.storage
@alldecoratedby{src.clm.utils.decorators.admin_cm_log}
"""
from clm.utils.decorators import admin_cm_log, cm_request
@admin_cm_log(log=True, pack=False)
@cm_request
def create(cm_response, **data):
"""
@clmview_admin_cm
@cm_request_transparent{storage.create()}
... |
from glanceclient.v1 import images
from openstack_dashboard.test.test_data import utils
def data(TEST):
TEST.images = utils.TestDataContainer()
TEST.snapshots = utils.TestDataContainer()
# Snapshots
snapshot_dict = {'name': u'snapshot',
'container_format': u'ami',
... |
import numpy as np
import sys, os, math
import datetime as dt
import scipy, scipy.signal
import parmap
from scipy.interpolate import splrep, splev, make_interp_spline, splder, sproot
from tqdm import tqdm
import torch
from torch import nn
import cudaSpline as deconv
import rowshift as rowshift
from yass.deconvolve.util... |
import base
import connection
import models
from base import UWSError |
"""
分割字符串或文本文件并交互进行分页
"""
def more(text, numlines=15):
lines = text.splitlines()
while lines:
chunk = lines[:numlines]
lines = lines[numlines:]
for line in chunk: print(line)
if lines and input('More"') not in ['y', 'Y']: break
if __name__ == '__main__':
import sys
more(o... |
"""
Cloud Controller: Implementation of EC2 REST API calls, which are
dispatched to other nodes via AMQP RPC. State is via distributed
datastore.
"""
from neutronclient.common import exceptions as neutron_exception
from oslo_log import log as logging
from ec2api.api import common
from ec2api.api import ec2utils
from ec... |
from django.contrib import admin
from pessoas.models import Pessoa, Voto
admin.site.register(Pessoa)
admin.site.register(Voto) |
from __future__ import unicode_literals
import csv
from datetime import datetime, timedelta
from admin.base.utils import OSFAdmin
from admin.base.views import GuidFormView, GuidView
from admin.common_auth.logs import (CONFIRM_SPAM, USER_2_FACTOR, USER_EMAILED,
USER_REMOVED, USER_REST... |
"""Test file to display the error message and verify it with FileCheck."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from absl import app
import tensorflow.compat.v2 as tf
if hasattr(tf, 'enable_v2_behavior'):
tf.enable_v2_behavior()
class ... |
import ConfigParser, json, os
bot_info = dict()
def read_config(config_dir, config_name):
#global bot_info
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), config_dir, config_name)
configReader = ConfigParser.ConfigParser()
configReader.read(config_path)
config = dict()
fo... |
from flup.server.fcgi import WSGIServer
from flaskext.xmlrpc import XMLRPCHandler, Fault
from xmlrpcdispatcher import XMLRPCDispatcher
class FlaskXMLRPC(object):
"""
Encapsulates an XML-RPC receiver within a flask server.
It also exports the service xmlrpc, which has the service contract outlined below.
... |
from django.db import migrations
from django.utils import timezone
def set_all_null_timestamps_to_now(apps, schema_editor):
DungeonLog = apps.get_model('data_log', 'DungeonLog')
RiftRaidLog = apps.get_model('data_log', 'RiftRaidLog')
WorldBossLog = apps.get_model('data_log', 'WorldBossLog')
for m in [Du... |
import base64
import time
import testtools
from tempest.api import compute
from tempest.api.compute import base
from tempest.common.utils.data_utils import rand_name
from tempest.common.utils.linux.remote_client import RemoteClient
import tempest.config
from tempest import exceptions
from tempest.test import attr
class... |
"""
Process macro batches of data in a pipelined fashion.
"""
import logging
from glob import glob
import functools
import gzip
from multiprocessing import Pool
import numpy as np
import os
import tarfile
import struct
from PIL import Image as PILImage
from neon.util.compat import range, StringIO
from neon.util.persist... |
"""Text embedding model stored as a SavedModel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
from absl import app
from absl import flags
import tensorflow.compat.v2 as tf
from tensorflow.python.ops import lookup_ops
from tensor... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Application.description'
db.delete_column(u'core_application', 'description')
... |
import json
from django.urls import reverse
from seahub.options.models import UserOptions
from seahub.test_utils import BaseTestCase
class DefaultLibraryTest(BaseTestCase):
def setUp(self):
self.user_name = self.user.username
self.admin_name = self.admin.username
self.group_id = self.group.i... |
'''
@author: jnaous
'''
from django.views.generic import list_detail, create_update, simple
from models import Project
from forms import ProjectCreateForm
from django.http import HttpResponseRedirect, HttpResponseNotAllowed, Http404
from django.core.urlresolvers import reverse
from django.core.exceptions import Multipl... |
from setuptools import setup
setup(
name='asyncio-yify',
version='0.0.8',
author='davidyen1124',
author_email='davidyen1124@gmail.com',
description='Damned fast YIFY parser using Asyncio',
lincense='Apache',
keywords='yify parser movies asyncio',
url='https://github.com/davidyen1124/Asyn... |
"""Fake LDAP server for test harness.
This class does very little error checking, and knows nothing about ldap
class definitions. It implements the minimum emulation of the python ldap
library to work with nova.
"""
import re
import shelve
import ldap
from keystone.common import logging
from keystone.common import uti... |
from __future__ import absolute_import
from nose.plugins.skip import SkipTest
from nose.tools import assert_raises, eq_
from aws import s3
def test_parse_uri():
p = s3.parse_uri
eq_(('bucket', 'folder/key', 'key'), p('s3://bucket/folder/key'))
eq_(('bucket', 'folder/key/', 'key'), p('s3://bucket/folder/key/'))
... |
class APIException(Exception):
"""
API Exception class
"""
pass |
import Wire2
import Servo |
from nose.tools import *
import networkx as nx
class TestVitality:
def test_closeness_vitality_unweighted(self):
G=nx.cycle_graph(3)
v=nx.closeness_vitality(G)
assert_equal(v,{0:4.0, 1:4.0, 2:4.0})
def test_closeness_vitality_weighted(self):
G=nx.Graph()
G.add_cycle([0,1,... |
from __future__ import absolute_import, division, print_function
import abc
import binascii
import inspect
import struct
import sys
import warnings
DeprecatedIn10 = DeprecationWarning
DeprecatedIn12 = PendingDeprecationWarning
def read_only_property(name):
return property(lambda self: getattr(self, name))
def regis... |
from pygments import highlight
from pygments.lexers import TextLexer, DiffLexer
from pygments.formatters import TerminalFormatter as Formatter
from deployer.node import ParallelNode, required_property, suppress_action_result
from deployer.utils import esc1
import difflib
class Config(ParallelNode):
"""
Base cla... |
"""
publisher_match_filter.py -- find the publishers in VIVO, and match them by name to the publishers
in the source.
There are two inputs:
1. publishers in VIVO. Keyed by simplified name
2. publishers in the source. Keyed by simplified name
There are three cases
1. publisher in VIVO and i... |
"""
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import gzip
import subprocess, glob
from astropy import units as u
from astropy.io import ascii, fits
from astropy.table import QTable, Table, Column
from xastropy.xutils import xdebug as xdb
def bintab_to_tabl... |
import os
import sys
from setuptools import setup, find_packages
sys.path.append('.')
from fedora_college import metadata
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
python_version_specific_requires = []
if sys.version_info < (2, 7) or (3, 0) <= sys... |
"""
Contains a number of utility functions for storage sockets.
"""
import json
_get_metadata = json.dumps({"errors": [], "n_found": 0, "success": False, "missing": [], "error_description": False})
_add_metadata = json.dumps(
{
"errors": [],
"n_inserted": 0,
"success": False,
"duplic... |
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.multivariate.pca import PCA
plt.rc("figure", figsize=(16, 8))
plt.rc("font", size=14)
data = sm.datasets.fertility.load_pandas().data
data.head()
columns = list(map(str, range(1960, 2012)))
data.set_index("Country Name", inplace=True)
dta = d... |
r"""
Display status of a service on your system.
Configuration parameters:
cache_timeout: refresh interval for this module (default 5)
format: display format for this module (default '\?if=!hide {unit}: {status}')
hide_extension: suppress extension of the systemd unit (default False)
hide_if_default: su... |
"""Unit tests for the bytes and bytearray types.
XXX This is a mess. Common tests should be unified with string_tests.py (and
the latter should be modernized).
"""
import array
import os
import re
import sys
import copy
import functools
import pickle
import tempfile
import unittest
import test.support
import test.stri... |
from __future__ import with_statement
from sympy.core import symbols
from sympy.utilities.pytest import raises
from sympy.matrices import ShapeError, MatrixSymbol
from sympy.matrices.expressions import HadamardProduct, hadamard_product
def test_HadamardProduct():
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z',... |
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from .models import User
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class MyUserCreationForm(Use... |
import sys
import os
extensions = ['sphinxcontrib.circuits']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'test'
copyright = u'2013, test'
version = '1.0'
release = '1.0'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static... |
import pyglet
class Record:
def __init__(self):
# score
self.best_score = 0
self.cur_score = 0
def get(self):
return self.cur_score
def inc(self):
self.cur_score += 1
def reset(self):
self.cur_score = 0
def save(self):
if self.cur_score > self.... |
"""
cookiecutter.generate
---------------------
Functions for generating a project from a project template.
"""
from __future__ import unicode_literals
from collections import OrderedDict
import fnmatch
import io
import json
import logging
import os
import shutil
from jinja2 import FileSystemLoader, Template
from jinja... |
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator, InvalidPage
from django.core.urlresolvers import reverse, resolve, Resolver404
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render... |
import sys
import os
import xml.sax
from pyproj import Transformer
input_file = sys.argv[1]
output_file = input_file.replace(".xml", "") + ".csv"
output = open(output_file, "w")
tags = ["bt:lokalnyId", "prg-ad:kodPocztowy", "prg-ad:miejscowosc", "prg-ad:ulica", "prg-ad:numerPorzadkowy", "gml:pos"]
transformer = Transfo... |
from openstatesapi.jurisdiction import make_jurisdiction
J = make_jurisdiction('nh')
J.url = 'http://nh.gov' |
from django.template import Context
from django.template.loader import get_template
class RenderObject(object):
template = None
def __init__(self, *args, **kwargs):
super(RenderObject, self).__init__()
self.kwargs = kwargs
def render(self):
if not self.template:
raise Exc... |
import os, sys, time, errno, six, io
def is_running(pid):
'''Returns True if process with PID `pid` is running. Current user must
have permission to access process information.'''
try:
os.kill(pid, 0)
except OSError as exc:
if exc.errno == errno.ESRCH:
return False
ra... |
from pytest import fixture, skip, PLATFORM
if PLATFORM == 'win32':
skip('Broken on Windows')
from circuits import Component, Event
from circuits.net.events import close
from circuits.node import Node, remote
from circuits.net.sockets import UDPServer
class App(Component):
ready = False
value = False
dis... |
import logging
import textwrap
import numpy as np
from copy import deepcopy
from .las_items import HeaderItem, CurveItem, SectionItems, OrderedDict
from . import defaults
from . import exceptions
logger = logging.getLogger(__name__)
def write(
las,
file_object,
version=None,
wrap=None,
STRT=None,
... |
from mod import MOD
from files import *
from loaders.gene_loader import GeneLoader
from loaders.disease_loader import DiseaseLoader
import gzip
import csv
class WormBase(MOD):
species = "Caenorhabditis elegans"
@staticmethod
def gene_href(gene_id):
return "http://www.wormbase.org/species/c_elegans/g... |
import time, sys, signal, atexit
import pyupm_hdxxvxta as sensorObj
def SIGINTHandler(signum, frame):
raise SystemExit
def exitHandler():
print "Exiting"
sys.exit(0)
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
print "Initializing..."
sensor = sensorObj.HDXXVXTA(1, 0)
while (1):
#... |
import ljd.ast.nodes as nodes
import ljd.ast.traverse as traverse
from ljd.ast.helpers import insert_table_record
def eliminate_temporary(ast):
_eliminate_multres(ast)
slots, unused = _collect_slots(ast)
_eliminate_temporary(slots)
# _remove_unused(unused)
_cleanup_invalid_nodes(ast)
return ast
def _eliminate_tem... |
import os
import time
from sys import platform as _platform
class colors:
red = '\033[31m'
blue = '\033[34m'
magenta = '\033[35m'
cyan = '\033[36m'
reset = "\033[0m"
def main_master():
if _platform == "linux" or _platform == "linux2":
print'[!] You are on Linux.'
print colors.cyan + '\... |
import time
import boto
from boto.connection import AWSAuthConnection
from boto.provider import Provider
from boto.exception import SWFResponseError
from boto.swf import exceptions as swf_exceptions
from boto.compat import json
Debug = 0
class Layer1(AWSAuthConnection):
"""
Low-level interface to Simple WorkFlo... |
"""This implements a virtual screen. This is used to support ANSI terminal
emulation. The screen representation and state is implemented in this class.
Most of the methods are inspired by ANSI screen control codes. The ANSI class
extends this class to add parsing of ANSI escape codes.
$Id$
"""
import copy
NUL = 0 # ... |
"""
Script that trains multitask models on Tox21 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import shutil
import numpy as np
import deepchem as dc
from tox21_datasets import load_tox21
np.random.seed(123)
n_features = 1024
tox21_t... |
from setuptools import setup, find_packages
setup(
name='Dragon Knight',
version='1.1.0',
packages=find_packages('.')
) |
import threading
from pygtail import Pygtail
class Source(threading.Thread):
"""
Clase Source de la que heredan todas las fuentes que queramos procesar en nuestra aplicacion
"""
def __init__(self, group=None, target=None, name=None,
args=(), source=None, verbose=None):
"""
... |
from __future__ import unicode_literals
from django.db import models, migrations
def change_lesson_on_spreadsheets(apps, schema_editor):
'''Change "dc/spreadsheet" → "dc/spreadsheets".'''
Lesson = apps.get_model('workshops', 'Lesson')
Lesson.objects.filter(name='dc/spreadsheet').update(name='dc/spreadsheets... |
version = "$Revision: 910524 $"
progname = "hotshot2cachegrind"
import os, sys
from hotshot import stats,log
import os.path
file_limit=0
what2text = {
log.WHAT_ADD_INFO : "ADD_INFO",
log.WHAT_DEFINE_FUNC : "DEFINE_FUNC",
log.WHAT_DEFINE_FILE : "DEFINE_FILE",
log.WHAT_LINENO : "LINENO",
log.W... |
import re
import rfc3987
from jsonschema import FormatChecker
from pyramid.threadlocal import get_current_request
from .server_defaults import (
ACCESSION_FACTORY,
test_accession,
)
from uuid import UUID
accession_re = re.compile(r'^ENC(FF|SR|AB|BS|DO|LB|PL)[0-9][0-9][0-9][A-Z][A-Z][A-Z]$')
test_accession_re = ... |
import pytest
def test_am_tokenizer_handles_long_text(am_tokenizer):
text = """ሆሴ ሙጂካ በበጋ ወቅት በኦክስፎርድ ንግግር አንድያቀርቡ ሲጋበዙ ጭንቅላታቸው "ፈነዳ"።
“እጅግ ጥንታዊ” የእንግሊዝኛ ተናጋሪ ዩኒቨርስቲ፣ በአስር ሺዎች የሚቆጠሩ ዩሮዎችን ለተማሪዎች በማስተማር የሚያስከፍለው
እና ከማርጋሬት ታቸር እስከ ስቲቨን ሆኪንግ በአዳራሾቻቸው ውስጥ ንግግር ያደረጉበት የትምህርት ማዕከል፣ በሞንቴቪዴኦ
በሚገኘው የመንግስት ትምህርት ቤት የሰለጠኑትን የ... |
"""Unit tests illustrating usage of the ``history_meta.py``
module functions."""
from unittest import TestCase
import warnings
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import select
... |
revision = '8'
down_revision = '7'
from alembic import op
column = 'hr_avg'
def upgrade():
op.create_index("move_user_id_%s_idx" % column, 'move', ['user_id', column], unique=False)
def downgrade():
op.drop_index("move_user_id_%s_idx" % column, table_name='move') |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oscardemo.settings.override")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import unittest
from biicode.common.test.bii_test_case import BiiTestCase
from biicode.common.edition.project_manager import ProjectManager
from biicode.common.find.finder_result import FinderResult
from biicode.common.find.policy import Policy
from biicode.common.model.brl.brl_block import BRLBlock
from biicode.common... |
from __future__ import unicode_literals
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from paypal.pro.exceptions import PayPalFailure
from paypal.pro.forms import ConfirmForm, PaymentForm
from paypal.pro.helpers import PayPalWPP, express_endpoint_for_token
from paypa... |
class MaskType(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict):... |
import functools
import nose
def expected_failure(test):
@functools.wraps(test)
def inner(*args, **kwargs):
try:
test(*args, **kwargs)
except Exception:
raise nose.SkipTest
else:
raise AssertionError(
'A failure was expected, but this t... |
import sys
import struct
import socket
import hashlib
import logging
from time import sleep
logger = logging.getLogger('pyhpfeeds')
OP_ERROR = 0
OP_INFO = 1
OP_AUTH = 2
OP_PUBLISH = 3
OP_SUBSCRIBE = 4
BUFSIZ = 16384
__all__ = ["new", "FeedException"]
def msghdr(op, data):
return struct.pack(... |
from waflib import Utils
def __get_cc_env_vars__(cc):
cmd = cc + ['-dM', '-E', '-']
try:
p = Utils.subprocess.Popen(cmd, stdin=Utils.subprocess.PIPE,
stdout=Utils.subprocess.PIPE,
stderr=Utils.subprocess.PIPE)
p.stdi... |
read("d.nex")
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=1, val=0.2)
m = Mcmc(t, nChains=4, runNum=0, sampleInterval=1000, checkPointInterval=250000)
m.run(... |
"""Define utilities for special formatting of records."""
import datetime
import time
from flask import current_app, make_response
from flask_login import current_user
from werkzeug.http import http_date
from .api import get_output_format_content_type
from .engine import format_records
def response_formated_records(rec... |
"""Brush editor"""
import os
import logging
logger = logging.getLogger(__name__)
from gettext import gettext as _
import gi
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from gi.repository import GObject
from gi.repository import GdkPixbuf
from libmypaint import brushsettin... |
"""
***************************************************************************
OTBAlgorithmProvider.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'information
Email : vol... |
import argparse
import os
import random
import sys
dirname = 'testdata/permutations'
defaultlines = ['aaa\n',
'bbb\n',
'ccc\n',
'ddd\n',
'eee\n']
options = [ ('1','1','1'),
('1','1','2'),
('1','1',None),
('1','2','1'),
... |
"""Perform classifier operations."""
import os
import sys
from flask import current_app
from invenio.ext.script import Manager
from .api import get_keywords_from_local_file
manager = Manager(usage=__doc__)
@manager.option('-f', '--file', dest='filepath',
help='load knowledge base from this file.')
@mana... |
"""Get the recid of a record based upon report-number, as stored
in the global variable 'rn'.
**Deprecated - Use Get_Recid Instead**
"""
__revision__ = "$Id$"
##
## Name: Get_Sysno.py
## Description: function Get_Sysno
## This function retrieves the system number of a documen... |
from textwrap import dedent
from unittest import (
TestCase,
mock,
)
from pcs import settings
from pcs.common.reports import ReportItemSeverity as severities
from pcs.common.reports import codes as report_codes
from pcs.lib.commands import resource
from pcs_test.tools import fixture
from pcs_test.tools.command_... |
from gnuradio import gr
from gnuradio import blocks
from gnuradio import filter
from gnuradio.fft import window
from gnuradio import analog
from gnuradio import channels
import sys
import math
import time
import numpy
try:
import pylab
except ImportError:
print("Error: Program requires matplotlib (see: matplotl... |
"""
plainbox.impl.exporter.test_rfc822
==================================
Test definitions for plainbox.impl.exporter.rfc822 module
"""
from io import BytesIO
from unittest import TestCase
from plainbox.impl.exporter.rfc822 import RFC822SessionStateExporter
class RFC822SessionStateExporterTests(TestCase):
def test_... |
import urllib
import re
import generic
from sickbeard import logger
from sickbeard import tvcache
class BinSearchProvider(generic.NZBProvider):
def __init__(self):
generic.NZBProvider.__init__(self, "BinSearch")
self.public = True
self.cache = BinSearchCache(self)
self.urls = {'base_... |
"""Translation service using Google Translate"""
import re
import simplejson
from madcow.util import strip_html
from madcow.util.http import geturl
from madcow.util import Module
class ChatLine(object):
def __init__(self, nick, text):
self.nick = nick
self.text = text
def __str__(self):
... |
from .instance import Instance
from .user import User |
cmd=''
f=open('server.sql','r')
for line in f:
if not line:
break
line=line.strip()
if not line:
continue
cmd+=line
if line[len(line)-1]==';':
print cmd
cmd=''
f.close() |
import numpy
from safe.impact_functions.core import FunctionProvider
from safe.impact_functions.core import get_hazard_layer, get_exposure_layers
from safe.storage.raster import Raster
from safe.common.utilities import verify
from numpy import nansum as sum
class HKVFloodImpactFunctionTEST(FunctionProvider):
"""Ris... |
import pytest
from unittest.mock import MagicMock
pytestmark = pytest.mark.bdb
@pytest.mark.skipif(reason='Will be handled by #1126')
def test_asset_id_index():
from bigchaindb.backend.mongodb.query import get_txids_filtered
from bigchaindb.backend import connect
# Passes a mock in place of a connection to ... |
"""
OmeValidator.py
Created by Andrew Patterson on 2007-07-24.
"""
import traceback
import logging
from xml.dom.minidom import getDOMImplementation
from StringIO import StringIO
from xml import sax
import os
from stat import *
logger = logging.getLogger('omevalidator')
SCHEMA_DIR = os.path.join(os.path.dirname(__file__... |
import time, sys, os, shutil, subprocess, distutils.dir_util
sys.path.append("../../configuration")
if os.path.isfile("log.log"):
os.remove("log.log")
if os.path.isfile("temp_log.log"):
os.remove("temp_log.log")
log = open("temp_log.log", "w")
from scripts import *
from buildsite import *
from process import *
from t... |
"""
Tests for Studio Course Settings.
"""
import copy
import datetime
import json
import unittest
from unittest import mock
from unittest.mock import Mock, patch
import ddt
from crum import set_current_request
from django.conf import settings
from django.test import RequestFactory
from django.test.utils import override... |
from . import model
from . import wizard |
import random
import pytest
import gevent
from inbox.ignition import engine_manager
from inbox.models.session import session_scope, session_scope_by_shard_id
from inbox.models.action_log import ActionLog, schedule_action
from inbox.transactions.actions import SyncbackService
from tests.util.base import add_generic_imap... |
from spack import *
class PyScientificpython(PythonPackage):
"""ScientificPython is a collection of Python modules for
scientific computing. It contains support for geometry,
mathematical functions, statistics, physical units, IO,
visualization, and parallelization."""
homepage = "https://s... |
from __future__ import print_function, absolute_import, division
from __future__ import division
import sys
import unittest
import re
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))
from SpiffWorkflow.specs import WorkflowSpec, Simple, Join
from SpiffWorkflow.specs.SubWorkflow im... |
from SeleniumLibrary import SeleniumLibrary
from SeleniumLibrary.base import keyword
class ExtSL(SeleniumLibrary):
@keyword
def ext_web_element(self, locator):
return self.get_webelements(locator)
@keyword
def ext_page_should_contain(self, text):
self.page_should_contain(text) |
from lymph.cli.base import Command, get_command_classes, get_command_class, format_docstring
HEADER = 'Usage: lymph <command> [options] [<args>...]'
HELP = HEADER + """
lymph help display help overview
lymph help <command> display command documentation
"""
TEMPLATE = HEADER + """
{COMMON_OPTIONS}
Comm... |
from .attention import Attention
from .gated_attention import GatedAttention
from .masked_softmax import MaskedSoftmax
from .matrix_attention import MatrixAttention
from .max_similarity_softmax import MaxSimilaritySoftmax
from .weighted_sum import WeightedSum |
"""
=======================
Triggered File Reader
=======================
This component accepts a filepath as an "inbox" message, and outputs the
contents of that file to "outbox". All requests are processed sequentially.
This component does not terminate.
"""
from Axon.Component import component
class TriggeredFileRe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.