content stringlengths 4 20k |
|---|
import attr
from axiom import item, attributes
class Account(item.Item):
"""
A bank account.
"""
# Our UUID
uuid = attributes.bytes(allowNone=False)
# From the OFX
routingNumber = attributes.text(allowNone=False)
accountID = attributes.text(allowNone=False)
accountType = attribute... |
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
from fixture.navigation import NavigationHelper
from fixture.page import PageHelper
class Application:
def __init__(self, browser, baseURL):
if... |
from openerp import models, fields, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
state = fields.Selection([
('draft', 'Draft'),
('sale', 'Sale Order'),
('done', 'Done'),
('cancel', 'Cancelled')])
class SaleOrderLine(models.Model):
_inherit = 'sale.order.l... |
__doc__ = '''
An abstract class for numeric values (integer or real).
**API reference**: :class:`Value`
This is the base class for numeric fields. Internally, it uses
Python's struct module to define the numeric value size and the byte
order (little-endian or big-endian).
The following code ... |
#!/usr/bin/env python
"""
Unfortunately the "expanded_url" as supplied by Twitter aren't fully
expanded one hop past t.co.
unshrtn.py will attempt to completely unshorten URLs and add them as the
"unshortened_url" key to each url, and emit the tweet as JSON again on stdout.
This script starts 10 seaprate processes w... |
import time
import logging
from webodm import settings
logger = logging.getLogger('app.logger')
class TestWatch:
def __init__(self):
self.clear()
def func_to_name(f):
return "{}.{}".format(f.__module__, f.__name__)
def clear(self):
self._calls = {}
self._intercept_list =... |
import os
import shutil
from mock import Mock, patch
from tempfile import mkdtemp
from unittest import TestCase
from pulp.plugins.config import PluginCallConfiguration
from pulp_puppet.common import constants
from pulp_puppet.plugins.importers.directory import SynchronizeWithDirectory
class TestSynchronizeWithDire... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
# Creating an input file for libsvm from embedding file in scode format
# S-CODE Format:
"""
<access.n.1> 1 0.114621 0.13825 -0.003325 -0.032303
-0.116092 -0.148589 -0.102534 0.054985 0.077873"""
impo... |
# Parse database configuration from $DATABASE_URL
from os import environ
GEOS_LIBRARY_PATH = environ.get('GEOS_LIBRARY_PATH')
GDAL_LIBRARY_PATH = environ.get('GDAL_LIBRARY_PATH')
AWS_ACCESS_KEY_ID = environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME =... |
# $Id: TestFileCIFSwriteHTTPread.py 1047 2009-01-15 14:48:58Z graham $
#
# Unit testing for TestFileCIFSwriteHTTPread module
#
import os
import sys
import httplib
import urllib2
import unittest
import subprocess
sys.path.append("../..")
from TestConfig import TestConfig
import TestHttpUtils
class TestFileCIFSwrite... |
import os
from setuptools import setup
README = """
See the README on `GitHub
<https://github.com/uw-it-aca/grade-conversion-calculator>`_.
"""
version_path = 'grade_conversion_calculator/VERSION'
VERSION = open(os.path.join(os.path.dirname(__file__), version_path)).read()
VERSION = VERSION.replace("\n", "")
# allow... |
from __future__ import absolute_import, division, unicode_literals
import json
import math
import time
from datetime import date, datetime, timedelta
from decimal import Decimal
from json.encoder import encode_basestring
from math import floor
from mo_dots import Data, FlatList, Null, NullType, SLOT, is_data, is_list... |
from rest_framework import generics, permissions as drf_permissions
from rest_framework.exceptions import ValidationError, NotFound
from framework.auth.oauth_scopes import CoreScopes
from website.project.model import Q, Node
from api.base import permissions as base_permissions
from api.base.views import JSONAPIBaseVie... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
from functools import wraps
import hashlib
import os.path
import json
from flask import request, Response
LINUX_USER = os.getenv('USER', 'pi')
WOTT_CREDENTIALS_PATH = '/opt/wott/credentials'
WOTT_USER_CREDENTIALS_P... |
"""
Contains a ctypes interface to the underlying ipset C library.
Python code probably wants to use the object-oriented interface in the
ipset package, instead.
"""
__all__ = (
"ipset",
"libc",
)
from ctypes import *
import ctypes.util
libc = CDLL(ctypes.util.find_library("c"))
ipset = CDLL(ctypes.util.fin... |
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_... |
# -*- coding: utf-8 -*-
from setuptools import setup
import os
def get_version(version_tuple):
if not isinstance(version_tuple[-1], int):
return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1]
return '.'.join(map(str, version_tuple))
init = os.path.join(os.path.dirname(__file__), 'haiku_e... |
"""
lotsizing_cut.py: solve the single-item lot-sizing problem.
Approaches:
- sils: solve the problem using the standard formulation
- sils_cut: solve the problem using cutting planes
Copyright (c) by Joao Pedro PEDROSO and Mikio KUBO, 2012
"""
from pyscipopt import Model, quicksum, multidict
def sils(T,f,c... |
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import... |
register(EXPORT,
id = 'Export GEDCOM Extensions',
name = _("Export GEDCOM Extensions (GED2)"),
name_accell = _("GEDCOM Extensions (GED2)"),
description = _("Extensions to the common GEDCOM format."),
version = '1.0.29',
gramps_target_version = "5.1",
status = STABLE,
fname = 'Gedco... |
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_... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.10.6.
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/
"""
import os
... |
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import os, shutil, subprocess, glob
from setup import Command, __appname__, __version__, require_... |
# coding: utf-8
from __future__ import unicode_literals
import re
import itertools
import json
from .common import InfoExtractor
from ..compat import (
compat_etree_fromstring,
)
from ..utils import (
int_or_none,
unified_strdate,
ExtractorError,
)
class BiliBiliIE(InfoExtractor):
_VALID_URL = r... |
"""
=========================
Kamaelia IRC Support Code
=========================
This provides support for Kamaelia.Protocol.IRC.*
Specifically it provides 2 core functions and 2 utility methods.
Core functions
--------------
informat(text,defaultChannel='#kamtest')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Summ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of text rendering in pyglet, including:
- how to specify fonts
- unicode
- rotating text
- mirror-image
- bidirectional and reshaped Arabic/Farsi text
"""
from __future__ import division
from psychopy import visual, core, event
# Create a window to draw in
win ... |
#!/usr/bin/env python3
import argparse
import sys
from ros_buildfarm.argument import add_argument_cache_dir
from ros_buildfarm.argument import add_argument_debian_repository_urls
from ros_buildfarm.argument import add_argument_os_code_name_and_arch_tuples
from ros_buildfarm.argument import add_argument_output_dir
fro... |
#! /usr/bin/python3
# -*- coding:Utf-8 -*-
"""
MyNotes - Sticky notes/post-it
Copyright 2016-2019 Juliette Monsel <<EMAIL>>
MyNotes 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,... |
import os
from browser import doc
import urllib.request
## this module is able to download modules that are external to
## localhost/src
## so we could download from any URL
class ModuleFinder:
def __init__(self, path_entry):
print("external_import here..")
#print(path_entry)
self._module=... |
import pymel.core as pm
# Step1:
# Select top group node. Run the following.It will generate a locator.
# Send to the current group pivot position.
# You can position the locator where you want to represent the final pivot position.
curSel = pm.ls(sl=True,type='transform')[0]
trans = pm.xform(curSel,ws=1,piv=1,q=1)
r... |
import frappe
from frappe import _
from frappe.utils import cint, flt
from frappe.database.schema import DBTable, get_definition
class PostgresTable(DBTable):
def create(self):
add_text = ''
# columns
column_defs = self.get_column_definitions()
if column_defs: add_text += ',\n'.join(column_defs)
# index
... |
from commands import add, admin
import clearbox
import cbc
# requires clearbox.py in the /scripts directory
@admin
def df(connection):
if connection.deflooring > 0:
connection.deflooring = 0
return 'DeFloor cancelled'
else:
connection.deflooring = 1
return 'Break first corner b... |
""" The base Controller API
Provides the BaseController class for subclassing.
"""
import logging
from pylons import request, session, url, tmpl_context as c
from pylons.controllers import WSGIController
from pylons.controllers.util import redirect
from pylons.templating import render_jinja2 as render
from pynip... |
'''
stash.py
sta.sh specific uploader
'''
from __future__ import print_function
import json
import urllib
import urlparse
from sqlite3 import IntegrityError
import httplib2
import requests
import mercury.log
log = mercury.log.getLogger()
redirect_url = 'http://localhost/oauth2'
def authenticate(config):
log.d... |
def mode_normal(console_printer, log_printer, args, debug=False):
import functools
from coalib.coala_main import run_coala
from coalib.output.ConsoleInteraction import (
acquire_settings, nothing_done,
print_results, print_section_beginning)
partial_print_sec_beg = functools.partial(
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from core.err_code import OCT_SUCCESS
from utils.commonUtil import getErrorMsgCN
class ApiResponse:
def __init__(self, netRet=OCT_SUCCESS, jsonResp=None):
self.netErrorNo = netRet
self.errorNo = 0
self.errorMsg = ""
self.errorLog = ""
self.err... |
#! /usr/bin/env python
import random
import math
dt = 1.0 / 30 / 10 # ten times the camera FPS
m_ball = 0.0577
g = 9.8
Fz = - m_ball * g
k = 0.8
def calc_pos(t, F, m, start_pos, start_velocity):
return start_pos + start_velocity * t + (F / 2 / m) * t * t
random.seed()
for i in range(0, 5):
speed = 20 + ... |
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list_... |
import csv
import matplotlib.pyplot as plt
from numpy import *
import scipy.interpolate
import math
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib.patches as patches
from matplotlib.path import Path
import os
# ---------------------------------------------------... |
from nailgun.statistics.utils import get_attr_value
from nailgun.statistics.utils import WhiteListRule
def volume_attachments_transform_func(attachments_list):
"""Transformation func for attachment attribute of the volume
oswl resource. Filter each element (which is dict itself) of
attachments list.
... |
import requests
import os
from bs4 import BeautifulSoup
from collections import deque
__author__ = 'bochen'
# Using the Link form MangaSpider to
# fetching the manga image, is called ImageSpider
class ImageSpider:
# Download the image from links, and save them into files
def save_Image(src, epNum, pgNum):
... |
from typing import List, Optional, Union
from airflow.hooks.base_hook import BaseHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class GenericTransfer(BaseOperator):
"""
Moves data from a connection to another, assuming that they both
provide the required ... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
class TimeLogBatch(Document):
def validate(self):
self.set_status()
self.total_hours = 0.0
for d in self.get("time_logs"):
tl = frappe.get_doc... |
from optparse import OptionParser
from os.path import exists
from shutil import copyfile
from sys import stdout
# Import from itools
import itools
from itools.core import get_pipe
if __name__ == '__main__':
version = 'itools %s' % itools.__version__
description = ('Merges the given POT file into the PO file... |
#!/usr/bin/env python3
import sys
from os.path import join,exists,dirname
import random
from datetime import datetime
import time
import numpy as np
from numpy.random import randint
from sklearn.datasets import load_svmlight_file
from torch.autograd import Function, Variable
import torch.nn as nn
import torch.optim as... |
import json
from flask import url_for
from CTFd.constants import JinjaEnum, RawEnum
from CTFd.utils import get_config
class ConfigTypes(str, RawEnum):
CHALLENGE_VISIBILITY = "challenge_visibility"
SCORE_VISIBILITY = "score_visibility"
ACCOUNT_VISIBILITY = "account_visibility"
REGISTRATION_VISIBILITY... |
from opcode import opmap, HAVE_ARGUMENT, EXTENDED_ARG
globals().update(opmap)
def _make_constants(f, builtin_only=False, stoplist=[], verbose=False):
try:
co = f.func_code
except AttributeError:
return f # Jython doesn't have a func_code attribute.
newcode = map(ord, co.co_code)
... |
"""Test the HomeKit config flow."""
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.homekit.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_NAME, CONF_PORT
from tests.async_mock import patch
from tests.common... |
def save_session(self):
"""saves open filenames to a file called session"""
name = open("session", "w")
for buffer in self.buffers:
text = buffer.filename
name.write(buffer.filename + "\n")
name.close()
def open_session(self, ret):
"""opens session from session file"""
if ret:
... |
from oslo_policy import policy
rules = [
policy.RuleDefault(
'external',
'field:networks:router:external=True',
description='Rule of external network'),
policy.RuleDefault(
'create_network',
'',
description='Access rule for creating network'),
policy.RuleDe... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_chameleon',
'pyramid_d... |
import sys
sys.path.append("/vagrant/dockerEE/service")
import os
import time
from environment_emulation_runner import EnvironmentEmulationRunner
## TestDaemon
#
# The test daemon class
class TestDaemon(object):
## constructor
def __init__(self):
self.stdin_path = self.stdout_path = self.stderr_path ... |
#!/usr/bin/env python
"""Creates the excercise contents."""
from __future__ import annotations
import multiprocessing
import logging
import os
import random
import subprocess
from typing import Dict, List, Optional, Set, Tuple, Union
from svgtransform import SvgTransform
LOGGER = logging.getLogger(__name__)
RANDOM_... |
import boto3
import sys
import time
import logging
import botocore.errorfactory
import ecstaskrunner
import ecstaskrunner.task
def has_failed(response):
return 'failures' in response
def run_task(**kwargs):
logger = logging.getLogger('ecstaskrunner')
client = boto3.client('ecs')
response = client.run... |
from collections import namedtuple
import requests
import requests_mock
from exchangelib.account import Identity, DELEGATE
from exchangelib.errors import UnauthorizedError
from exchangelib.transport import wrap, get_auth_method_from_response, BASIC, NOAUTH, NTLM, DIGEST
from exchangelib.util import PrettyXmlHandler, ... |
from django.conf.urls import *
from apps.reader import views
urlpatterns = [
url(r'^$', views.index),
url(r'^buster', views.iframe_buster, name='iframe-buster'),
url(r'^login_as', views.login_as, name='login_as'),
url(r'^logout', views.logout, name='welcome-logout'),
url(r'^login', views.login, nam... |
"""
Sends a post-release email
"""
from __future__ import print_function
from rez.release_hook import ReleaseHook
from rez.system import system
from email.mime.text import MIMEText
from rez.utils.logging_ import print_warning, print_error
from rez.utils.yaml import load_yaml
from rez.utils.scope import scoped_formatte... |
"""
****************************************
**espresso.interaction.TersoffPairTerm**
****************************************
"""
from espresso import pmi, infinity
from espresso.esutil import *
from espresso.interaction.Potential import *
from espresso.interaction.Interaction import *
from _espresso import interact... |
from __future__ import division
from .base import Layout
class VerticalTile(Layout):
"""Tiling layout that works nice on vertically mounted monitors
The available height gets divided by the number of panes, if no pane is
maximized. If one pane has been maximized, the available height gets split
in m... |
r"""
===============================================================================
Submodule -- electrical_conductance
===============================================================================
"""
import scipy as _sp
def series_resistors(physics, phase, network,
pore_conductivity='pore.... |
#!/usr/bin/env python
import sys
from os.path import expanduser
from os.path import exists
from os.path import isdir
from os.path import abspath
from os.path import join
from os.path import walk
from pipes import quote
from re import search
from re import compile
import subprocess
import argparse
import logging
cl... |
import ctypes.util
import os
from PyInstaller.depend.utils import _resolveCtypesImports
from PyInstaller.compat import is_cygwin
# Include glob for library lookup in run-time hook.
hiddenimports = ['glob']
# Try to resolve your libusb libraries in the following order:
#
# libusb-1.0, libusb-0.1, openusb
#
# NOTE... |
from __future__ import with_statement, absolute_import
import time
from contextlib import closing
import psycopg2
from . import print_row_progress, status_logger
from .postgres_writer import PostgresWriter
class PostgresDbWriter(PostgresWriter):
"""Class used to stream DDL and/or data
from a MySQL server t... |
'''
Test for deleting and expunge image created vm ops.
The key step:
-add image1
-create vm1 from image1
-export image1
-create image2 from vm1
-export image2
-create vm2 from image2
-del and expunge image1
-change vm2 os
-del image2
-resize data volume on vm2
-expunge image2
-change vm2 state
@author: PxChen
'''
i... |
#! /usr/mybin/env python
from ROOT import kRed, kBlue, kOrange, kGreen
from base.Graphics import Style
from base.FileHandler import LegoTrainFileReader
from util.TriggerTurnonCurve import TriggerTurnonCurve
from plots.TriggerTurnonPlot import TriggerTurnonPlot
def MakeNormalisedSpectrum(inputdata, name):
"""
... |
from __future__ import unicode_literals
from importlib import import_module
import inspect
import logging
import json
from django.conf.urls import patterns
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import get_ns_resolver, get_resolver, get_script_prefix, NoReverseMatch
from... |
import pygame
from Axon.Ipc import producerFinished, shutdownMicroprocess
from Kamaelia.Visualisation.PhysicsGraph.TopologyViewer import TopologyViewer
from Kamaelia.Visualisation.Axon.AxonVisualiserServer import AxonVisualiser
from Kamaelia.Support.Particles import SimpleLaws, Particle
from Kamaelia.Visualisation.Axo... |
"""This component provides support for Stookalert Binary Sensor."""
from datetime import timedelta
import logging
import stookalert
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_SAFETY,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import ATTR... |
"""The tests for Lock device conditions."""
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.lock import DOMAIN
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
from homeassistant.helpers import device_registry
from homeassistant.setup import async_setup_... |
import logging
import praw
import requests
import re
from .exceptions import (SubmissionError, SubredditError, SubscriptionError,
AccountError)
from .helpers import humanize_timestamp, wrap_text, strip_subreddit_url
__all__ = ['SubredditContent', 'SubmissionContent', 'SubscriptionContent']
_... |
#!/usr/bin/env python
import Tkinter as tk
from random import random
def make_a_right_turn(a, b, c):
"""Going from a to b to c involves a right turn?"""
u = (c[0] - b[0], c[1] - b[1])
v = (a[0] - b[0], a[1] - b[1])
cross_product = u[0] * v[1] - u[1] * v[0]
return cross_product < 0
def graham_s... |
import collections
from pupa.scrape import Scraper, Organization
from openstates.utils import LXMLMixin
base_url = 'http://www.nmlegis.gov/Committee/'
Member = collections.namedtuple('Member', 'name role chamber')
def clean_committee_name(name_to_clean):
head, separator, tail = name_to_clean.replace('House ', '... |
#!/usr/bin/env python
#
# A wrapper around the psycopg2 code that makes some things easier. For
# example, returns are dictionaries, the "query" method creates and
# automatically releases cursors.
#
# You may also want to see Martin Blais' antiorm, which does some similar
# things: http://furius.ca/antiorm/
#
# ... |
import os.path
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
THISDIR = os.path.abspath(os.path.dirname(__file__))
def read_init_module():
# cssypy/__init__.py does not have any imports, so just run it as a script
# to get its version information.
... |
'''
Created on 23 Sep 2014
@author: Panos
'''
# ===========================================================================
# Copyright 2013 University of Limerick
#
# This file is part of DREAM.
#
# DREAM is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Lic... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013-2018 Danilo Bargen
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, modify,... |
import datetime
import uuid as stdlib_uuid
from oslo_utils import timeutils
import webob
from nova.api.openstack.compute import consoles as consoles_v2
from nova.api.openstack.compute.plugins.v3 import consoles as consoles_v21
from nova.compute import vm_states
from nova import console
from nova import db
from nova i... |
import sys
import aiohttp_jinja2
from aiohttp import web
from .toolbar import DebugToolbar
from .tbtools.tbtools import get_traceback
from .utils import addr_in, REDIRECT_CODES, APP_KEY, TEMPLATE_KEY, hexlify, \
ContextSwitcher
__all__ = ['toolbar_middleware_factory', 'middleware']
HTML_TYPES = ('text/html', 'app... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import os
from typing import Optional, List, Tuple, Dict, Union
from models.literalConstants import LiteralConstants
class FileProcessing:
BASE_PATH: str = os.getcwd() + "/"
def __init__(self, path: str, file_type: LiteralConstants.FileType) -> None:
... |
# -*- coding: utf-8 -*-
"""UnitTests for sysdescrparser."""
import unittest
import os
import json
from sysdescrparser import sysdescrparser
from sysdescr import SysDescr
class UnitTests(unittest.TestCase):
"""Class UnitTest.
Unit test for sysdescrparser.
"""
def setUp(self):
"""Setup."""... |
# Iterates over a directory that contains correspondence list json files, and optimizes the montage by perfroming the transform on each file.
# The output is either in the same directory or in a different, user-provided, directory
# (in either case, we use a different file name)
#
# requires:
# - java (executed from th... |
from __future__ import division
from collections import defaultdict
import numpy
from scipy import ndimage
DISTANCE = numpy.sqrt([
2., 1., 2.,
1., 1., 1.,
2., 1., 2.
])
DIR_MAP = dict(zip(range(9), [32, 64, 128, 16, -1, 1, 8, 4, 2]))
FLOWS_IN = numpy.array([2, 4, 8, 1, numpy.nan, 16, 128, 64, 32])
def ... |
import cherrypy
import sys
from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource
from girder.api.rest import RestException, loadmodel, getCurrentUser
from girder.constants import AccessType, TokenScope
from girder.constants import TerminalColo... |
import unittest
import flask_featureflags as feature_flags
from flask_featureflags.contrib.inline import InlineFeatureFlag
from tests.fixtures import app
from tests.fixtures import feature_setup
inline_feature_flag = InlineFeatureFlag()
class InlineFeatureFlagTest(unittest.TestCase):
@classmethod
def setUpCla... |
#
# Created by DraX on 2005.08.18 modified by Ariakas on 2005.09.19
#
import sys
from net.sf.l2j.gameserver.model.quest import State
from net.sf.l2j.gameserver.model.quest import QuestState
from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest
MARK_OF_RAIDER_ID = 1592
KHAVATARI_T... |
import argparse
import logging
import os
from configobj import ConfigObj
from .main import (
ensure_default_settings,
get_versionone_connection,
get_jira_connection,
get_jira_issue_for_v1_issue,
get_versionone_story_by_name,
update_jira_ticket_with_versionone_data,
reset_saved_passwords
)
... |
import string
import re
import smtplib
import logging
from boto.exception import BotoServerError
from django.core.mail.message import EmailMessage
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from openedx.core.djangoapps.content.cou... |
#!/usr/bin/env python
import imp
import pkgutil
import sys
from os.path import dirname
"""
Usage: set_py_check_dependencies [MODULENAME]...
For each MODULENAME, print a line indicating whether the respective
module is found and loadable.
"""
all_ok = True
install = []
damaged = []
for pkg in sys.argv[1:]:
... |
import os
import re
import sys
from glob import glob
from imp import load_source
from os.path import isdir, isfile, join
import click
from platformio import exception, util
from platformio.app import get_state_item, set_state_item
from platformio.pkgmanager import PackageManager
PLATFORM_PACKAGES = {
"framework... |
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from django.db.models import Q
from zerver.models import Realm, Stream, Message, Subscription, Recipient, get_realm
class Command(BaseCommand):
help = "Generate statistics on the streams for a realm."
def add_arguments... |
import sys
import os
import errno
from io import StringIO as StringIO
import re
import os.path
from types import ModuleType
import stat
import tarfile
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line
'''
Container w/ loading/dumping capabilities for tsv format... |
import tensorflow as tf
import awesome_gans.modules as t
tf.set_random_seed(777)
class UGAN:
def __init__(
self,
s,
batch_size=64,
height=32,
width=32,
channel=3,
sample_num=8 * 8,
sample_size=8,
z_dim=256,
gf_dim=64,
df_dim... |
from soldiers import *
from towers import *
from economy import Economy
from output import ConsoleOutput, Output
from runGame import Game
import gamemap
import deap
import random, copy
from deap import base
from deap import creator
from deap import tools
def updateArmyWithCurrentMap(fodderArmy, newMap):
for unit... |
"""
Read the cophenetic matrix and add some additional metadata to it.
"""
import os
import sys
import argparse
import re
def read_domains(df):
"""
Read and return the domains
:param df: the domains file to read
:return: the domain for each of the species
"""
data = {}
with open(df, 'r')... |
"""Test IAM Policy templates are valid JSON."""
import json
import jinja2
import pytest
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2... |
import io
import os
import setuptools
# Package metadata.
name = "google-api-core"
description = "Google API client core library"
# Should be one of:
# 'Development Status :: 3 - Alpha'
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_status = "Development Status :: 5 - Pr... |
from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection, ConfigPassword
from Components.Console import Console
from Components.Network import iNetwork
from os import system, path as os_path
from string import maketrans, strip
import sys
import types
from re import compi... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_find
version_added: "2.3"
short_description: Return a list of files based on specific criteria
description:
- Return a list of files based ... |
"""
SQLAlchemy models for watcher service
"""
from oslo_db.sqlalchemy import models
from oslo_serialization import jsonutils
import six.moves.urllib.parse as urlparse
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy.ext.declarative import declarative_base
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.