content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
import re
from .base import CommandTestCase
from gandi.cli.commands import vlan
from gandi.cli.core.base import GandiContextHelper
class VlanTestCase(CommandTestCase):
def test_list(self):
result = self.invoke_with_exceptions(vlan.list, [])
self.assertEqual(result.outp... |
#! /usr/bin/python3
from time import process_time
from lxml import etree
import os
ifolder = '/home/nm/corpus/pre1950'
ofolder = '/home/nm/corpus-txt/pre1950'
def safe_str(text):
if text is not None:
return text
return ''
def get_fname_lists(ifolder, ofolder):
start = process_time()
ifname_l... |
import logging
from odoo.addons.mail.controllers.main import MailController
from odoo import http
from odoo.http import request
_logger = logging.getLogger(__name__)
class CrmController(http.Controller):
@http.route('/lead/case_mark_won', type='http', auth='user', methods=['GET'])
def crm_lead_case_mark_wo... |
"""
Brine, advanced pickle features for python
author: Christopher O'Brien <<EMAIL>>
license: LGPL v.3
"""
from setuptools import setup, Extension
import multiprocessing # NOQA : this import is required for tests to work
ext = [Extension("brine._cellwork", ["brine/cellwork.c"]), ]
setup(name = "brine",
v... |
import sys
sys.path.append("..")
from flask import request, g
from hackathon.database import UserToken, User, UserEmail
from hackathon.constants import ReservedUser, HTTP_HEADER
from hackathon import Component, RequiredFeature
__all__ = ["UserManager"]
class UserManager(Component):
"""Component for user manag... |
# -*- coding: utf-8 -*-
from django import template
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.shortcuts import render_to_response
#
import uuid
#
from models import Blog
from forms import BlogForm
from mediafiles.models import MediaFile
from mediafiles.forms import MediaFileForm,medi... |
# -*- coding: utf-8 -*-
"""
Django settings for moocminder project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.... |
#! /usr/bin/env python
'''
<star/> is not working here
commands need the short and the long name
sort and grade process commands for other functions(adds self.
'''
import rospy
from robbie_behave.interaction import *
from std_msgs.msg import String, Float64
from robbie_msgs.msg import RobbieCmd
import time
#import js... |
# -*- coding: utf-8 -*-
import logging
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
logger = logging.getLogger(__name__)
# flake8: noqa
DEFAULT_PERMS = {
"Tester": {
"classification": {"a... |
# pma.py TestIntWrong
# 6 states, 5 transitions, 1 accepting states, 0 unsafe states, 1 finished and 0 deadend states
# actions here are just labels, but must be symbols with __name__ attribute
def Initialize(): pass
def ReadInt(): pass
def Login(): pass
def Logout(): pass
def UpdateInt(): pass
# states, key of each... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_HTTPError,
compat_str,
compat_urllib_parse_urlencode,
compat_urllib_parse_urlparse,
)
from ..utils import (
ExtractorError,
qualities,
)
class AddAnimeIE(InfoExtractor):
_VAL... |
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import int_or_none
class MporaIE(InfoExtractor):
_VALID_URL = r'^https?://(www\.)?mpora\.(?:com|de)/videos/(?P<id>[^?#/]+)'
IE_NAME = 'MPORA'
_TEST = {
'url': 'http://mpora.de/videos/AAd... |
from neon.layers.layer import (Linear, Bias, Affine, Conv, Convolution, GeneralizedCost, Dropout,
Pooling, Activation, DataTransform, BatchNorm, BatchNormAutodiff,
Deconv, Deconvolution, GeneralizedCostMask, LookupTable,
Branch... |
from .testmodels import FieldsWithoutOptionsModel
from django.test import TestCase
from google.appengine.api.datastore import Get
from google.appengine.ext.db import Key
from google.appengine.api.datastore_types import Text, Category, Email, Link, \
PhoneNumber, PostalAddress, Text, Blob, ByteString, GeoPt, IM... |
import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
from scipy.ndimage.filters import gaussian_filter1d
from numpy.random import poisson
def underdogwin(gpm1, gpm2, elapsed_time, thresh, total_time):
remaining_time = total_time - ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
"""
VirtualBox Validation Kit - Test that runs various benchmarks.
"""
__copyright__ = \
"""
Copyright (C) 2010-2014 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free softwa... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from jinja2.exceptions import UndefinedError
from ansible.errors import AnsibleFileNotFound, AnsibleLookupError, AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.module_utils.parsi... |
#!/usr/bin/env python
import sys
from distutils.core import setup
setup_args = {}
#############################################################################################
##### CEBALERT: copied from topographica; should be simplified
required = {'param':">=0.0.1",
'PIL':">=1.1.6"}
packages_to_ins... |
import functools
import inspect
import operator
from collections import deque
from . import invocation, signature, utils
from .mock_registry import mock_registry
__all__ = ['mock']
__tracebackhide__ = operator.methodcaller(
"errisinstance",
invocation.InvocationError
)
class _Dummy(object):
# We spell... |
#!/usr/bin/env mpipython.exe
import StGermain
StGermain.initialise()
# We have to init here because a default to the inventory in snac requires construction of StGermain things... the only way to
# fix this is to upgrade to pythia-0.8, which will mean citcom and exchanger needs to too.
from Snac.pyre.Application imp... |
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from time import sleep
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get("http://0... |
# -*- coding: utf-8 -*-
"""
ecg_streaming
-------------
Modified from biosppy.signals.ecg and biosppy.signals.tools
Generate tuples using ECG R-peak segmentation algorithm.
Following the approach by Christov
:copyright: (c) 2016 by IBM Corp.
:copyright: (c) 2015 by Instituto de Telecomun... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 10:39:14 2015
@author: karel
"""
import sys
import matplotlib
#matplotlib.use('pdf')
#matplotlib.use('Qt4Agg')
matplotlib.use('TkAgg')
import numpy as np
import os
import shutil
#from scipy.io import savemat
from sys import platform
import matplotlib.pyplot as plt
from... |
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
import matplotlib.pyplot as plt
import math
import scipy.signal
def diff(voltage):
d_voltage = voltage[0:-1] - voltage[1:]
return d_voltage
def signal_diff(voltages):
#Work with normalized voltages:
vmin ... |
def get_data(k):
k.dte.set_prefixes([u''])
def myNameAsked(c):
self_label = c.kernal.prolog_query_one('rdfsLabel(self, %s, L).' % c.lang)
if c.lang == 'de':
c.resp("Ich heiße %s" % self_label)
c.resp("Mein Name ist %s" % self_label)
else:
c.resp("I... |
__author__ = "Frederic F. MONFILS"
__version__ = "$Revision: $".split()[1]
__revision__ = __version__
# $Source: $
__date__ = "$Date: $"
__copyright__ = "Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS"
__license__ = "GPLv3"
__contact__ = "ffm at cetic.be"
import compiler
from core.metric import... |
# -*- coding: utf-8 -*-
# Weather Twitter Bot - AJBBB - 7/8/2015 v2.*
import urllib2
import json
from birdy.twitter import UserClient
import tweepy
#Twitter Keys
CONSUMER_KEY = "YOUR CONSUMER KEY HERE"
CONSUMER_SECRET = "YOUR CONSUMER SECRET HERE"
ACCESS_TOKEN = "YOUR ACCESS TOKEN HERE"
ACCESS_TOKEN_SECRET = "YOUR ... |
import discord
import asyncio
import html
import random
import time
from foobar import *
client = discord.Client()
user = discord.User()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async de... |
"""
mbed SDK
Copyright (c) 2011-2016 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 or agreed to in wr... |
#!/usr/bin/env python
# import system module
import sys
import os
from socket import *
import time
import select
# check the legitimacy of the running arguments
if len(sys.argv) != 5:
print("Wrong argument number")
exit()
# get all arguments
try:
serverIP = sys.argv[1]
except ValueError:
print("Oops! ... |
import os
from gabbi import driver
from cloudkitty.tests.gabbi import fixtures
from cloudkitty.tests.gabbi.rating.pyscripts import fixtures as py_fixtures
TESTS_DIR = 'gabbits'
def load_tests(loader, tests, pattern):
test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
return driver.build_tests(te... |
"""These decorators can be applied to your ``PistonAPI`` methods to control
how your method arguments are validated."""
import re
from functools import wraps
class ValidationException(Exception):
pass
from auth import BasicAuthorizer, OAuthAuthorizer
def validate_pattern(varname, pattern, required=True):
""... |
"""End-to-end test for the leader board example.
Code: beam/sdks/python/apache_beam/examples/complete/game/leader_board.py
Usage:
python setup.py nosetests --test-pipeline-options=" \
--runner=TestDataflowRunner \
--project=... \
--region=... \
--staging_location=gs://... \
--temp_loca... |
"""A Kegnet client that sends a fake flow."""
from pykeg.core import importhacks
import gflags
import math
import time
from pykeg.core import kb_app
from pykeg.core import kb_common
from pykeg.core import util
from pykeg.core.net import kegnet
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('ticks', 1000,
'Number o... |
# -*- coding: utf-8 -*-
"""
flask.logging
~~~~~~~~~~~~~
Implements the logging support for Flask.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from logging import getLogger, StreamHandler, Formatter, Logger, DEBU... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'OpenRemoteOntologyDialog.ui'
#
# by: pyside-uic 0.2.15 running on PySide 1.2.1
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_OpenRemoteOntologyDialog(object):
def setupUi(self, ... |
import unittest
import sys
import tutil
import webvulnscan.attacks.cookiescan
# A cookie is implicit cacheable, if
# 1. A cookie is set.
# 2. The Expire-Date is in the future
# 3. No Cache-Control is set.
def make_urlmap(headers):
headers['Content-Type'] = 'text/html; charset=utf-8'
return {
'/'... |
#!/usr/bin/env python3
"""
Gather data from given lib file. This data is then used to populate JSON file
that has delay numbers for some parameters related to F2A and A2F pins.
"""
import argparse
from collections import defaultdict
# =============================================================================
def ... |
from validator.decorator import version_range
from validator.constants import (FIREFOX_GUID, FENNEC_GUID,
THUNDERBIRD_GUID as TB_GUID, ANDROID_GUID)
# Compatibility app/version ranges:
def _build_definition(maj_version_num, firefox=True, fennec=True,
thunderbird... |
try:
import re
import sys
import socket
import struct
from lib.core.exceptions import CrowbarExceptions
except Exceptions, err:
from lib.core.exceptions import CrowbarExceptions
raise CrowbarExceptions(str(err))
class InvalidIPAddress(ValueError):
"""
The IP address given to ipadd... |
"""Api unit tests."""
__author__ = '<EMAIL> (Adam McGrath)'
import datetime
import os
import json
import mock
import unittest
import webtest
import base
import helpers
import admin
import models
class AdminTestCase(base.TestCase):
def setUp(self):
super(AdminTestCase, self).setUp()
self.testbed.init_da... |
# -*- coding: utf-8 -*-
#
# This module (which must have the name queryfunc.py) is responsible
# for converting incoming queries to a database query understood by
# this particular node's database schema.
#
# This module must contain a function setupResults, taking a sql object
# as its only argument.
#
# library impo... |
"""Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
"""
def sieve_of_eratosthenes(limit):
"""Find all prime numbers up to the given limit.
This is a lazy implementation of the sieve of Eratosthenes.
"""
# Initialize a l... |
from test_framework import TruthcoinTestFramework
from truthcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def get_sub_array_from_array(object_array, to_match):
'''
Finds and returns a sub array from an array of arrays.
to_match should be a unique idetifier of a sub... |
from optparse import make_option
from django.core.management.base import CommandError, BaseCommand
class Command(BaseCommand):
help = 'Register a question data type.'
option_list = BaseCommand.option_list + (
make_option('-t', '--title', action='store', type="string",
dest='title',
... |
import api
class Community():
# Community.Communities
def communities(self, duration=0, auth=True):
params = {'Duration': duration}
return api.call('Communities', params, auth)
# Community.CommunitySearch
def community_search(self, searchType, keyword, activeOnly=False, titleOnly=False... |
import itertools
import unittest
import numpy
from six import moves
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainer.utils import conv_nd
class TestAsTuple(unittest.TestCase):
def test_scalar(self):
actual = conv_nd.as_tuple(1, 3)
expec... |
from __future__ import print_function
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.layers import LSTM
from keras.optimizers import RMSprop
from keras.utils.data_utils import get_file
import numpy as np
import random
import sys
import h5py
from utils import *
import ... |
import os
import subprocess
import tempfile
import urllib
import click
import click_spinner
import cli_common.command
import cli_common.log
import cli_common.utils
import please_cli.config
import please_cli.utils
logger = cli_common.log.get_logger(__name__)
CMD_HELP = '''
Update Nix dependencies for a PROJECT.
\b
... |
from ctypes import c_int, c_char
from warnings import warn
import openmc.exceptions as exc
from . import _dll
def _error_handler(err, func, args):
"""Raise exception according to error code."""
# Get error code corresponding to global constant.
def errcode(s):
return c_int.in_dll(_dll, s).value
... |
"""
NamesOfGod
Copyright (C) 2016 Jose Miguel Garrido
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 option) any later version.
This program is distrib... |
from django.conf.urls import patterns
urlpatterns = patterns('components.rights.views',
(r'^$', 'ingest_rights_list'),
(r'add/$', 'ingest_rights_edit'),
(r'delete/(?P<id>\d+)/$', 'ingest_rights_delete'),
(r'grants/(?P<id>\d+)/delete/$', 'ingest_rights_grant_delete'),
(r'grants/(?P<id>\d+)/$', 'inge... |
from concurrent.futures import ThreadPoolExecutor
from client.model import Folder
class DropboxSendspaceSync(object):
def __init__(self, dropbox, sendspace):
self._dropbox = dropbox
self._sendspace = sendspace
self.errors = list()
self.logs = list()
self.futures = list()
... |
import random
import hashlib
from twisted.trial import unittest
from kademlia.node import Node, NodeHeap
from kademlia.tests.utils import mknode
class NodeTest(unittest.TestCase):
def test_longID(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
n = Node(rid)
self.assertEq... |
# -*- coding: utf-8 -*-
import 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 'Node.shot'
db.delete_column(u'h1ds_node', 'shot_id')
# Deleting field 'Node.paren... |
from weblate.trans.management.commands import WeblateCommand
from weblate.lang.models import Language
from weblate.trans.search import (
update_index, create_source_index, create_target_index
)
from optparse import make_option
class Command(WeblateCommand):
help = 'rebuilds index for fulltext search'
opti... |
import unittest
import struct
import sys
from test import test_support, string_tests
class StrTest(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUserStringTest,
string_tests.MixinStrUnicodeTest,
):
type2test = str
# We don't nee... |
from random import choice
from weboob.capabilities.torrent import MagnetOnly
from weboob.tools.compat import basestring
from weboob.tools.test import BackendTest
class PiratebayTest(BackendTest):
MODULE = 'piratebay'
def test_torrent(self):
# try something popular so we sometimes get a magnet-only t... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse
from django.utils.encoding import smart_str
from django.conf import settings
from django.contrib.auth.decorators import login_requi... |
"""
URL patterns for testing django-nova views.
"""
from django.conf.urls.defaults import *
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^projects/', include('django_nova.urls.project')),
url(r'^region/', include('django_nova.urls.region')),
url(r'^admin/projects/', include('d... |
#!/usr/bin/env python3
import pygame
# Each game controller axis returns a value in the closed interval [-1, 1]. We
# limit the number of decimal places we use with the PRECISION constant. This is
# done for a few reasons: 1) it makes the numbers more human-friendly (easier to
# read) and 2) it reduces the number of... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 16:03:40 2014
@author: luca
"""
from matplotlib.pyplot import ginput, connect, gcf, axvline, disconnect, draw
import numpy as np
from scipy.interpolate import UnivariateSpline
class Picker:
def __init__(self):
self.finished = False
self.picked = ... |
import logging, coloredlogs
from threading import Thread
from random import choice
from time import sleep
from modules.config import *
from modules.database import Database
from modules.api import API
database = Database(db_host, db_user, db_pass, db_name, db_autocommit)
database.database_connection()
class Raffle:
... |
#!/usr/bin/env python3
# use horizon based roll/pitch rates (and maybe motion based yaw
# rates.) Compare rates in camera space vs. imu space and try to find
# an optimal transform to minimize the idfference between them.
import argparse
import math
from matplotlib import pyplot as plt
import numpy as np
import os
... |
from sympy.core.basic import Basic
from sympy.vector.vector import Vector
from sympy.vector.coordsysrect import CoordSysCartesian
from sympy.vector.functions import _path
from sympy import Symbol
from sympy.core.cache import cacheit
class Point(Basic):
"""
Represents a point in 3-D space.
"""
def __n... |
#!/usr/bin/env python
# import modules
import pytest
import os
from rig_remote.bookmarks import Bookmarks
from rig_remote.disk_io import IO
from mock import MagicMock, Mock
import tkFileDialog
from rig_remote.exceptions import (
InvalidPathError,
Fo... |
#!/usr/bin/env python2
from glob import glob
from urllib import quote
import re
'''
Everything in the header string will be written out to the top of the README file
Github or Bitbucket support Markdown so you can format links, headers, bulleted lists
etc... within this string and it will be rendered on Github
'''
h... |
#!/usr/bin/python
import socket
HOST = '192.168.1.102'
PORT = 50007
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def... |
"""
:mod:`asymcrypto` --- SCION asymmetric crypto functions
=======================================================
"""
# stdlib
import base64
import os
# External
from nacl.exceptions import BadSignatureError
from nacl.public import Box, PrivateKey, PublicKey
from nacl.signing import SigningKey, VerifyKey
from nacl.u... |
from openerp import models, fields, api, _
from openerp.exceptions import Warning
class DonationDonation(models.Model):
_inherit = 'donation.donation'
mandate_id = fields.Many2one(
'account.banking.mandate', string='Mandate',
states={'done': [('readonly', True)]}, track_visibility='onchange',... |
import shutil
import stat
import tempfile
import time
import unittest
import obnamlib
class ClientMetadataTreeTests(unittest.TestCase):
def current_time(self):
return time.time() if self.now is None else self.now
def setUp(self):
self.now = None
self.tempdir = tempfile.mkdtemp()
... |
"""A scheduler that gets payoffs from a local simulation"""
import asyncio
import itertools
import json
import logging
import os
import shutil
import tempfile
import zipfile
from gameanalysis import paygame
from gameanalysis import rsgame
from gameanalysis import utils
from egta import profsched
class _ZipScheduler... |
"""Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to both as 'h'.
"""
import datetime
import xml.utils.iso8601 as iso8601
from docutils.core import publish_parts
from webhelpers.date import distance_of_time_in_words
from webhel... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Plugin for calling FHEM home automation
@author: Marco Schotthöfer
@requires: python-fhem (pip install fhem)
"""
#
# Imports
#
import logging # Global logger
from includes import globalVars # Global variables
# Helper function, uncomment to use
#from includes.helper i... |
from route53.exceptions import Route53Error
from route53.resource_record_set import AResourceRecordSet, AAAAResourceRecordSet, CNAMEResourceRecordSet, MXResourceRecordSet, NSResourceRecordSet, PTRResourceRecordSet, SOAResourceRecordSet, SPFResourceRecordSet, SRVResourceRecordSet, TXTResourceRecordSet
# Maps ResourceRe... |
import datetime
import json
import os
import re
import six
from kwrankingclient.openstack.common import timeutils
from kwrankingclient import exception
from kwrankingclient.openstack.common.gettextutils import _ # noqa
HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
... |
import serialWrapper
import packetBuilder
import packetParser
import socket
import Queue
import sys
import multiprocessing
from serial.tools import list_ports
commands_to_stm = packetBuilder.CommandsList()
current_module = sys.modules[__name__]
com_port = None
def create_connection_to_stm():
port_number = ge... |
# -*- coding: utf-8 -*-
import re
import subprocess
import sys
from .source import Source
from .configuration import Configuration
from itertools import chain
import io
import codecs
class PDFKit(object):
"""
Main class that does all generation routine.
:param url_or_file: str - either a URL, a path to a... |
import textwrap
from unittest import mock
import pytest
from . import entrypoint
def test_extract_url_should_return_service_with_is_entrypoint() -> None:
contents = textwrap.dedent("""\
services:
- name: b
- name: a
isEntrypoint: true
""")
expected = 'http://a.service-... |
from txamqp.client import Closed
from txamqp.queue import Empty
from txamqp.content import Content
from txamqp.testlib import TestBase, supportedBrokers, QPID, OPENAMQ
from twisted.internet.defer import inlineCallbacks
class ASaslPlainAuthenticationTest(TestBase):
"""Test for SASL PLAIN authentication Broker func... |
## @package domomaster
# Master daemon for D3 boxes.
#
# Developed by GreenLeaf.
from threading import Thread;
import MasterDaemon;
from MysqlHandler import *;
from Crypto.Cipher import AES;
import json;
from MasterSql import *;
import hashlib;
from Logger import *;
log_flag = False;
LOG_FILE = '/var/log/domoleaf/dom... |
import unittest
import logging
import os
from crashtec.cdbprocessor import callstackparser
#from crashtec.infrastructure.public import definitions as infradefs
_logger = logging.getLogger("cdb_processor")
class TestProblemStackParser(unittest.TestCase):
def test01_extrack_stack_lines(self):
RESULT_LINES ... |
"""
Caching framework.
This package defines set of cache backends that all conform to a simple API.
In a nutshell, a cache is a set of values -- which can be any object that
may be pickled -- identified by string keys. For the complete API, see
the abstract BaseCache class in django.core.cache.backends.base.
Client ... |
import itertools
import math
import sys
import matplotlib.pyplot as plt
import common.proto_utils as proto_utils
import modules.routing.proto.topo_graph_pb2 as topo_graph_pb2
import util
color_iter = itertools.cycle(
['navy', 'c', 'cornflowerblue', 'gold', 'darkorange'])
def calculate_s(px, py):
"""Calcula... |
# -*- coding: utf-8 -*-
try:
from oslo.config import cfg
except ImportError:
from oslo_config import cfg
import novaclient.exceptions as novaclientexceptions
from syseleven.cloudutilslibs.openstackclients import (get_heat_client,
get_neutron_client,
... |
import numpy as np
import math
# Constants for (heart) trackfile definition
tk_frameCol = 0
tk_labelledCol = 1
tk_presentCol = 2
tk_yposCol = 3
tk_xposCol = 4
tk_oriCol = 5
tk_viewCol = 6
tk_phasePointsCol = 7
tk_cardiacPhaseCol= 8
# Constants for substructure track file definition
stk_frameCol = 0
stk_labelledCol = ... |
"""
File Name: UnoPytorch/response_net.py
Author: Xiaotian Duan (xduan7)
Email: <EMAIL>
Date: 8/17/18
Python Version: 3.6.6
File Description:
"""
import torch
import torch.nn as nn
from networks.structures.residual_block import ResBlock
fr... |
# -*- coding: utf-8 -*-
RETURNABLES = {\
'NodeID':'vald',
'SourceID':'Source.id',
'SourceAuthorName':'Source.author',
'SourceCategory':'Source.category',
'SourcePageBegin':'Source.pages',
'SourcePageEnd':'Source.pages',
'SourceName':'Source.journal',
'SourceTitle':'Source.title',
'SourceURI':'Source.url',
'SourceVolum... |
import mock
import os
import uuid
import unittest
from cloudbaseinit.openstack.common import cfg
from cloudbaseinit.plugins.windows import userdatautils
from cloudbaseinit.tests.metadata import fake_json_response
CONF = cfg.CONF
class UserDataUtilsTest(unittest.TestCase):
def setUp(self):
self.fake_dat... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
K-means Clustering
=========================================================
The plots display firstly what a K-means algorithm would yield
using three clusters. It is then shown what the effect of a bad
initializa... |
# -*- coding: utf-8 -*-
"""
CPSC 599 module: klatt
Purpose
=======
Provides a convenient wrapper for writing waveform data.
Legal
=====
All code, unless otherwise indicated, is original, and subject to the
terms of the GPLv3, which is provided in COPYING.
(C) Neil Tallim, 2009
"""
import struct
import wave
cl... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
## Import common moduli
import sys, os.path
import numpy as np
from scipy.constants import c, hbar, pi
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
matplotlib.rc('text', usetex=True)
matplotlib.rc('font', size=16)
matplotlib.rc('text.latex'... |
import sys, os
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from nucleator import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print "Nucleator requires setuptools in order to build. " \
"Install it using your package manager (usually python-se... |
import os
from collections import deque
import torch
from torch.utils.data import Dataset
# ------------
# Data loading
# ------------
class CNNDMDataset(Dataset):
"""Abstracts the dataset used to train seq2seq models.
The class will process the documents that are located in the specified
folder. The ... |
from flask_appbuilder.security.views import UserDBModelView
from flask_babelpkg import lazy_gettext
class MyUserDBModelView(UserDBModelView):
"""
View that add DB specifics to User view.
Override to implement your own custom view.
Then override userdbmodelview property on SecurityManager
... |
#!/usr/bin/env python
"""
Copyright (C) 2015, Digium, Inc.
Ashley Sanders <<EMAIL>>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
"""
import sys
import logging
sys.path.append("lib/python")
sys.path.append("tests/rest_api/applications")
from stasisstatus.obs... |
import logging
import time
import os
import sys
import re
from autotest.client.shared import error
from autotest.client import utils
from autotest.client.shared.syncdata import SyncData
from virttest import data_dir, env_process, utils_test, aexpect
@error.context_aware
def run_floppy(test, params, env):
"""
... |
import re
class HtmlPunctuationMaker(object):
"""
Replace common punctuation marks with proper HTML representations.
--- — em dash
-- – en dash
"" ... "" “ ” opening and closing double quotes
' ... ' ‘ ’ opening and closing single quotes
... |
#!/usr/bin/env python
# encoding: utf-8
r"""
Compressible Euler flow in cylindrical symmetry
===============================================
Solve the Euler equations of compressible fluid dynamics in 2D r-z coordinates:
.. math::
\rho_t + (\rho u)_z + (\rho v)_r & = - \rho v / r \\
(\rho u)_t + (\rho u^2 + p... |
import multiprocessing
import os
try:
import sqlite3 # Not present on ChromeOS DUT.
except ImportError:
pass
import page_sets
from profile_creators import fast_navigation_profile_extender
class CookieProfileExtender(
fast_navigation_profile_extender.FastNavigationProfileExtender):
"""This extender fills ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.