content stringlengths 4 20k |
|---|
import os
import sys
import string
from configuracoes import *
from comum.compilador.analisador_lexico import decompoe_texto_fonte, classificador_lexico
from comum.automatos.loaders import transdutor_finito
from meta_reconhecedor import MetaReconhecedor
from minimizador import *
# leitor e classificador de caractere... |
import yaml
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.web import server
from twisted.internet import ssl
from zope.interface import implements
from specter import service
class Opti... |
import inspect
import os
import unittest
from unittest.mock import patch, MagicMock, call
from server.piledhttprequesthandler import PiLEDHTTPRequestHandler
mock_makeDevBuild = MagicMock()
def mock_init(self, request, client_address, server):
self._clientResourceBaseDir = os.path.dirname(
os.path.dirnam... |
import anydbm, whichdb
import os.path
import json
from itertools import chain
from inspect import cleandoc
import gtk, pango
from uxie.utils import make_missing_dirs, join_to_settings_dir
def init(injector):
injector.bind('window', 'editor-prefs', 'Prefs/_Editor settings#1', show_editor_preferences)
injector... |
from rezgui.qt import QtCore, QtGui
from rezgui.models.ContextModel import ContextModel
from rezgui.mixins.ContextViewMixin import ContextViewMixin
from rez.utils.formatting import readable_time_duration
import time
class ContextResolveTimeLabel(QtGui.QLabel, ContextViewMixin):
def __init__(self, context_model=No... |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,... |
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
SQLite3 implementation of database operations.
"""
backend_name = "sqlite3"
# SQLite ignores several constraints. I wish I could.
supports_foreign_keys = False
has_check_constraints = Fal... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from rest_framework.settings import api_settings
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.contrib.distributions.python.ops import operator_pd_full
from tensorflow.contrib.distributions.python.ops import operator_pd_vdvt_update
from tensorfl... |
import mock
from twisted.internet import defer
from twisted.trial import unittest
from buildbot.process import log
from buildbot.process import logobserver
from buildbot.test.fake import fakemaster
from buildbot.test.util.misc import TestReactorMixin
class MyLogObserver(logobserver.LogObserver):
def __init__(s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ziggurat_foundations.models.base import get_db_session
from ziggurat_foundations.models.services import BaseService
__all__ = ["ExternalIdentityService"]
class ExternalIdentityService(BaseService):
@classmethod
def get(cls, external_id, lo... |
"""
Twitter platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.twitter/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (
... |
"""Module with utility functions for FCHK files."""
import numpy as np
from psi4.driver.p4util.testing import compare_strings, compare_arrays, compare_values, compare_integers
from psi4 import core
from .exceptions import ValidationError
__all__ = ['fchkfile_to_string','compare_fchkfiles']
def _consume_fchk_section(... |
'''
Test case to show how to use phase loop (CERN PS Booster context).
:Authors: **Danilo Quartullo**
'''
from __future__ import division, print_function
import numpy as np
from blond.input_parameters.ring import Ring
from blond.input_parameters.rf_parameters import RFStation
from blond.trackers.tracker import RingAn... |
import os
import subprocess
import sys
from sphinx.errors import ExtensionError
from . import ref
def setup(app):
"""Register the extension with Sphinx.
Args:
app: The Sphinx application.
"""
for name, (default, rebuild, _) in ref.CONFIG_VALUES.iteritems():
app.add_config_value(name... |
from collections import namedtuple
from biicode.common.exception import ConfigurationFileError
from biicode.common.edition.parsing.conf.conf_file_parser import parse
def parse_deps_conf(text, line_number):
dependencies = []
def parse_dependencies(line):
dep = DependentConfiguration.parse(line)
... |
from __future__ import unicode_literals
from __future__ import print_function
from moya import tools
from moya.context.missing import Missing
from moya.compat import text_type
from moya.elements.elementbase import ReturnContainer
import pytz
import datetime
import unittest
import io
import os.path
class TestTools(u... |
"""
Python Lexical Analyser
Traditional Regular Expression Syntax
"""
from plex.regexps import *
from plex.errors import PlexError
class RegexpSyntaxError(PlexError):
pass
def re(s):
"""
Convert traditional string representation of regular expression |s|
into Plex representation.
"""
retur... |
import datetime
import functools
import json
import uuid
from aiohttp import web
from aiohttp_apiset.views import ApiSet
from .redis import RedisMixin
class JsonEncoder(json.JSONEncoder):
ensure_ascii = False
@classmethod
def dumps(cls, data, **kwargs):
kwargs.setdefault('ensure_ascii', cls.ens... |
"""WebSocket based API for Home Assistant."""
from homeassistant.core import callback
from homeassistant.loader import bind_hass
from . import commands, connection, const, decorators, http, messages
DOMAIN = const.DOMAIN
DEPENDENCIES = ('http',)
# Backwards compat / Make it easier to integrate
# pylint: disable=inv... |
"""
Handles all requests relating to volumes + cinder.
"""
import copy
import sys
from cinderclient import client as cinder_client
from cinderclient import exceptions as cinder_exception
from cinderclient.v1 import client as v1_client
from keystoneclient import exceptions as keystone_exception
from keystoneclient imp... |
"""SCons.Tool.zip
Tool-specific initialization for zip.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permiss... |
from distutils.core import setup
setup(
url = 'https://github.com/uxcn/sh-utils',
name = 'sh-utils',
version = '0.9',
fullname = 'sh-utils',
description = 'some commands to simplify various things',
long_descr... |
import collections
import polib
import datetime
import os
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-i", "--input", dest="input",
help="nightly.nsi location", default="../Shared/installer/nightly.nsi" )
parser.add_option("-o", "--output", dest="output",
... |
from django.contrib import admin
from jaam.photos.models import Photo, PhotoGallery, PhotoExifData, PhotoGalleryItem
from jaam.journalism.admin import BaseAdmin
class PhotoAdmin(BaseAdmin):
add_form_template = 'admin/photo_add.html'
search_fields = ('title', 'caption',)
list_display = ('__unicode__', 'proj... |
from __future__ import division
from __future__ import absolute_import
import re
from datetime import datetime
from sqlobject import *
from beerlog.comment.models import Comment
class Entry(SQLObject):
title = UnicodeCol(length=255)
body = UnicodeCol()
tags = RelatedJoin('Tag')
slug = UnicodeCol(leng... |
# External Libraries
import numpy
import matplotlib.pyplot as ppt
import sys
def iterate(wage, wealth, p, p0, p1, alpha, gamma):
nextpd = []
if wage == 0:
nextpd.append((0, (1 - gamma) * wealth, p0))
nextpd.append((1, (1 - gamma) * wealth + (1 - alpha), 1 - p0))
if wage == 1:
nex... |
import logging
import os
from absl import app
from absl import flags
from contextlib import suppress
from datetime import datetime
from urllib.parse import unquote
from classes.report_type import Type
from main import report_fetch, report_runner
logging.basicConfig(
filename=f'report2bq-{datetime.now().strftime("%... |
class ComponentAdapter:
def __init__(self, components, name, data):
self.components = components
self.name = name
self.data = data
@property
def optional(self):
return self.data.get('optional', [])
@property
def supersedes(self):
return self.data.get('super... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
__author__ = 'Francics'
from codecs import open
import os.path
def DelFileLine(filename,bgnline,endline):
'''
parament:
filename
bgnline int 待删除文件的开始行数
endline int 待删除文件的结束行数
'''
if not isinstance(bgnline,int):
raise TypeError('bgnline ... |
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'core',
'version': '1.0'
}
import re
from ansible.module_utils.ios import run_commands
from ansible.module_utils.ios import ios_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import it... |
from __future__ import division
import math
import numpy as np
def tile_images(imgs, n_col, pad=2, fill=0):
"""Make a tile of images
Args:
imgs (numpy.ndarray): A batch of images whose shape is BCHW.
n_col (int): The number of columns in a tile.
pad (int or tuple of two ints): :obj:`... |
import wx
from src.wizard.view.clsFileList import FileListView
from src.models.YamlConfiguration import YamlConfiguration
from src.common.functions import searchDict
class FileListController(FileListView):
def __init__(self, daddy, **kwargs):
super(FileListController, self).__init__(daddy, **kwargs)
... |
#!/usr/bin/env python
import inspect
import os
import subprocess
import socket
import ssl
import sys
import time
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[... |
from c7n.utils import type_schema
from c7n_azure.actions.base import AzureBaseAction
class DeleteAction(AzureBaseAction):
"""
Perform delete operation on any ARM resource. Can be used with
generic resource type `armresource` or on any other more specific
ARM resource type supported by Cloud Custodian.... |
"""
Tests for graph traversal generator functions.
"""
from __future__ import absolute_import
from unittest import TestCase
import ddt
from ..grade_utils import compare_scores
@ddt.ddt
class TestGradeUtils(TestCase):
""" Tests for the grade_utils module. """
@ddt.data(
(1, 2, 3, 4, False, True, 0.5... |
# ~*~ coding: utf-8 ~*~
import os
import re
import pytz
from django.utils import timezone
from django.shortcuts import HttpResponse
from django.conf import settings
from .utils import set_current_request
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
de... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
na... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_appliance_health_info
short_description: Gathers info about health of the VCSA.... |
#!/usr/bin/python
import subprocess
import praw
import datetime
import pyperclip
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringIO
from base64 import b64encode
from base64 import b64decode
from ConfigParser import ConfigParser
import OA... |
#!/usr/bin/env python
## zip archive frontend for git-fast-import
##
## For example:
##
## mkdir project; cd project; git init
## python import-zips.py *.zip
## git log --stat import-zips
from os import popen, path
from sys import argv, exit
from time import mktime
from zipfile import ZipFile
if len(argv) < 2:
p... |
import logging
try:
import click
from lockfile import LockFile, LockTimeout
except ImportError:
click = None
logger = logging.getLogger('spoppy.main')
def get_version():
return '2.4.0'
if click:
@click.command()
@click.argument('username', required=False)
@click.argument('password', re... |
from logging import INFO, Formatter
from logging.handlers import RotatingFileHandler
from flask import Flask, current_app
from flask_restful_swagger_2 import Api, request
from routes.api.chat.chat import Chat, ChatInvitation
from routes.api.tour.tour_detail import TourDetail
from routes.api.tour.tour_list import Cate... |
from __future__ import unicode_literals
import frappe
from frappe.website.website_generator import WebsiteGenerator
class Chapter(WebsiteGenerator):
_website = frappe._dict(
condition_field = "published",
)
def get_context(self, context):
context.no_cache = True
context.show_sidebar = True
context.parents ... |
from catalyst.assets import Equity
from catalyst.finance.slippage import SlippageModel
from catalyst.utils.sentinel import sentinel
class TestingSlippage(SlippageModel):
"""
Slippage model that fills a constant number of shares per tick, for
testing purposes.
Parameters
----------
filled_per_... |
from test import test_support
import unittest
import sys, cStringIO, subprocess
import quopri
ENCSAMPLE = """\
Here's a bunch of special=20
=A1=A2=A3=A4=A5=A6=A7=A8=A9
=AA=AB=AC=AD=AE=AF=B0=B1=B2=B3
=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE
=BF=C0=C1=C2=C3=C4=C5=C6
=C7=C8=C9=CA=CB=CC=CD=CE=CF
=D0=D1=D2=D3=... |
"""
This script can be used to set up a Google Maps Trip Query at a specific point in time.
Necessary Google APIs:
Directions API
Distance Matrix API
Elevation API
Geocoding API
Time Zone API
Roads API
See more on how to enable these here: https://github.com/googlemaps/google-maps-services-python
"""
import emission.... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
from erpnext.education.utils import validate_duplicate_student
from frappe.utils import cint
class StudentGroup(Document):
def validate(self):
self.validate_mandatory_fields()
self.validate_streng... |
from build_assistant.autogen.AutoGenConfig import EnumConfig, EnumValue
from build_assistant.autogen.raw_events.constants import BASE_EVENTS_PATH, SUBTYPE_ENUM, BASE_EVENT_CLASS
from build_assistant.autogen.raw_events.common import event_class_name, event_subtype_value
from build_assistant.autogen.raw_events.BaseEventC... |
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
from c7n.query import QueryResourceManager, ChildResourceManager
from c7n.manager import resources
from c7n.utils import chunks, get_retry, generate_arn, local_session
from c7n.resources.shield import IsShieldProtecte... |
import datetime
import logging
import re
import google.appengine.ext.ndb as ndb
import models
XREF_RE = re.compile(r'k8s-gubernator.appspot.com/build(/[^])\s]+/\d+)')
class Deduper(object):
''' A memory-saving string deduplicator for Python datastructures.
This is somewhat like the built-in intern() func... |
from neutron.common import constants
from neutron.common import topics
from neutron.common import utils
from neutron import manager
from neutron.openstack.common import log as logging
from neutron.openstack.common.rpc import proxy
LOG = logging.getLogger(__name__)
class DhcpAgentNotifyAPI(proxy.RpcProxy):
"""AP... |
"""
This module contains the occurrences highlighter mode.
"""
from pyqode.qt import QtGui
from pyqode.core.api import Mode, DelayJobRunner, TextHelper, TextDecoration
from pyqode.core.backend import NotRunning
from pyqode.core.backend.workers import findall
class OccurrencesHighlighterMode(Mode):
""" Highlights ... |
#!/usr/bin/python
import __main__
global quote_reacted
quote_reacted = {}
#===================================================================================================================
#PLUGIN CALLS
async def help_menu():
help_info = {}
help_info['title'] = 'Quote messages'
help_info['description'... |
# Exercise 3
#
# Change the Guess My Number so the player picks a number between 1 and 100 and the computer has to guess. Before you
# start, think about how you guess. If all goes well, try coding the game.
#
import random
max_val = 100
guesses = 100
n_found = False
number = random.randint(0, max_val)
comp_number = ... |
import handlers
from django.conf.urls import *
from treeio.core.api.auth import auth_engine
from treeio.core.api.doc import documentation_view
from treeio.core.api.resource import CsrfExemptResource
ad = {'authentication': auth_engine}
# messaging resources
mlistResource = CsrfExemptResource(handler=handlers.MailingL... |
"""Easily update version numbers across your project.
"""
import argparse
from functools import reduce
import re
import sys
import toml
from . import deltas
__version__ = "0.2"
class ConfigError(ValueError):
pass
def read_config():
with open('reversion.toml') as f:
conf = toml.load(f)
if 'curre... |
# coding: utf-8
import sqlite3
import time
class NodesTrace:
"""
Author: Sébastien Vaucher
From: https://github.com/sebyx31/ErasureBench/blob/e1dbac83dd7993302da049db700105b8fa4df69f/projects/erasure-tester/container-scripts/nodes_trace.py
A generator for the number of nodes in the cluster at each ti... |
CppTypeMap = {
'string': 'std::string',
'xsd:string': 'std::string',
'xsd:integer': 'int',
'xsd:unsignedInt': 'uint32_t',
'xsd:boolean': 'bool',
'xsd:unsignedLong' : 'uint64_t',
'xsd:dateTime': 'time_t',
'xsd:time': 'time_t'
}
JavaTypeMap = {
'string': 'String',
'xsd:string': 'S... |
#I2C address table
#address |device
#0x0Bh |Arduino
#0x77h |BMP180
#0x0Ah |D6T
#program structure
#every 1000ms will:
# read any new commands from XBEE
# execute commands if necessary
# poll sensors for data
# request data and commands from Arduino
# execute commands if necessary
# assemb... |
# coding=utf-8
from unittest import TestCase
from nose.tools import eq_
from grail import step, BaseTest
from tests.utils import validate_method_output
korean_string = '올'
russian_string = 'д'
class TestEncoding(TestCase):
def test_localization_exception(self):
validate_method_output(self.verify_step, u'... |
#! /usr/bin/env python
import re
import sys
import semver
import requests
import json
from datetime import datetime
from getpass import getpass
from pbs import git, ant, scp, pwd, cd, ssh
def retreive_build_number():
return open('build.ver').read()
if __name__ == '__main__':
try:
releases_root = '/a... |
import sys
import time
import random
sys.path.insert(0, "bin/python")
import samba.tests
from ldb import SCOPE_BASE, LdbError
import samba.tests
import samba.dcerpc.drsuapi
from samba.dcerpc.drsblobs import schemaInfoBlob
from samba.ndr import ndr_unpack
from samba.dcerpc.misc import GUID
class SchemaInfoTestCase(... |
import os
import sys
import subprocess
import signal
import argparse
import time
import random
from dht.network import DhtNetwork
from dht.network import DhtNetworkSubProcess
from dht.tests import PerformanceTest, PersistenceTest, PhtTest
from dht import virtual_network_builder
from dht import network as dhtnetwork
f... |
import collections
import itertools
import os
import unittest
from telemetry.testing import fakes
from gpu_tests import fake_win_amd_gpu_info
from gpu_tests import gpu_test_base
from gpu_tests import path_util
from gpu_tests import test_expectations
from gpu_tests import webgl_conformance
from gpu_tests import webgl_... |
from catmap import ReactionModel
mkm_file = 'CO_oxidation.mkm'
model = ReactionModel(setup_file=mkm_file)
model.run()
from catmap import analyze
vm = analyze.VectorMap(model)
vm.plot_variable = 'rate' #tell the model which output to plot
vm.log_scale = True #rates should be plotted on a log-scale
vm.min = 1e-25 #mini... |
""" Module invoked for finding and loading DIRAC (and extensions) modules
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from DIRAC.Core.Utilities import List
from DIRAC import gConfig, S_ERROR, S_OK, gLogger
from DIRAC.ConfigurationSystem.Cli... |
"""
A special directive for generating a matplotlib plot.
.. warning::
This is a hacked version of plot_directive.py from Matplotlib.
It's very much subject to change!
Usage
-----
Can be used like this::
.. plot:: examples/example.py
.. plot::
import matplotlib.pyplot as plt
plt.plot... |
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.list... |
# import dao3032
# No longer imported here - callers responsibility to load
#
import win32com.client
def DumpDB(db, bDeep = 1):
# MUST be a DB object.
DumpTables(db,bDeep)
DumpRelations(db,bDeep)
DumpAllContainers(db,bDeep)
def DumpTables(db, bDeep = 1):
for tab in db.TableDefs:
tab = db.T... |
# coding:utf-8
import sys
import logging
import argparse
import threading
import time
from six.moves import queue
from captain_comeback.index import CgroupIndex
from captain_comeback.restart.engine import RestartEngine
logger = logging.getLogger()
DEFAULT_ROOT_CG = "/sys/fs/cgroup/memory/docker"
DEFAULT_SYNC_TARGE... |
import ROOT
from PyAnalysisTools.base.FileHandle import FileHandle
from PyAnalysisTools.PlottingUtils.PlotConfig import PlotConfig as pc
from PyAnalysisTools.PlottingUtils.ComparisonPlotter import ComparisonPlotter
from PyAnalysisTools.base.OutputHandle import OutputFileHandle
class FONLLCalculator(ComparisonPlotter)... |
""" This module implements the DecompressionMiddleware which tries to recognise
and extract the potentially compressed responses that may arrive.
"""
import bz2
import gzip
import logging
import tarfile
import zipfile
from io import BytesIO
from tempfile import mktemp
from scrapy.responsetypes import responsetypes
... |
import os
import pytest
from tagsets.script import ScriptContext
# Test support code
# Tests
# require command
def test_script_require_command_true():
runner = ScriptContext({})
code = compile("require(\"a tree is a tree is a tree\", True)",
'<string>', 'exec')
runner.run_python_cod... |
"""
This class provides data structures and functions for reading a MESA profile.
Copyright 2015 Donald E. Willcox
This file is part of mesa2flash.
mesa2flash 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 Fou... |
# coding: utf-8
'''
tests.test_radar
~~~~~~~~~~~~~~~~
Tests radar.
'''
from datetime import datetime
from yufou import radar
def test_round_to_5_minutes():
for minute in range(0, 5):
d = datetime.utcnow().replace(minute=minute)
assert 0 == radar.round_to_5_minutes(d).minute
fo... |
"""
A fake SMTP server which runs in its own thread. Use this in tests to capture
e-mails sent by Beaker and assert their contents.
"""
import threading
import smtpd
import asyncore
import logging
log = logging.getLogger(__name__)
class CapturingSMTPServer(smtpd.SMTPServer):
def __init__(self, localaddr, remo... |
from executil import ExecError, getoutput
class Device:
"""class to hold device information enumerated from udev database"""
def __init__(self, s, volinfo=True):
self.path = ''
self.name = ''
self.symlinks = []
self.env = {}
self._parse_raw_data(s)
if volinfo:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Calculate and manipuate kmer
"""
import re
import itertools
import math
from collections import deque
from collections import Counter
import numpy as np
import Bio.SeqIO as SeqIO
# Global variable
KMER_ARR = ["A", "C", "G", "T"]
KSIZE_LIMIT = 31
# Regex to clean se... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import block.models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('block', '0011_auto_20151030_1551'),
migrations.swappable_dependency(settings.AUT... |
#!/usr/bin/python2.7
import random
import argparse
import sys
import string
import copy
from random import Random
#Gobal vars
state = ''
first = ''
last = ''
# The files with all the countries
country_file = 'data/countries.txt'
# A file with all the states in the USA
usa_states_file = 'data/usa_states.txt'
# All ... |
import unittest
import MySQLdb
from _mysql_exceptions import OperationalError
from os import fork
from time import sleep, time
from contextlib import closing
from uuid import uuid4
def spin(count, pid=1):
if pid == 0:
return count + 1
if count < 1:
return 0
else:
return spin(count -... |
"""
Copyright 2015 Rackspace
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 or agreed to in writing, software
dist... |
"""SCons.Tool.aixcc
Tool-specific initialization for IBM xlc / Visual Age C compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 20... |
from unittest import TestCase
from arclength.qss import QSS3ArcLength
class QSS3ArcLengthTest(TestCase):
def test_qss3_arc_length(self):
v_x = [([1e-09, 299.49220799999995, 0.0], 3.338985032959523e-12, 0.0001798411682143429),
([0.05386102855781296, 299.49220799999995, 0.0], 0.00017984... |
import theano
import theano.tensor as T
import numpy as np
from theano.printing import Print
from theano_toolkit import utils as U
from theano_toolkit.parameters import Parameters
from theano.tensor.extra_ops import repeat
import controller
import head
import scipy
def cosine_sim(k, M):
k_lengths = T.sqrt(T.sum(k... |
import scipy as sp
import numpy as np
import cv2
from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
from skimage.data import camera
from scipy.linalg import pinv
import matplotlib.pyplot as plt
cv_ver = int(cv2.__version__.split('.')[0])
_cv2_LOAD_IMAGE_COLOR = cv2.IMREAD_COLOR if c... |
#!/usr/bin/env python3
# encoding: utf-8
"""
trackplacer3.datatypes -- file-format-independent handling of journeys
A journey is an object containing a map file name and a (possibly
empty) list of tracks, each with a name and each consisting of a
sequence of track markers.
Original (python2 + pygtk) implementation by... |
"""Multi tab memory test.
This test is a multi tab test, but we're interested in measurements for
the entire test rather than each single page.
"""
from telemetry.page import page_test
from metrics import memory
class MemoryMultiTab(page_test.PageTest):
def __init__(self):
super(MemoryMultiTab, self).__init_... |
# coding=utf-8
"""Wizard Step Browser."""
import os
from sqlite3 import OperationalError
from PyQt4.QtCore import QSettings
from db_manager.db_plugins.postgis.connector import PostGisDBConnector
from qgis.core import (
QgsDataItem,
QgsVectorLayer,
QgsRasterLayer,
QgsDataSourceURI,
QgsBrowserModel)... |
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
#Python Dependencies
import sys, cmd, socket, optparse
from urlparse import urljoin
from cmd import Cmd
class jmxCmd(Cmd):
if l... |
import json
import collections
import copy
try:
unicode = unicode
except NameError:
unicode = str
class QueryResourceDoesNotExist(Exception):
'''Query returndtBCnOCz4bed no results'''
pass
class QueryResourceMultipleResultsReturned(Exception):
'''Query was supposed to return unique result, retur... |
"""Tests for the CORS CSRF version of Django Rest Framework's SessionAuthentication."""
from mock import patch
from django.middleware.csrf import get_token
from django.test import TestCase
from django.test.utils import override_settings
from django.test.client import RequestFactory
from django.conf import settings
... |
"""This module provides the blueprint for the statuses API endpoints.
For more information please refer to the documentation: http://bigchaindb.com/http-api
"""
from flask import current_app
from flask_restful import Resource, reqparse
from bigchaindb.web.views.base import make_error
class StatusApi(Resource):
... |
#!/usr/bin/env python3.3
import os
import re
import subprocess
"""
Prequisties need $GOPATH set and GO binary in $PATH
"""
go_extension = ".go"
current_directory = os.getcwd()
package_to_install_dir = os.path.basename(current_directory)
package_to_install_re = r"package(\s)+" + package_to_install_dir
go_tes... |
"""
Unittests for migrating a course to split mongo
"""
import six
from django.core.management import CommandError, call_command
from django.test import TestCase
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundE... |
#!/usr/bin/env python2.7
# -*- mode: python; coding: utf-8; -*-
"""
Module for processing SentiWS lexicon
Constants:
SWS_NEGATIVE - default name of negative polarity lexicon
SWS_POSITIVE - default name of positive polarity lexicon
TAB_RE - regexp matching tab separators
COMMA_RE - regexp matching comma separators
BAR... |
from Screens.Screen import Screen
from Plugins.Plugin import PluginDescriptor
from Components.SystemInfo import SystemInfo
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry, config, ConfigBoolean, ConfigNothing, ConfigSlider
from Components.Label import Label
from Compo... |
'''Commandline scripts.
These scripts are called by the executables defined in setup.py.
'''
from __future__ import with_statement, print_function
import abc
import sys
from optparse import OptionParser
import rsa
import rsa.bigfile
import rsa.pkcs1
HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
def keyge... |
import sys, os
sys.path.append((os.path.join(sys.path[0],'..')))
import functions
from shutil import copyfile
functions.register()
curpath = os.path.abspath(sys.path[0])
def gendoc(funtype, toplevelonly=False):
file=open(os.path.join(curpath, 'source', funtype+'.txt'),'w')
tmpstr=".. _"+(funtype.lower()+' ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.