content string |
|---|
import sys
import time
from array import *
from random import randint
MAX = 2**24 - 1
NO_OF_STATIONS = 2265 #max number of stations
no_of_connections = 178665 #no of input connections
class Connections:
def __init__(self,line):
parameters = line.split(' ');
self.train_no = parameters[0]
self.dept_stn = int(... |
# coding: utf-8
# v1.0.1
import tingbot
from tingbot import *
import urllib, json
from datetime import datetime
import time
state = {}
screenList = {
0: 'main'
}
currentScreen = 0
state['screen'] = screenList[currentScreen]
baseUrl = "http://" + tingbot.app.settings['IP'] + ":" + str(tingbot.app.settings['PORT'... |
"""
Decorators for views based on HTTP headers.
"""
from functools import wraps
from django.http import HttpResponseNotAllowed
from django.middleware.http import ConditionalGetMiddleware
from django.utils import timezone
from django.utils.cache import get_conditional_response
from django.utils.decorators import decor... |
# -*- encoding: utf-8 -*-
from django.shortcuts import render, get_object_or_404
from perfils.models import Perfil, Solicitud
from perfils.forms import formulariLogin, formulariModificar, formulariRegistrarse, formulariEditarContrasenya
from django.contrib import messages
from django.contrib.auth import authenticate, l... |
"""
Module to set up run time parameters for Clawpack -- classic code.
The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.
"""
import os
import numpy as np
#------------------------------
def setrun(claw_pkg='classic'):
#--------------------------... |
# -*- encoding: utf-8 -*-
"""Implements test function locking, using pytest_services file locking
Usage::
from robottelo.decorators.func_locker import (
locking_function,
lock_function,
)
# in many cases we have tests that need some test functions to run isolated
# from other py.tes... |
import sys
from behave import __version__
from behave.configuration import Configuration, ConfigError
from behave.formatter.ansi_escapes import escapes
from behave.i18n import languages
from behave.formatter import formatters
from behave.runner import Runner
from behave.parser import ParserError
TAG_HELP = """
Scenar... |
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class BytecoinRPC:
OBJID = 1
def __init__(self, host, port, username, passw... |
from couchpotato.core.downloaders.base import Downloader, ReleaseDownloadList
from couchpotato.core.helpers.encoding import tryUrlencode, ss, sp
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import time... |
import discord
from discord.voice_client import StreamPlayer
from roboto.commands import dispatcher, TaskState, Commands
class ServerState(object):
def __init__(self, server_id):
from roboto import text
self.server_id = server_id
self._voice_channel_id = None
self._media_player = ... |
from __future__ import absolute_import
import functools
from ensconce import exc
from ensconce.dao import access
from ensconce.webapp.util import operator_info
# Access Levels
# 1 - User read 00000000 00000001 2^0
# 2 - User write 00000000 00000010 2^1
# 4 - Group read ... |
import curses as cs
from rgkit.settings import settings
class RGCurses(object):
def __init__(self, game_inst, names):
self._game = game_inst
self._names = names
self._turn = 0
self._done = False
self._paused = False
self._selected = [settings.board_size // 2, settin... |
from six.moves import xrange
from flatland import (
Element,
Skip,
SkipAll,
SkipAllFalse,
Unevaluated,
)
from tests._util import requires_unicode_coercion
import pytest
def test_cloning():
new_element = Element.named(u'x')
assert isinstance(new_element, type)
assert new_element.__mo... |
from __future__ import unicode_literals
import frappe
import os, json
from frappe import _
from frappe.modules import scrub, get_module_path
from frappe.utils import flt, cint, get_html_format
import frappe.widgets.reportview
def get_report_doc(report_name):
doc = frappe.get_doc("Report", report_name)
if not doc.h... |
#!/usr/bin/env python
from pwn import *
binary = './ropasaurusrex-85a84f36f81e11f720b1cf5ea0d1fb0d5a603c0d'
# Remote version
l = listen(0)
l.spawn_process([binary])
r = remote('localhost', l.lport)
# Uncomment for local version
# r = process(binary)
#
# If we run with a cyclic pattern, we end up with the following ... |
"""Definition of Beam TFX runner."""
import datetime
from typing import Optional
from absl import logging
from tfx.dsl.components.base import base_component
from tfx.orchestration import data_types
from tfx.orchestration import metadata
from tfx.orchestration import pipeline
from tfx.orchestration import tfx_runner
... |
"""
Testsuite for Topology PyNEST Interface.
This testsuite mainly tests the PyNEST interface to the
topology module, not the underlying topology module functions.
It also tests the visualization functions that are available
in PyNEST only.
"""
import unittest
from nest.topology.tests import test_basics
from nest.t... |
"""
Django settings for ControlPrestamo project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
i... |
#General Convenience Methods
def namePuzzle(puzzle):
print("\n"+ "Starting puzzle #" + puzzle + "...")
def solvePuzzle(puzzle):
print("\n"+ "Solved puzzle #" + puzzle)
#1. Print int array, neg, then zero, then positive
namePuzzle('1')
numbers = [0,1,2,-1,0,3,0, -2]
numbers.sort()
for num in numbers:
prin... |
r"""Tests for holparam_predictor.
This test assumes an embedding size of 4.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import flags
import numpy as np
import tensorflow as tf
from deepmath.deephol import holparam_predictor
fro... |
import pytest
import dgtal
@pytest.mark.parametrize("Type", [("DigitalSetZ2i"), ("DigitalSetZ3i")])
def test_constructor_with_domain(Type):
kernel_submodule = getattr(dgtal, "kernel")
DigitalSet = getattr(kernel_submodule, Type)
Domain = DigitalSet.TDomain
Point = DigitalSet.TPoint
# Construct Doma... |
# -*- coding: utf-8 -*-
from django.views.generic import TemplateView, DetailView, ListView, FormView
from django.core.urlresolvers import reverse_lazy
__author__ = 'AlexStarov'
class OpinionAddView(FormView):
template_name = 'opinion_add.jinja2'
from applications.opinion.forms import OpinionAddForm
form... |
import dbus, gtk
from xl import event, player, settings
SERVICES = [
dict( # GNOME
bus_name='org.gnome.ScreenSaver',
path='/org/gnome/ScreenSaver',
dbus_interface='org.gnome.ScreenSaver',
),
dict( # KDE
bus_name='org.freedesktop.ScreenSaver',
path='/',
dbus_i... |
# -*- coding: utf-8 -*-
""" Project
@author: Michael Howden (<EMAIL>)
@date-created: 2010-08-25
Project Management
"""
prefix = request.controller
resourcename = request.function
response.menu_options = [
[T("Home"), False, URL(r=request, f="index")],
[T("Gap Analysis"), False, U... |
from datetime import datetime as dt, timedelta as dtd
import numpy as np
import pandas as pd
import pytest
from pandas.util.testing import assert_frame_equal
from arctic.date import DateRange, mktz
from arctic.exceptions import NoDataFoundException, LibraryNotFoundException, OverlappingDataException
from arctic.ticks... |
import os
import re
import tempfile
from json import JSONEncoder
from colorclass.color import Color
from dexsim import get_value
from dexsim.plugin import Plugin
PLUGIN_CLASS_NAME = "f79c49"
# 片段1
# base64解密
# new-instance v0, Ljava/lang/String;
# const-string v1, "EZ5LaexoU7OiZuRcijBTc0DJTu7nFWcNOBHfVE0CMIo="
# con... |
from app import app
from flask import Flask
from flask import g, Response, request
import json
import MySQLdb
import logging
import config
app.config['APPLICATION_ROOT'] = '/api/v1'
@app.before_request
def db_connect():
g.conn = MySQLdb.connect(host=config.host,
user=config.user,
... |
import logging
from celery.task import task, periodic_task
from celery.schedules import timedelta
from videos.models import VideoUrl, VIDEO_TYPE_YOUTUBE
from videos.types import UPDATE_VERSION_ACTION
from auth.models import CustomUser as User
from models import ThirdPartyAccount
from remover import Remover
from utils.m... |
import struct
import ParticipantInfo
#Model class for Telemetry Packages
class TelemetryData:
def __init__(self, package):
self.build_version = struct.unpack('H', package[0:2])[0]
self.package_type = struct.unpack('B', package[2:3])[0] & 0x03
self.sequence_number = (struct.unpack('B', packa... |
import os
import subprocess32 as subprocess
import unittest
import GafferTest
class PythonApplicationTest( GafferTest.TestCase ) :
def testVariableScope( self ) :
subprocess.check_call( [ "gaffer", "python", os.path.dirname( __file__ ) + "/pythonScripts/variableScope.py" ] )
def testErrorReturnStatus( self ) :... |
from bisect import bisect
import gtk
import gobject
from gtk.gdk import Rectangle, CONTROL_MASK, SHIFT_MASK
from gtk import keysyms
from uxie.utils import send_focus_change
icon_sizes = None
class DrawItem(object):
__slots__ = ['ix', 'iy', 'iwidth', 'iheight',
'tx', 'ty', 'twidth', 'theight', 'width', '... |
'''
Created on Oct 17, 2010
@author: Mark V Systems Limited
(c) Copyright 2010 Mark V Systems Limited, All rights reserved.
'''
import os, sys, traceback, re
from arelle import (ModelXbrl, XmlUtil, ModelVersReport, XbrlConst, ModelDocument,
ValidateXbrl, ValidateFormula)
from arelle.FileSource import o... |
__author__ = 'vitorio'
from bs4 import BeautifulSoup
import argparse
parser = argparse.ArgumentParser(description='Remove empty text-related markup from an hOCR file ("ocr_line" with no content, "ocr_carea" with no "ocr_line", "ocr_page" with no "ocr_line" or floats)')
parser.add_argument('hocrfile', help='The hOCR f... |
from ansible.module_utils.netcfg import NetworkConfig, dumps
from ansible.module_utils.network import NetworkModule
import ansible.module_utils.dellos9
def get_config(module):
config = module.params['config'] or dict()
if not config and not module.params['force']:
config = module.config.get_config()
... |
import pickle
phone_book = [
{"name": "Petr", "surname": "Petrov", "age": 50, "phone_number":"+380501234567", "skype": ""},
{"name": "Ivan", "surname": "Ivanov", "age": 15, "phone_number":"+380507654321", "skype": ""},
{"name": "Victor", "surname": "Victorov", "age": 24, "phone_number":"+380931234567", "sk... |
"""
A simple model that demonstrates discrete-time system simulation using an
IIR filter.
@author: Allan McInnes
"""
from scipysim.actors import CompositeActor, MakeChans, Event
from scipysim.actors.signal import Split, Delay
from scipysim.actors.math.trig import DTSinGenerator
from scipysim.actors.math import Summer
... |
# test with game/manage.py test
import unittest
from src.utils import utils
class TestIsIter(unittest.TestCase):
def test_is_iter(self):
self.assertEqual(True, utils.is_iter([1,2,3,4]))
self.assertEqual(False, utils.is_iter("This is not an iterable"))
class TestCrop(unittest.TestCase):
def te... |
"""
External minimize: using lmfit minimizers for BornAgain fits.
Fit progress is plotted using lmfit iteration calbback function.
"""
import numpy as np
from matplotlib import pyplot as plt
import bornagain as ba
from bornagain import deg, angstrom, nm
import lmfit
def get_sample(params):
"""
Returns a sampl... |
import os
import shutil
import tarfile
import tempfile
import OvfFile
import OvfLibvirt
import OvfReferencedFile
import OvfManifest
FORMAT_DIR = "Dir"
FORMAT_TAR = "Tar"
class OvfSet(object):
"""
This is the base OvfSet class. It represents an OVF Set, either as a tar
archive or as a directory layout
... |
import sys
import inspect
import os
import glob
import re
import subprocess
try:
from play.utils import *
except:
pass
MODULE = 'migrate'
COMMANDS = ['migrate','migrate:help','migrate:init','migrate:up','migrate:version','migrate:drop-rebuild','migrate:create','migrate:drop']
app = None
# Migrate - databas... |
from panda3d.core import *
from panda3d.direct import *
from direct.interval.IntervalGlobal import *
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedSmoothNode
from toontown.toonbase import ToontownGlobals
from otp.otpbase import OTPGlobals
from direct.fsm import FSM
from di... |
# coding=utf-8
"""Provider code for SDBits."""
from __future__ import unicode_literals
import logging
import re
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.indexers.utils import mappings
from medusa.logger.adapters.sty... |
#
# misc.py
#
# meant to be imported as: import misc as hlp
#
# Created by Florian Hoppe on 06.11.2013.
#
from HTMLParser import HTMLParser
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame, Series
import pandas as pd
class _MLStripper(HTMLParser):
def __init__(self):
... |
import csv
import os
from itertools import zip_longest
import pandas as pd
from graphysio import writedata
from graphysio.dialogs import DlgPeriodExport, askDirPath, askSaveFilePath
from graphysio.utils import sanitize_filename
file_filters = ';;'.join(
[f'{ext.upper()} files (*.{ext})' for ext in writedata.curv... |
import argparse
import datetime
import common
parser = argparse.ArgumentParser()
parser.add_argument('-p',
'--project-name',
required=True,
dest='project_name',
help='The LP project name.')
args = parser.parse_args()
PROJECT_NAME = args... |
#!/bin/python
import os, time
#############################################
# #
# this file is design to reproduce the #
# test results proveide in #
# #
# when ran on a single CPU, #
# this should take about a week #
# #
#############################################
def mak... |
import pytest
from datadog_checks.dev.testing import requires_py3
from ..utils import get_check
pytestmark = [
requires_py3,
pytest.mark.openmetrics,
pytest.mark.openmetrics_transformers,
pytest.mark.openmetrics_transformers_counter_gauge,
]
def test(aggregator, dd_run_check, mock_http_response):
... |
"""Tests for builtin_functions module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.contrib.autograph.converters import builtin_functions
from tensorflow.contrib.autograph.core import converter_testing
from tensorflow.pytho... |
import brooks.communication
from brooks.state import State
def initial():
return State(
step_duration_days=1,
num_function_points_requirements=500,
num_function_points_developed=0,
num_new_personnel=20,
num_experienced_personnel=0,
personnel_allocation_rate=0,
... |
# -*- coding: utf-8 -*-
"""
oss2.utils
----------
工具函数模块。
"""
from email.utils import formatdate
import os.path
import mimetypes
import socket
import hashlib
import base64
import threading
import calendar
import datetime
import time
import errno
from .compat import to_string, to_bytes
from .exceptions import Clien... |
__author__ = "auxiliary-character"
import csv
import wpilib
from wpilib.command import Command
from wpilib.timer import Timer
from utilities.settings import Settings
class RecordMacro(Command):
"""This records robot movements and writes them to a .csv file."""
def __init__(self, robot, name):
super... |
import numpy as np
from Orange.regression import Learner
from Orange.classification.simple_random_forest import SimpleRandomForestModel as SRFM
__all__ = ['SimpleRandomForestLearner']
class SimpleRandomForestLearner(Learner):
"""
A random forest regressor, optimized for speed. Trees in the forest
are co... |
# -*- coding: utf-8 -*-
## Generic packages
from fabric.api import *
from fabtools.vagrant import vagrant
## Librairies
from fabtools import service
from fabtools import deb
from fabtools import files
from fabtools import utils
from fabtools import require
from fabtools import cron
from datetime import datetime
from ... |
'''
Exact density fitting with Gaussian and planewaves
Ref:
J. Chem. Phys. 147, 164119 (2017)
'''
import copy
import numpy
from pyscf.lib import logger
from pyscf.pbc.df import df_jk
from pyscf.pbc.df import aft_jk
#
# Divide the Coulomb potential to two parts. Computing short range part in
# real space, long range ... |
"""Session class module"""
import requests
from authentise_services import errors
from authentise_services.config import Config
class Session(object): # pylint: disable=too-few-public-methods
"""This class is for creating and holding onto user sessions for the model warehouse service"""
def __init__(self, ... |
'''
test_Connectable.py
Tests the functionality of thedom/Connectable.py
Copyright (C) 2015 Timothy Edmund Crosley
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 ve... |
from msrest.service_client import ServiceClient
from msrest import Configuration, Serializer, Deserializer
from .version import VERSION
from msrest.pipeline import ClientRawResponse
from . import models
class AutoRestReportServiceConfiguration(Configuration):
"""Configuration for AutoRestReportService
Note th... |
'''
@author: <EMAIL>
'''
from MatrixArithmetic import *
import unittest
class TestMultiply(unittest.TestCase):
def setUp(self):
self.A = [
[1,1,0,0]
]
self.mA = Matrix(self.A)
self.B = [
[1,0,0,0,1,1,0],
... |
from dfa.common import dfa_logger as logging
from dfa.server.services.firewall.native import fw_constants as fw_const
from dfa.server.services.firewall.native.drivers import dev_mgr_plug
LOG = logging.getLogger(__name__)
# Not sure of the exact name. But, this implements a case when all requests
# goto first device ... |
import pandas as pd
import data
import dtools
from pybrain.datasets import SupervisedDataSet
from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers import RPropMinusTrainer
from pybrain.structure import RecurrentNetwork, FullConnection
from pybrain.structure.modules ... |
from __future__ import print_function
import os
import warnings
class Odeoptions():
"""
Class of options for evolution solvers such as :func:`qutip.mesolve` and
:func:`qutip.mcsolve`. Options can be specified either as arguments to the
constructor::
opts = Odeoptions(gui=False, order=10, ...)... |
""" utility functionality for molecular similarity
includes a command line app for screening databases
Sample Usage:
python MolSimilarity.py -d data.gdb -t daylight_sig --idName="Mol_ID" \
--topN=100 --smiles='c1(C=O)ccc(Oc2ccccc2)cc1' --smilesTable=raw_dop_data \
--smilesName="structure" -o results.... |
"""RPC client tools"""
from __future__ import absolute_import
import os
import socket
import struct
import time
from . import base
from ..contrib import util
from .._ffi.base import TVMError
from .._ffi import function as function
from .._ffi import ndarray as nd
from ..module import load as _load_module
class RPCS... |
import re
import sys
from setuptools import setup
# Get version without importing, which avoids dependency issues
def get_version():
with open('serpextract/__init__.py') as version_file:
return re.search(r"""__version__\s+=\s+(['"])(?P<version>.+?)\1""",
version_file.read()).group(... |
"""Delete cluster command."""
from googlecloudsdk.api_lib.dataproc import util
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
class Delete(base.Command):
"""Delete a cluster."""
detail... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hs_modelinstance', '0006_auto_20151216_1511'),
('hs_core', '0026_merge'),
('hs_modflow_modelinstance', '0001_initial'),
]... |
import sys
import subprocess
from SALib.test_functions import Ishigami
import numpy as np
import re
salib_cli = "./src/SALib/scripts/salib.py"
ishigami_fp = "./src/SALib/test_functions/params/Ishigami.txt"
if sys.version_info[0] == 2:
subprocess.run = subprocess.call
def test_delta():
cmd = "python {cli} sa... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
import asyncio
import logging
import os
import re
import tarfile
from datetime import datetime
from os.path import exists, join
from shlex import split
from pypi2deb.decorators import cache
from dhpython.pydist import load, safe_name
FILENAME_RE = re.compile(r'''
(?:.*/)?
(?P<name>[a-zA-Z-].*)
[-_]
(?... |
from httplib2 import Http as HttpBase
from socket import gethostbyname
from urlparse import urlparse
import logging
log = logging.getLogger(__name__)
class ForbiddenHost(Exception):
"""
raised when e.g. trying to fetch a resource from a forbidden host
"""
pass
# XXX this should be renamed as it has a... |
#!/usr/bin/env python
from setuptools import setup
import sys
version = "0.3.0"
classifiers = [
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Progr... |
# encoding: 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):
# Adding model 'ListPattern'
db.create_table('augment_listpattern', (
('id', self.gf('django.d... |
version_info = (0, 15, 1, 'final', 0)
if version_info[3] == 'final':
if version_info[2] == 0:
version_string = '%d.%d' % version_info[:2]
else:
version_string = '%d.%d.%d' % version_info[:3]
else:
version_string = '%d.%d.%d%s%d' % version_info
__version__ = version_string
api_versions = ["... |
"""
This file is part of checkmate, a meta code checker written in Python.
Copyright (C) 2015 Andreas Dewes, QuantifiedCode UG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3... |
from collections import OrderedDict
from typing import Dict, Type
from .base import CloudRedisTransport
from .grpc import CloudRedisGrpcTransport
from .grpc_asyncio import CloudRedisGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTranspor... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('announcements', '0006_merge')]
operations = [
migrations.CreateModel(
nam... |
#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Herald XMPP transport directory
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 1.0.1
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
... |
"""All pytest-django fixtures"""
from __future__ import with_statement
import os
import warnings
import pytest
from . import live_server_helper
from .db_reuse import (monkey_patch_creation_for_db_reuse,
monkey_patch_creation_for_db_suffix)
from .django_compat import is_django_unittest
from .l... |
# pylint: disable=invalid-name
"""
File Access Handler Module
--------------------------
This module provides file access handlers.
"""
from __future__ import absolute_import
from bacpypes.errors import ExecutionError
from bacpypes.apdu import AtomicReadFileACK, AtomicWriteFileACK, \
AtomicReadFileACKAccessMet... |
"""
components/tools/OmeroPy/src/omero/util/imageUitl.py
-----------------------------------------------------------------------------
Copyright (C) 2006-2009 University of Dundee. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General P... |
from tempest.api.database import base
from tempest.lib import exceptions as lib_exc
from tempest import test
class DatabaseFlavorsNegativeTest(base.BaseDatabaseTest):
@classmethod
def setup_clients(cls):
super(DatabaseFlavorsNegativeTest, cls).setup_clients()
cls.client = cls.database_flavors... |
"""Base configuration of Scenario Analysis.
@author : Liangjun Zhu, Huiran Gao
@changelog:
- 16-12-30 - hr - initial implementation.
- 17-08-18 - lj - reorganize as basic class.
- 18-02-09 - lj - compatible with Python3.
- 18-10-29 - lj - Redesign the code structure.
"""
from __future__ ... |
__all__ = [
'CVSRepository',
'login',
'get_sticky_tag',
]
__metaclass__ = type
import sys
import os
try:
import hashlib
except ImportError:
import md5 as hashlib
import git
from jhbuild.errors import BuildStateError, CommandError
from jhbuild.versioncontrol import Repository, Branch, register... |
from __future__ import print_function
red = bold = yellow = lambda x: x
class ParseItem:
def __init__(self, start, end, symbole):
self.start = start
self.end = end
self.symbole = symbole
def __cmp__(self, o):
if self.start != o.start:
return 1
if self.en... |
# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil import parser, rrule
from dateutil.relativedelta import relativedelta
from textblob.packages import nltk
days = "(mon|tue|wed|thu|fri|sat|sun|weekday|wday)"
months = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"
dmy = "(year|day|week|month)"
rel... |
"""Processors for processing and converting spider and queue items."""
from .processor import Processor
from .text import TextProcessor
from .html import HTMLProcessor
from .zip import ZipProcessor
from .ocr import OCRProcessor
from .pdf import PDFProcessor
from .csv_processor import CSVProcessor
from .libreoffice impo... |
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.md') as fh:
long_description = fh.read()
setup(
name='serpens',
version='0.0.1',
author='Konstantin Malanchev',
author_email='<EMAIL>',
description='Stellar snakes',
long_description=long_description,
... |
import pytest
from admin.brands import views
from django.test import RequestFactory
from django.core.exceptions import PermissionDenied
from osf.models import Brand
from django.contrib.auth.models import Permission
from osf_tests.factories import BrandFactory, AuthUserFactory
from admin_tests.utilities import setup... |
"""
EIGRP Scapy Extension
~~~~~~~~~~~~~~~~~~~~~
:version: 2009-08-13
:copyright: 2009 by Jochen Bartl
:e-mail: <EMAIL> / <EMAIL>
:license: GPL v2
:TODO
- Replace TLV code with a more generic solution
* http://trac.secdev.org/scapy/ticket/90
- Write function for calc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: hed.py
import cv2
import tensorflow as tf
import numpy as np
import argparse
from six.moves import zip
import os
from tensorpack import *
from tensorpack.dataflow import dataset
from tensorpack.utils.gpu import get_num_gpu
from tensorpack.tfutils import optimizer... |
# -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.configure.settings import TimeProfileEditView
from cfme.utils.update import update
pytestmark = [pytest.mark.tier(3),
test_requirements.settings]
@pytest.mark.sauce
def test_time_profile_crud(applian... |
# -*- coding: utf-8 -*-
"""Handle settings for HugoPhotoSwipe
HugoPhotoSwipe uses a settings file for the configuration set by the user. This
configuration is loaded/initialized here as a ``settings`` object and is used
throughout the program.
Flags to the ``hps`` executable are saved as settings as well, but are... |
from sympy.core import (pi, oo, symbols, Rational, Integer,
GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq)
from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
gamma, sign)
from sympy.sets import Range
from sympy.logic import ITE
from symp... |
""" plots of spectra around the H-alpha line for 1,000 LAMOST sub-giant stars
that fit Andy Casey's criteria """
from TheCannon.lamost import load_spectra
import sys
import pyfits
from plot_residual import plot
from residuals import load_model
sys.path.append("/Users/annaho/Github/Spectra")
from normalize import norma... |
from sqlalchemy import MetaData, Table
from migrate import ForeignKeyConstraint
from nova import log as logging
meta = MetaData()
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine;
# bind migrate_engine to your metadata
meta.bind = ... |
"""Affinity Propagation clustering algorithm."""
# Gael Varoquaux <EMAIL>
# License: BSD 3 clause
import numpy as np
from ..base import BaseEstimator, ClusterMixin
from ..metrics import euclidean_distances
from ..metrics import pairwise_distances_argmin
from ..utils import as_float_array, check_array
from ..... |
__author__ = 'fermin'
import subprocess
from lxml import etree
p = subprocess.Popen(['./query-van.sh'], shell=False, stdout=subprocess.PIPE)
output = p.stdout.read()
doc = etree.fromstring(output)
van_positions = {}
for ce in doc.findall('.//contextElement'):
id = ce.find('.//id').text
for ca in ce.findall(... |
import string
from fractions import gcd
alphabet = ','.join(string.ascii_uppercase).split(',')
probabilities = {'A':0.08167,
'B': 0.01492,
'C': 0.02782,
'D': 0.04253,
'E': 0.12702,
'F': 0.02228,
'G': 0.02015,
'H': 0.06094,
'I': 0.06966,
'J': 0.00153,
'K': 0.00772,
'L': 0.04025,
'M': 0.02406,
'N': 0.06... |
"""Base class for fusion's REST calls
https://bigml.com/api/fusions
"""
try:
import simplejson as json
except ImportError:
import json
from bigml.api_handlers.resourcehandler import ResourceHandlerMixin
from bigml.api_handlers.resourcehandler import check_resource_type, \
resource_is_ready, get_fusi... |
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import time
from datetime import timedelta
import math
import prettytensor as pt
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/MNIST/',one_hot=True)
data.test.cls = np.argmax(data.test.labels... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.