content stringlengths 4 20k |
|---|
import os
import base64
import urlparse
import httplib
import json
from urllib import urlencode
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
client_id = os.environ["OAUTH_CLIENT_ID"]
client_secret = os.environ["OAUTH_CLIENT_SECRET"]
server_ip = os.environ["OAUTH_TOKEN_SERVER_IPV4"]
se... |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_10/models/cashbotHQ/ZONE11a',
'wantDoors': 1},
1001: {'type... |
class Licenses:
"""
https://www.vertica.com/docs/9.2.x/HTML/Content/Authoring/SQLReferenceManual/SystemTables/CATALOG/LICENSES.htm
"""
name = 'licenses'
fields = ('end_date', 'licensetype', 'node_restriction')
query = 'SELECT {} FROM v_catalog.{}'.format(', '.join(fields), name)
class License... |
# -*- coding: utf-8 -*-
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few yea... |
#!/usr/bin/env python
"""
@package mi.dataset.driver.flort_kn.auv
@file mi/dataset/driver/dosta_ln/auv/flort_kn_auv_telemetered_driver.py
@author Jeff Roy
@brief Driver for the flort_kn_auv instrument
Release notes:
Initial Release
"""
from mi.dataset.dataset_driver import SimpleDatasetDriver
from mi.dataset.parser... |
import random
import string
MIN_TAG_LEN = 1
MAX_TAG_LEN = 4
MIN_TEXT_LEN = 0
MAX_TEXT_LEN = 20
TAGS = 20
AUTO_TESTS = 50
def rand_text_gen(min_len, max_len, with_br_or_hr):
text=""
if (with_br_or_hr):
for i in range (random.randint(min_len, max_len)):
text+=random.choice(string.ascii_upper... |
from nltk.corpus import sentiwordnet as swn
from collections import defaultdict
import numpy as np
def get_sentiment_score(ls):
'''
input type sentence
this method estimate a score for the sentence based on the swn model
'''
from nltk.tokenize import word_tokenize
import re
word_list = wor... |
# coding: utf8
from django.core.management.base import BaseCommand, CommandError
from player.models import *
import yaml,sys,urllib.parse
class Command(BaseCommand):
help = "Load the database"
def add_arguments(self,parser):
parser.add_argument('filename',nargs='+',type=str)
def handle(self,**option):
albums... |
# -*- coding: utf-8 -*-
import re
import sublime
import sublime_plugin
def selections(view, default_to_all=True):
regions = [r for r in view.sel() if not r.empty()]
if not regions and default_to_all:
regions = [sublime.Region(0, view.size())]
return regions
class TrimmerCommand(sublime_plugin.T... |
"""
"""
__revision__ = "$Id$"
from invenio.bibfield_jsonreader import JsonReader
from invenio.bibfield_utils import CoolDict, CoolList
class MarcReader(JsonReader):
"""
Reader class that understands MARC21 as base format
"""
@staticmethod
def split_blob(blob, schema):
"""
Spli... |
from scapy.all import *
from veripy.assertions import *
from veripy.models import ComplianceTestCase
class RbitChangeHelper(ComplianceTestCase):
disabled_nd = True
disabled_ra = True
def set_up(self):
raise Exception("override #set_up to define #p")
def run(self):
self.router(1).sen... |
"""Comment utility functions."""
from flask import request
from invenio.modules.comments.models import CmtRECORDCOMMENT
def comments_nb_counts():
"""Get number of comments for the record `recid`."""
recid = request.view_args.get('recid')
if recid is None:
return
elif recid == 0:
ret... |
from numpy import *
import operator
def createDataset():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
def classify0(inx, dataset, labels, k):
datasetSize = dataset.shape[0]
diffmat = tile(inx, (datasetSize, 1)) - dataset
diffsq = diffmat **... |
import matplotlib
matplotlib.use('Agg')
import numpy as np
import netCDF4
from datetime import datetime
import pyroms
import pyroms_toolbox
import sys
def create_HYCOM_file(name, time, lon, lat, z, var):
print 'Write with file %s' %name
#create netCDF file
nc = netCDF4.Dataset(name, 'w', format='NETCD... |
import inspect
import os
import re
from setuptools import setup
INSTALL_REQUIRES = [
'obspy>=1.1.0',
# pyqt can not be declared as a dependency cleanly it seems, see
# http://stackoverflow.com/questions/4628519/
# 'PyQt5',
'numpy',
'scipy',
'matplotlib',
'requests',
]
ENTRY_POINTS =... |
#!/usr/bin/env python2
from __future__ import print_function
import datetime
import re
import sys
import textwrap
from collections import defaultdict
import click
import git
import github
import tabulate
from cfme.utils.conf import docker
LINE_FMT = "{pr:<{pr_len}} | {label:<{label_len}} | "
def clean_commit(comm... |
"""Performs XML-to-YAML translation.
TranslateXmlToYaml(): performs xml-to-yaml translation with
string inputs and outputs
AppYamlTranslator: Class that facilitates xml-to-yaml translation
"""
import os
import re
from google.appengine.tools import app_engine_web_xml_parser as aewxp
from google.appengine.tools ... |
{
'bsls_atomic': [
{'case': 7, 'host_type': 'VM', 'policy': 'skip'},
{'case': 8, 'host_type': 'VM', 'policy': 'skip'},
],
'bslstl_map': [
{'case': 8, 'host_type': 'VM', 'policy': 'skip'},
],
'bsls_stopwatch': [
{'case': 6, 'host_type': 'VM', 'policy': 'skip'}
],
}... |
import networkx as nx
from .s_c_c import filter_big_scc
from .s_c_c import get_big_sccs
import os.path
def remove_cycle_edges_by_agony_iterately(sccs, edges_score, edges_to_be_removed):
while True:
graph = sccs.pop()
pair_max_agony = None
max_agony = -1
for pair in graph.edges():
... |
"""
Copyright 2019 Glen Harmon
POETIC-FORM Object Description
https://www.ripe.net/manage-ips-and-asns/db/support/documentation/ripe-database-documentation/rpsl-object-types/4-3-descriptions-of-secondary-objects/4-3-8-description-of-the-poetic-form-object
"""
from .rpsl import Rpsl
class PoeticForm(Rpsl):
def... |
from __future__ import print_function
import gdb
class sd_dump_hashmaps(gdb.Command):
"dump systemd's hashmaps"
def __init__(self):
super(sd_dump_hashmaps, self).__init__("sd_dump_hashmaps", gdb.COMMAND_DATA, gdb.COMPLETE_NONE)
def invoke(self, arg, from_tty):
... |
import os.path
import subprocess
import logging
logger = logging.getLogger()
import collections
import vcf as pyvcf
class Vcf(object):
def __init__(self, filename, build=True):
# Determine if the input file was compressed by bgzip and has a tabix
# index
ftest = subprocess.check_output(["... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.mlnxos import mlnxos_mlag_vip
from units.modules.utils import set_module_args
from .mlnxos_module import TestMlnxosModule, load_fixture
class TestMlnxosMlag... |
#!/usr/bin/env python
import base
import vault
import requests
import json
import sys
import re
from termcolor import colored
ENABLED = True
class style:
BOLD = '\033[1m'
END = '\033[0m'
def colorize(string):
colourFormat = '\033[{0}m'
colourStr = colourFormat.format(32)
resetStr = colourForma... |
from enum import Enum
class StatusWorker(Enum): # pylint: disable=too-few-public-methods
"""Statuses a RedisWorker can be in."""
dead_parrot = 0 # canary value
scheduled = 1
booting = 2
ready = 3
running = 4
ran = 5
failed = 6
committed = 7
class StatusMaster(Enum): # pylint: ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os.path
from flask import Blueprint, render_template
from browsepy.file import File
mimetypes = {
'mp3': 'audio/mpeg',
'ogg': 'audio/ogg',
'wav': 'audio/wav'
}
__basedir__ = os.path.dirname(os.path.abspath(__file__))
player = Blueprint(
'depreca... |
"""
IP protocol definitions.
"""
import binascii
import ctypes
import struct
class IP(ctypes.Structure):
"""
Represents an IP packet.
"""
_fields_ = [('v', ctypes.c_ushort), # version
('hl', ctypes.c_ushort), # internet header length
('tos', ctypes.c_ub... |
from openerp.tests.common import TransactionCase
from openerp.modules.module import get_module_resource
class TestStatementFile(TransactionCase):
"""Run test to import camt.053 import."""
def test_statement_import(self):
"""Test correct creation of single statement."""
import_model = self.reg... |
# Authors: Mainak Jas <<EMAIL>>
# Tom Dupre La Tour <<EMAIL>>
# Umut Simsekli <<EMAIL>>
# Alexandre Gramfort <<EMAIL>>
# Thomas Moreau <<EMAIL>>
import time
import numpy as np
from scipy import optimize
from joblib import Parallel, delayed
from . import cython_code
from .utils.opt... |
import numpy as np
def create_log_kernel(radius, ndims, calibration):
"""Largely inspired from Trackmate Fiji plugin.
https://github.com/fiji/TrackMate/blob/master/src/main/java/fiji/plugin/trackmate/detection/DetectionUtils.java#L53
"""
# Compute sigma
sigma = radius / np.sqrt(ndims)
sigma_... |
from io import StringIO
from antlr4.atn.ATNState import ATNState, DecisionState
from antlr4.atn.SemanticContext import SemanticContext
class ATNConfig(object):
def __init__(self, state=None, alt=None, context=None, semantic=None, config=None):
if config is not None:
if state is None:
... |
#!/usr/bin/env python
"""Check Nginx config on readthedocs.org."""
import sys
import requests
# Globals to keep count of test results
TESTS = 0
FAILS = 0
def served_by_nginx(url):
"""Return True if url returns 200 and is served by Nginx."""
r = requests.get(url, allow_redirects=False)
status = (r.statu... |
import abc
import contextlib
from ..core_types import NativeType, VirtualString, TextColor
from ..nbt import NBTType
from ..variables import VarType, ProxyEmptyException
from ..core import BasicBlock, VisibleFunction, Preamble
import commands as c
def get_subclasses(cls):
for subclass in cls.__subclasses__():
... |
import sys
import os
import random
sys.path.insert(1, os.path.join("..", "..", ".."))
import h2o
from tests import pyunit_utils
from h2o.grid.grid_search import H2OGridSearch
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def grid_parallel():
train = h2o.import_file(path=pyunit_utils.locate("smallda... |
''' args.py '''
import argparse
import os
import sys
import heron.tools.common.src.python.utils.config as config
def add_titles(parser):
'''
:param parser:
:return:
'''
# pylint: disable=protected-access
parser._positionals.title = "Required arguments"
parser._optionals.title = "Optional arguments"
r... |
import os
import time
import traceback
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import env_fallback
import json
# BEGIN DEPRECATED
# check for pyFG lib
try:
from pyFG import FortiOS, FortiConfig
from pyFG.exceptions import FailedCommit
HAS_PYFG = True
except Impor... |
# -*- coding: utf-8 -*-
"""
sphinx.ext.napoleon.iterators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A collection of helpful iterators.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import collections
class peek_iter(object):
"""An iterato... |
from pyanaconda.i18n import N_, _
from pyanaconda.ui import common
import simpleline as tui
class ErrorDialog(tui.UIScreen):
"""Dialog screen for reporting errors to user."""
title = N_("Error")
def __init__(self, app, message):
"""
:param app: the running application reference
:t... |
from django.test import TestCase, RequestFactory
from django.test import Client
from suite.views import ClubEdit
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
from suite.models import Club
class ViewClubEditTestCase(TestCase):
... |
import cgi
import app
import app.model
import app.util
import app.web
import app.web.ui
import settings
import smoid.languages
class IndexAtom (app.web.RequestHandler):
"""
A listing of the pastes as an atom feed.
"""
def __init__ (self):
app.web.RequestHandler.__init__(self)
self.se... |
"""
Sets up the main window for the 4D viewer. This includes creating MpImage4D, MpPlot,
ControlWidget4D. Also connections are made between QT signals sent by other
classes and functions within this class.
"""
from PyQt5 import QtGui, QtCore, QtWidgets
from .. import _Core as _Core
from .. import _DisplayDefinitions ... |
class GenericFlaw:
#Constants
MSG_EVIL_URL = _(" Evil url: {0}")
MSG_PARAM_INJECT = _("{0} in {1} via injection in the parameter {2}")
MSG_FROM = _(" coming from {0}")
MSG_QS_INJECT = _("{0} in {1} via injection in the query string")
MSG_PATH_INJECT = _("{0} in {1} via injection in the resourc... |
import pandas as pd, numpy as np, numpy.testing as npt, plspm.util as util, itertools as it, collections as c
from plspm.util import TopoSort
from plspm.mode import Mode
from plspm.scale import Scale
class Structure:
"""Specify relationships betweeen constructs
Use this class to specify the relationships be... |
from django.db import models
from import_export import resources
class Provinsi(models.Model):
nama_provinsi = models.CharField(max_length=100)
keterangan = models.CharField(max_length=500)
createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
updatetime = models.DateTimeField(auto_no... |
import re
import struct
from ubifs.defines import *
from ubifs import nodes
from ubifs.nodes import extract
from ubifs.log import log
class ubifs():
"""UBIFS object
Arguments:
Str:path -- File path to UBIFS image.
Attributes:
Int:leb_size -- Size of Logical Erase Blocks.
Int... |
"""
The MIT License (MIT)
Copyright (c) 2015 Taio Jia (jiasir) <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy,... |
from django.utils.html import format_html
from django.utils.translation import gettext
from rest_framework import serializers
from olympia.addons.models import Addon
from olympia.addons.serializers import AddonSerializer, VersionSerializer
from olympia.api.fields import (
FallbackField,
GetTextTranslationSeri... |
"""This module contains the general information for StorageEnclosureDiskSlotZoneHelper ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class StorageEnclosureDiskSlotZoneHelperConsts:
ADMIN_STATE_TRIGGER = "trigger"
ADMI... |
import re
import os.path
import traceback
from sys import exc_info
from offlineimap import CustomConfig
from offlineimap.ui import getglobalui
from offlineimap.error import OfflineImapError
class BaseRepository(CustomConfig.ConfigHelperMixin, object):
def __init__(self, reposname, account):
self.ui = getg... |
import os
import shutil
from twisted.trial import unittest
from buildslave.commands import fs
from buildslave.commands import utils
from buildslave.test.util.command import CommandTestMixin
from twisted.python import runtime
# python-2.4 doesn't have os.errno
if hasattr(os, 'errno'):
errno = os.errno
else:
i... |
import arcpy
import numpy
class masker:
'''Provides access to functions that produces masks from remote sensing image, according to its bit structure.'''
def __init__(self, band, *var):
self.bandarray = band
def getmask(self, bitpos, bitlen, value):
'''Generates mask with given bit information.
Parameters
... |
# coding: utf-8
import datetime
from django.template.response import TemplateResponse
def set_cookie(response, key, value, days_expire=90):
if days_expire is None:
max_age = 365 * 24 * 60 * 60 # one year
else:
max_age = days_expire * 24 * 60 * 60
expires = datetime.datetime.strftime(date... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-----------------------------------------------... |
import unittest
import numpy as np
class TestInputFunctions(unittest.TestCase):
def test_ramp(self):
"""Test functions.ramp"""
from pysd import functions
functions.time = lambda: 14
self.assertEqual(functions.ramp(.5, 10, 18), 2)
functions.time = lambda: 4
self.a... |
#
# comment class for Gig-o-Matic 2 - member comments on gigs. Replaces the old "gigcomment" class
#
# Aaron Oppenheimer
# 25 April 2014
#
from google.appengine.ext import ndb
import gig
import member
import datetime
#
# class for comment
#
class Comment(ndb.Model):
""" Models a gig-o-matic plan """
member =... |
"""Support for Melissa Climate A/C."""
import logging
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY,
HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATUR... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('content', '0030_auto_20160510_0946'),
]
operations = [
migrations.CreateModel(
name='Donat... |
from typing import List, Optional, Union
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.utils.decorators import apply_defaults
class S3ToRedshiftTransferOperator(BaseOperator):
"""
... |
import os
import shutil
from robotide.context.platform import IS_WINDOWS
from robotide.preferences.configobj import ConfigObj, ConfigObjError,\
Section, UnreprError
from robotide.preferences import excludes
from robotide.publish import RideSettingsChanged
if IS_WINDOWS:
SETTINGS_DIRECTORY = os.path.join(
... |
# Standard Library Imports
import operator
# 3rd Party Imports
# Local Imports
from . import BaseFilter
class StopFilter(BaseFilter):
""" Filter class for limiting which stops trigger a notification. """
def __init__(self, name, data):
""" Initializes base parameters for a filter. """
super(S... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: keyword
__all__ = ['iskeyword', 'kwlist']
kwlist = ['and',
'as',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'l... |
# -*- coding: utf-8 -*-
from flask_restful import Resource, marshal_with
from flask_restful_swagger import swagger
from app.mod_shared.models import db
from app.mod_profiles.models import *
from app.mod_profiles.resources.fields.measurementFields import MeasurementFields
class ProfileMeasurementList(Resource):
# ... |
#############################################################################################################################################
######### ###### ##### ###### #### #### ############ ####### ######### ########### #################################
############ ######## ## #### # ... |
from __future__ import absolute_import
import collections
import itertools
import sys
from datetime import datetime
from flask import abort, g, render_template, request, redirect, Blueprint, flash, url_for, current_app, make_response
from werkzeug.contrib.atom import AtomFeed
from flask_login import login_required, c... |
"""
The MIT License (MIT)
Copyright (c) 2015 Adrian Montero - CESR USC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, ... |
import json
import os
import string
import qmk
class MFTSCommand(qmk.Command):
'''Squirrel away text snippets or retrieve them.'''
sub_cmds = 'add echo get ls open rm'.split()
def __init__(self):
super(MFTSCommand, self).__init__(self)
self._name = 'mfts'
self._help = self.__doc... |
import re
from .. import error
from . import get_vid
from . import get_base_info
from . import get_video_info
# global vars
# version of this extractor
THIS_EXTRACTOR_VERSION = 'evparse lib/sohu version 0.1.1.0 test201505032232'
# http://tv.sohu.com/20150215/n409034362.shtml
RE_SUPPORT_URL = '^http://tv\.sohu\.com... |
# -*- coding: utf-8 -*-
'''
Manage python installations with pyenv.
.. versionadded:: v2014.04
'''
from __future__ import absolute_import
# Import python libs
import os
import re
import logging
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as ... |
# coding=utf-8
import struct
from collections import namedtuple
from base64 import b64decode
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Util import asn1
__author__ = 'Tyler Butler <<EMAIL>>'
ProofKeyDiscoveryData = namedtuple('ProofKeyDiscover... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from celery import shared_task
from apps.core.m... |
#!/usr/bin/python
"""
Usage: %(scriptName)s IP:PORT
Receive UDP packets on a IP+PORT location and print the size received.
"""
# Copyright (C) 2013 Faustino Frechilla (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "... |
# UT| python2 {src_file}
from __future__ import print_function
# UT[ ../unte.py * find_files_walk
def find_files_walk(result, path_dir, path_file):
pattern = os.path.basename(path_file)
for root, dirs, files in os.walk(path_dir):
for f in files:
if fnmatch.fnmatch(f, pattern):
... |
# -*- coding: utf-8 -*-
"""LTI model module.
TODO: Use SQLAlchemy magic on model to make queries on assignment easier
TODO: Tests
"""
#
## SAUCE - System for AUtomated Code Evaluation
## Copyright (C) 2013 Moritz Schlarb
##
## This program is free software: you can redistribute it and/or modify
## it under the terms o... |
from rally.common.i18n import _
from rally.common import log as logging
from rally.common import utils as rutils
from rally import consts
from rally.plugins.openstack.context.cleanup import manager as resource_manager
from rally.plugins.openstack.scenarios.cinder import utils as cinder_utils
from rally.task import cont... |
# -*- coding: utf-8 -*-
''' Read a CSV with revenues and insert them in the DB.
Usage:
./import_revenue [FILE] [LINES_PER_INSERT]
./import_revenue (-h | --help)
Options:
-h --help Show this message.
'''
from datetime import datetime, timedelta
import calendar
from sqlalchemy.sql.expression import ins... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from math import pi
import matplotlib.ticker as mticker
class MathTextSciFormatter(mticker.Formatter):
def __init__(self, fmt="%1.2e"):
self.fmt = fmt
def __call__(self, x, pos=None):
s = self.fmt % x
decimal_point =... |
__author__ = "Vasyl Khomenko"
__copyright__ = "Copyright 2013, Qubell.com"
__license__ = "Apache"
__version__ = "1.0.1"
__email__ = "<EMAIL>"
import os
from base import BaseTestCase
from qubell.api.private.manifest import Manifest
class ZonesClassTest(BaseTestCase):
@classmethod
def setUpClass(cls):
... |
import os
from contextlib import contextmanager
from glob import glob
import gzip
from tqdm import tqdm
import subprocess
class ParsingError(Exception):
"""Generic exception thrown by a parser."""
pass
def gzip_open_text(path, mode=None):
if not mode:
mode = 'rt'
else:
mode += 't'
... |
import django_filters
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions
from rest_framework_gis.filters import InBBoxFilter
from parkings.models import Parking
class ParkingFilter(django_filters.rest_framework.FilterSet):
status = djan... |
"""Magnum test utilities."""
from magnum.db import api as db_api
def get_test_baymodel(**kw):
return {
'id': kw.get('id', 32),
'project_id': kw.get('project_id', 'fake_project'),
'user_id': kw.get('user_id', 'fake_user'),
'uuid': kw.get('uuid', 'e74c40e0-d825-11e2-a28f-0800200c9a... |
from __future__ import absolute_import, print_function, unicode_literals
from django.test import TestCase
from mock import patch
import ntpath
import os
import posixpath
import sys
from .dummydata import windows_data, osx_data, linux_data
from ..utils.filesystem import enumerate_mounted_disk_partitions, EXPORT_FOLDE... |
# -*- coding: utf-8 -*-
r"""
A collection of methods which are related to filter design.
This module contains the following functions:
* *db*: Calculation of decibel values :math:`20\log_{10}(x)` for a vector of
values
* *ua*: Shortcut for calculation of unwrapped angle of complex values
* *grpdelay*: Calculation ... |
#!/usr/bin/env python
# File created on 09 Feb 2010
from __future__ import division
__author__ = "Justin Kuczynski"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["Justin Kuczynski", "Greg Caporaso", "Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "Justin Kuczynski... |
import abc
import enum
import numpy as np
import scipy.sparse
import scipy.io
import copy
from typing import Callable, List
import spins.invdes.parametrization as invparam
import spins.fdfd_tools as fdfd_tools
from spins.gridlock import Direction
from spins.invdes.problem.objective import OptimizationFunction
from sp... |
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_... |
# Python bindings to oDesk API
# python-odesk version 0.5
# (C) 2010-2015 oDesk
import os
import time
import urlparse
import urllib
import oauth2 as oauth
import logging
from .config import BASE_URL
from odesk.namespaces import Namespace
class OAuth(Namespace):
"""Authorization router.
Has methods for r... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
try:
from socket import inet_ntop, inet_pton, AF_INET
except ImportError:
from socket import inet_ntoa, inet_aton, AF_INET
inet_ntop = lambda x, y: inet_ntoa(y)
inet_pton = lambda x, y: inet_aton(y)
from pyasn1.compat.octets import int2oct, oct2int
OctetString, = mibBuilder.importSymbols('ASN1', 'Oct... |
import boto.ec2
import boto.route53
import imp, re, importlib
from st2actions.runners.pythonrunner import Action
import os, yaml, json, time
from ec2parsers import ResultSets
class BaseAction(Action):
def __init__(self, config):
super(BaseAction, self).__init__(config)
if config['st2_user_data'] i... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from wagtail.wagtailcore.models import Page
from wagtail.tests.testapp.models import SimplePage
from wagtail.tests.utils import WagtailTestUtils
class TestChooserBrowse(TestCase, WagtailTestUtils):
def setUp(self):
self.root_pa... |
import time
import pandas as pd
__all__ = ["KSPMonitor", "KSPMonitorDummy"]
class KSPMonitor(object):
"""Class design from Eike Mueller.
KSP monitor for writing output.
"""
def __init__(self, label=None, verbose=2):
"""Constructor for the KSPMonitor
:arg label: a string name for t... |
#!/usr/bin/env python
#encoding=utf8
'''
生成上证指数的特征
'''
import pdb
import timeutil as t
START_DATE = 20130101
SEP = 50
SEP_NUM = 250
def load_sz(conn):
''''''
sz_dic = {}
for item in conn.find({'_id':{'$gt':START_DATE}}):
sz_dic[item['_id']] = item
return sz_dic
def generate(reader, output_fn... |
"""Sanskrit transliteration conversion."""
import sys
import json
from StringIO import StringIO
import argparse
import codecs
try:
import debug
from pdb import set_trace as breakpoint
except:
pass
UTF8Writer = codecs.getwriter('utf8')
epilog = """
Transliteration names (not case sensitive in program ar... |
"""
Testing module for CUDS serialization functions.
"""
import unittest
import os
import shutil
from contextlib import closing
import tempfile
import uuid
from simphony.core import CUBA
from simphony.cuds.meta.api import CUDSComponent
from simphony.cuds.meta.api import Material
from simphony.cuds.meta.api import ... |
import threading, time, Queue, os, sys, shutil
from util import user_dir, appdata_dir, print_error, print_msg
from bitcoin import *
try:
from ltc_scrypt import getPoWHash
except ImportError:
print_msg("Warning: ltc_scrypt not available, using fallback")
from scrypt import scrypt_1024_1_1_80 as getPoWHash
... |
"""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 The... |
# Adopted from https://github.com/allenai/allennlp under Apache Licence 2.0.
# Changed the packaging.
from typing import List, Set, Tuple, Dict
import numpy
def decode_mst(
energy: numpy.ndarray, length: int, has_labels: bool = True
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""Note: Counter to typical in... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='WhatArtist',
fields=[
('id', models.AutoField(ve... |
try:
from osgeo import gdal
except ImportError:
import gdal
import sys
import stat
import os
import glob
# =============================================================================
# Usage()
# =============================================================================
def Usage():
print('Usage: gda... |
from piliko import *
############## bounding box
def bounding_box_circle( c ):
xmin = c.center.x-babylonian_square_root(abs(c.radial_quadrance))
xmax = c.center.x+babylonian_square_root(abs(c.radial_quadrance))
ymin = c.center.y-babylonian_square_root(abs(c.radial_quadrance))
ymax = c.center.y+babylonian_square_ro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.