code stringlengths 1 199k |
|---|
from enum import Enum
class EnumVMStatus(Enum):
deploying = "deploying"
running = "running"
halted = "halted"
paused = "paused"
halting = "halting"
migrating = "migrating"
starting = "starting"
error = "error"
networkKilled = "networkKilled" |
'''
New Integration Test for creating KVM VM and check time for each stage.
@author: Glody
'''
import apibinding.inventory as inventory
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import os
import random
import string
impor... |
import pytest
from share.regulate import Regulator
from tests.share.normalize.factories import (
Agent,
AgentIdentifier,
Contributor,
CreativeWork,
Creator,
Funder,
Host,
Institution,
IsPartOf,
Organization,
Person,
Publisher,
Tag,
WorkIdentifier,
)
class TestMode... |
import functools
import os
import tempfile
import base64
from tempfile import mkstemp
from OpenSSL import crypto
import M2Crypto
from M2Crypto import X509
from extensions.sfa.util.faults import CertExpired, CertMissingParent, CertNotSignedByParent
from extensions.sfa.util.sfalogging import logger
glo_passphrase_callbac... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
import re
from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin
from pants.backend.jvm.tasks.nailgun_task import NailgunTask
from pants.bas... |
""" iframe-eventsource transport """
import asyncio
from aiohttp import web, hdrs
from sockjs.protocol import ENCODING
from .base import StreamingTransport
from .utils import session_cookie
class EventsourceTransport(StreamingTransport):
def send(self, text):
blob = ''.join(('data: ', text, '\r\n\r\n')).enc... |
import pecan
from pecan import rest
from wsme import types as wtypes
from wsmeext import pecan as wsme_pecan
from payload.cache import models
from payload.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class QueueCaller(object):
"""API representation of a queue caller."""
created_at = ... |
"""
DOCS for dataenc as a module
When run it should go through a few basic tests - see the function test()
This module provides low-level functions to interleave two bits of data into each other and separate them.
It will also encode this binary data to and from ascii - for inclusion in HTML, cookies or email transmiss... |
import _thread as thread
import logging
import operator
import sys
from queue import Empty
from queue import Queue
from threading import Lock
from threading import Semaphore
from threading import Thread
from docker.errors import APIError
from docker.errors import ImageNotFound
from compose.cli.colors import AnsiMode
fr... |
"""Tests for the storage media tool object."""
import argparse
import io
import os
import unittest
try:
import win32console
except ImportError:
win32console = None
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.lib import errors as dfvfs_errors
from dfvfs.helpers import source_scanner
from dfvfs.... |
'''
Created on Sept 26, 2013
@author: Rafael Nunes
'''
def webapp_add_wsgi_middleware(app):
from google.appengine.ext.appstats import recording
app = recording.appstats_wsgi_middleware(app)
return app |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class ThriftLinterTest(PantsRunIntegrationTest):
def test_good(self):
# thrift-linter sh... |
from oslo_config import cfg
from nova.tests.functional.api_sample_tests import api_sample_base
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.legacy_v2.extensions')
class FlavorExtraSpecsSampleJsonTests(api_sample_base.ApiSampleTestBaseV3):
ADMIN_API = True
... |
import acm
import ael
import FHTI_EDD_OTC_Util
import HTI_ExcelReport2
import HTI_Util
import HTI_FeedTrade_EDD_Util
import os
import win32com.client
import HTI_CollateralManagement_TRS
import sqlite3
ael_variables = [['posdate', 'Date', 'string', [str(ael.date_today()), 'Today'], 'Today', 1, 0, 'Report Date', None, 1]... |
"""Compiles all *.proto files it finds into *_pb2.py."""
from __future__ import print_function
import logging
import optparse
import os
import re
import shutil
import subprocess
import sys
import tempfile
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
MIN_SUPPORTED_PROTOC_VERSION = (3, 17, 3)
MAX_SUPPORTED_PROTO... |
"""
Brocade south bound connector to communicate with switch using
HTTP or HTTPS protocol.
"""
import time
from oslo_log import log as logging
from oslo_serialization import base64
from oslo_utils import encodeutils
import requests
import six
from cinder.i18n import _
from cinder.zonemanager.drivers.brocade import exce... |
from scaleiopy import *
from pprint import pprint
import sys
sio = scaleio.ScaleIO("https://" + sys.argv[1] + "/api",sys.argv[2],sys.argv[3],False,"ERROR") # HTTPS must be used as there seem to be an issue with 302 responses in Requests when using POST
snapSpec = scaleio.SnapshotSpecification()
snapSpec.addVolume(sio.g... |
"""Checkout Zookeeper ensemble.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
from treadmill import context
from treadmill import checkout
from treadmill import zknamespace as z
def _metadata():
"... |
from django.contrib import admin
from fclover.comment.models import *
admin.site.register(CommentU2A)
admin.site.register(CommentU2U)
admin.site.register(MessageU2A)
admin.site.register(MessageU2U) |
from __future__ import absolute_import
import datetime
import json
import math
import time
from google.api_core import datetime_helpers
from google.cloud.pubsub_v1.subscriber._protocol import requests
_MESSAGE_REPR = """\
Message {{
data: {!r}
attributes: {}
}}"""
def _indent(lines, prefix=" "):
"""Indent some... |
from sqlalchemy import *
meta = MetaData()
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
volumes = Table('volume', meta, autoload=True)
volumes.c.clone_of.alter(name='restore_of')
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
volumes ... |
"""The HFS path specification implementation."""
from dfvfs.lib import definitions
from dfvfs.path import factory
from dfvfs.path import path_spec
class HFSPathSpec(path_spec.PathSpec):
"""HFS path specification implementation.
Attributes:
data_stream (str): data stream name, where None indicates the default
... |
"""Manages progress bars for DVC repo."""
import logging
import sys
from threading import RLock
import fsspec
from tqdm import tqdm
from dvc.env import DVC_IGNORE_ISATTY
from dvc.utils import env2bool
logger = logging.getLogger(__name__)
tqdm.set_lock(RLock())
class Tqdm(tqdm):
"""
maximum-compatibility tqdm-ba... |
"""Helpers for the 'hello' and legacy hello commands."""
import copy
import datetime
import itertools
from typing import Any, Generic, List, Mapping, Optional, Set, Tuple
from bson.objectid import ObjectId
from pymongo import common
from pymongo.server_type import SERVER_TYPE
from pymongo.typings import _DocumentType
c... |
import copy
import json
import warnings
import requests
from indexclient.errors import BaseIndexError
MAX_RETRIES = 10
UPDATABLE_ATTRS = [
"file_name",
"urls",
"version",
"metadata",
"acl",
"authz",
"urls_metadata",
]
def json_dumps(data):
return json.dumps({k: v for (k, v) in data.items... |
from .columbia_imagecontentsearch import ColumbiaImageContentSearch
from .settings import ColumbiaSetting
def load(info):
columbiaSetting = ColumbiaSetting()
for setting in columbiaSetting.requiredSettings:
columbiaSetting.get(setting)
info['apiRoot'].columbia_imagecontentsearch = ColumbiaImageConte... |
import json
import argparse
from datetime import datetime, date
from fuzzywuzzy import fuzz, process
from elasticsearch import Elasticsearch
from elasticsearch.helpers import streaming_bulk, scan
parser = argparse.ArgumentParser()
parser.add_argument("--config-path", type=str, action='store', default='../config.json')
... |
"""Tests for numerical correctness."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.keras import keras_parameterized
from tensorflow.python... |
from __future__ import print_function
import os
TEST_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(os.path.dirname(__file__), '..', '..', 'resources')
BUILD = ['build', '--no-notify', '--no-status']
CLEAN = ['clean', '--all', '--yes'] # , '--no-notify', '--no-color', '--no-status']
def test_add_package(... |
from __future__ import unicode_literals
import os
import unittest
import io
from lxml import etree
from packtools.catalogs import checks
SAMPLES_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'samples')
class SetupTests(unittest.TestCase):
def test_message_is_splitted(self):
fp = e... |
import os
import time
from .. import run_nbgrader
from .base import BaseTestApp
from .conftest import notwindows
from ...utils import parse_utc
@notwindows
class TestNbGraderCollect(BaseTestApp):
def _release_and_fetch(self, assignment, exchange, course_dir):
self._copy_file(os.path.join("files", "test.ipyn... |
import warnings
from . import _minpack
import numpy as np
from numpy import (atleast_1d, dot, take, triu, shape, eye,
transpose, zeros, prod, greater,
asarray, inf,
finfo, inexact, issubdtype, dtype)
from scipy.linalg import svd, cholesky, solve_triangular, LinAl... |
from django import template
from datatables.utils import lookupattr
register = template.Library()
register.filter('lookupattr', lookupattr) |
"""A module that handles matrices.
Includes functions for fast creating matrices like zero, one/eye, random matrix etc.
"""
from matrices import Matrix, SMatrix, zero, zeronm, zeros, one, ones, eye, \
hessian, randMatrix, GramSchmidt, wronskian, casoratian, \
list2numpy, matrix2numpy, DeferredVector, block_di... |
from __future__ import absolute_import
from django.conf import settings
def is_active_superuser(request):
user = getattr(request, 'user', None)
if not user:
return False
if settings.INTERNAL_IPS:
ip = request.META['REMOTE_ADDR']
if not any(ip in addr for addr in settings.INTERNAL_IPS... |
"""
Additional tests for PandasArray that aren't covered by
the interface tests.
"""
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.arrays import PandasArray
from pandas.core.arrays.numpy_ import PandasDtype
@pytest.fixture(
params=[
np.array(["a", "b"], dtype=... |
import sys
from klampt import *
from klampt.glrobotprogram import *
keymap = None
def build_default_keymap(world):
"""builds a default keymape: 1234567890 increases values of DOFs 1-10
of robot 0. qwertyuiop decreases values."""
if world.numRobots() == 0:
return {}
robot = world.robot(0)
up... |
"""
Various utility functions.
-----
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License. See http://scipy.org.
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
Author: Pearu Peterson <pearu@cens.ioc.ee>
Created: May 2006
-----
"""
__all__ = ['split_comma', '... |
from setuptools import setup, find_packages
description="""
Ligthweight connection pooler for PostgreSQL.
"""
long_description = """
* **Documentation**: TODO
* **Project page**: TODO
"""
setup(
name="pgbouncer-ng",
version=':versiontools:pgbouncerlib:',
url='https://github.com/niwibe/pgbouncer-ng',
lic... |
"""Ops that consume or generate index-based pointers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
fr... |
import numpy as np
from nose.tools import assert_equal
from numpy.testing import assert_array_equal
from ..fixes import _in1d, _copysign
def test_in1d():
a = np.arange(10)
b = a[a%2 == 0]
assert_equal(_in1d(a, b).sum(), 5)
def test_copysign():
a = np.array([-1, 1, -1])
b = np.array([ 1, -1, 1])
... |
import numpy as np
import time
import copy
from numpy import array, random, diag
from vb_mf import normalize_trans, normalize_emit, make_log_obs_matrix, make_log_obs_matrix_gaussian
from treehmm.static import float_type
min_val = float_type('1e-150')
def independent_update_qs(args):
theta, alpha, beta, gamma, X, lo... |
"""
==============================================================
Reading a .dip file form xfit and view with source space in 3D
==============================================================
Here the .dip file was generated with the mne_dipole_fit command.
Detailed unix command is :
$mne_dipole_fit --meas sample_audv... |
""" The implementation of an IPython shell. """
try:
import IPython.frontend
except ImportError:
raise ImportError, '''
________________________________________________________________________________
Could not load the Wx frontend for ipython.
You need to have ipython >= 0.9 installed to use the ipython widget... |
from django.conf.urls import url
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from eventkit_cloud.core.urls import urlpatterns as eventkit_cloud_urlpatterns
urlpatterns = [
url(
r"^favicon.png$",
RedirectView.as_view(url=static... |
"""Utilities for use across the Message Manamgent module"""
class APIDict(dict):
"""Custom API Dict type"""
def __init__(self, session_func, uri=None, *args, **kwargs):
super(APIDict, self).__init__(*args, **kwargs)
self.session_func = session_func
self.uri = uri
def __setitem__(self... |
from __future__ import print_function
import slices, go
a = [1,2,3,4]
b = slices.CreateSlice()
print ("Python list:", a)
print ("Go slice: ", b)
print ("slices.IntSum from Python list:", slices.IntSum(go.Slice_int(a)))
print ("slices.IntSum from Go slice:", slices.IntSum(b))
su8 = slices.SliceUint8([1,2])
su16 = slices... |
import argparse
import sys
from pgltools_library import *
def _formatContacts(contacts,delim):
return [delim.join([str(y) for y in x[:-1]])+delim+delim.join([str(y) for y in x[-1]]) for x in contacts if len(x)!=0]
def _subtract1D(chrA1,startA1,endA1,chrA2,startA2,endA2,chrB,startB,endB,Aannots,whichBin):
if whi... |
from django.db.models.fields import FieldDoesNotExist
class WrongManager(Exception): pass |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
import six
from bokeh.document import Document
import bokeh.application.handlers.code as bahc
script_adds_two_roots = """
from bokeh.io import curdoc
from bokeh.model import Model
from bokeh.core.properties import ... |
import datetime
from decimal import Decimal
import mock
from constance.admin import get_values
from constance.checks import check_fieldsets, get_inconsistent_fieldnames
from constance.management.commands.constance import _set_constance_value
from django.core.exceptions import ValidationError
from django.test import Tes... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
import io
from os import pardir
from os.path import split, join, abspath, relpath, basename, splitext
import subprocess
@pytest.mark.codebase
def test_code_quality():
''' Applies a collection of general codebas... |
""" Models for representing top-level plot objects.
"""
from __future__ import absolute_import
from six import string_types
import warnings
from ..core.query import find
from ..core import validation
from ..core.validation.errors import REQUIRED_RANGE
from ..core.validation.warnings import (
MISSING_RENDERERS, NO_D... |
import sys
import time
import datetime
import os
import os.path
import io
import json
import pprint
import ssl
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
sys.path.insert(0,os.path.abspath("venv/lib/python2.7/site-packages/"))
from requests_toolb... |
"""Job controller utils."""
import logging
import os
import subprocess
import sys
from reana_db.database import Session
from reana_db.models import Workflow
def singleton(cls):
"""Singelton decorator."""
instances = {}
def getinstance(**kwargs):
if cls not in instances:
instances[cls] = ... |
import argparse
import logging
import os
import pytest
import subprocess
import tempfile
import time
from mock import patch
import teuthology
from teuthology import misc
from teuthology.config import set_config_attr
from teuthology.openstack import TeuthologyOpenStack, OpenStack, OpenStackInstance
from teuthology.opens... |
"""
Press 's' to take a picture and start matching image real-time
"""
import cv2
import numpy as np
from cam import MyCam
from fmatch import draw_match
print __doc__
MIN_MATCH_COUNT = 10
orb = cv2.ORB()
cam = MyCam()
cam.size = (640, 480)
img1 = img1 = cv2.imread('box.png', 0)
cv2.imshow('source', img1)
while True:
... |
"""
homeassistant.components.sensor.mysensors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for MySensors sensors.
Configuration:
To use the MySensors sensor you will need to add something like the
following to your config/configuration.yaml
sensor:
platform: mysensors
port: '/dev/ttyACM0'
Variables:
port
*Requ... |
import requests
class DataViewRestClient():
def __init__(self, endpoint, authtoken, certificate=None):
self.ENDPOINT = endpoint
self.AUTHTOKEN = authtoken
self.CERTIFICATE = certificate
if not self.ENDPOINT.endswith('/'):
self.ENDPOINT = self.ENDPOINT + '/'
def get_headers(self):... |
import cython
cython.declare(Nodes=object, ExprNodes=object, EncodedString=object,
BytesLiteral=object, StringEncoding=object,
FileSourceDescriptor=object, lookup_unicodechar=object,
Future=object, Options=object, error=object, warning=object,
Builtin=object, ... |
class Node(object):
"""
double linked list node
"""
def __init__(self, value, keys):
self.value = value
self.keys = keys
self.prev = None
self.next = None
class LinkedList(object):
def __init__(self):
self.head, self.tail = Node(0, set()), Node(0, set())
... |
import Tkinter as tk
import ttk
import platform
def quit():
global tkTop
tkTop.destroy()
tkTop = tk.Tk()
tkTop.geometry('500x300')
tkLabelTop = tk.Label(tkTop, text=" http://hello-python.blogspot.com ")
tkLabelTop.pack()
notebook = ttk.Notebook(tkTop)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
no... |
"""
Wrap your code with a time limit to prevent something from taking too long
(getting into an infinite loop, etc.)
**Examples**
>>> from timeout import timeout
>>> with timeout(seconds=3):
>>> do something
Taken and slightly modified from Thomas Ahle at:
<http://stackoverflow.com/questions/2281850... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('people', '0004_auto_20150706_1547'),
]
operations = [
migrations.AddField(
model_name='contributorlistpage',
name='people_per_pag... |
import sys, string
if len(sys.argv) >= 4:
file = open(sys.argv[1], "r")
csid = sys.argv[2]
name = sys.argv[3]
if len(sys.argv) == 4:
dceid = "omniCodeSet::ID_" + csid
else:
dceid = sys.argv[4]
else:
sys.stderr.write("Usage: %s <file> <csid> <name> [dce id]\n" % sys.argv[0])
... |
"""Test that the toolchain can build executables.
Multiple build tools and languages are supported. If an emulator is available,
its ability to run the generated executables is also tested.
"""
import argparse
import glob
import os
import shutil
import subprocess
import sys
import tempfile
def test_none_build_system(bu... |
"""Persistent identifier minters."""
from __future__ import absolute_import
import uuid
from .providers import DepositProvider
def deposit_minter(record_uuid, data):
"""Mint a deposit identifier.
A PID with the following characteristics is created:
.. code-block:: python
{
"object_type":... |
import codecs
import collections
import re
"""
This script van generate a dictionary of language names.
This dictionary looks as follows:
language_names = {
"C": {
"nl": "Dutch",
"de": "German",
"en": "English",
},
"nl": {
"nl": "Nederlands",
"de": "Duits",
"e... |
import logging
_logger = logging.getLogger('read-etexts-activity')
supported = True
try:
import gst
gst.element_factory_make('espeak')
from speech_gst import *
_logger.info('use gst-plugins-espeak')
except Exception, e:
_logger.info('disable gst-plugins-espeak: %s' % e)
try:
from speech_... |
import sys
sys.path.append("/usr/share/rhn/")
from up2date_client import rhnserver
from up2date_client import up2dateAuth
from up2date_client import pkgUtils
from actions import packages
__rhnexport__ = [
'update']
ACTION_VERSION = 2
def __getErrataInfo(errata_id):
s = rhnserver.RhnServer()
return s.errata.... |
"""ROI and ROIList classes for storing and manipulating
regions of interests (ROIs).
ROI.ROI objects allow for storing of ROIs as either as a boolean mask of
included pixels, or as multiple polygons. Masks need not be continuous and
an ROI can be defined by multiple non-adjacent polygons.
In addition, each ROI can be a... |
from PyQt4.QtCore import QAbstractTableModel, Qt, QVariant, QModelIndex
class ObjectclassTableModel(QAbstractTableModel):
def __init__(self, parent = None):
QAbstractTableModel.__init__(self, parent)
self.templateObject = None
def setTemplateObject(self, templateObject = None):
self.begi... |
"""
* sVimPy - small Virtual interpreting machine for Python
* (c) 2012 by Tim Theede aka Pez2001 <pez2001@voyagerproject.de> / vp
*
* python arduino api wrapper
*
* 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 ... |
from argparse import Action, ArgumentDefaultsHelpFormatter, ArgumentTypeError
from glob import glob
from importlib import import_module
from os.path import basename, dirname
from reportclient import set_verbosity
from abrtcli import config
from abrtcli.i18n import _
class Command:
aliases = []
description = Non... |
CODES = [
('', ''),
('011111', u'011111 - CULTIVO DE ARROZ'),
('011112', u'011112 - CULTIVO DE TRIGO'),
('011119', u'011119 - CULTIVO DE CEREALES EXCEPTO LOS FORRAJEROS Y LAS SEMILLAS N.C.P.'),
('011121', u'011121 - CULTIVO DE MAIZ'),
('011122', u'011122 - CULTIVO DE SORGO GRANIFERO'),
('011... |
from __future__ import division, absolute_import, unicode_literals
import time
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from .. import qtutils
from ..i18n import N_
from . import defs
from .text import MonoTextView
class LogWidget(QtWidgets.QWidget):
"""A simple dialog to... |
from ReddiWrap import ReddiWrap
reddit = ReddiWrap(user_agent='ReddiWrap')
USERNAME = 'your_username'
PASSWORD = 'your_password'
MOD_SUB = 'your_subreddit' # A subreddit moderated by USERNAME
reddit.load_cookies('cookies.txt')
if not reddit.logged_in or reddit.user.lower() != USERNAME.lower():
print('logging into %s'... |
import picross
import sys
import time
import optparse
def decode_mcs(file):
code = []
for l in open(file,'U').readlines():
if len(l)==44:
code.extend([ int(l[2*x+9:2*x+11],16) for x in range(0,16) ])
return ''.join(map(chr,code))
def load_firmware(dev,fw):
device = picross.usbdevice(... |
import traceback
import importlib
from .WebWizardConst import *
from ..common.UCB import UCB
from ..common.FileAccess import FileAccess
from ..ui.event.Task import Task
from ..ui.event.CommonListener import StreamListenerProcAdapter
from .ProcessErrors import ProcessErrors
from .ExtensionVerifier import ExtensionVerifi... |
import argparse
import importlib
import ast
from .docscrape_sphinx import get_doc_object
def main(argv=None):
"""Test numpydoc docstring generation for a given object"""
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('import_path', help='e.g. numpy.ndarray')
def _parse_config(s):
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
author: Ansible Core Team
connection: persistent
short_description: Use a persistent unix socket for connection
description:
- This is a helper plugin to allow making other connections per... |
import json
def _load_coeffs(filename):
with open(filename) as f:
return json.load(f)
def _evaluate(coeffs, x):
return coeffs["a"] * x ** 2 + coeffs["b"] * x + coeffs["c"]
if __name__ == "__main__":
coeffs = _load_coeffs("coeffs.json")
output = [_evaluate(coeffs, x) for x in range(10)]
with ... |
"""
This module is pretty messy - it is still very much under active development and
will likely be changed a lot in the near future - don't depend on any of the
functionality currently defined!
"""
import wx
import re
import wx.lib.buttons
import wx.grid
import numpy
import os
import avoplot
from avoplot.series import... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: icx_ping
version_added: "2.9"
author: "Ruckus Wireless (@Commsc... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_policy_rule
short_description: Manage LTM policy rules o... |
import math
from collections import defaultdict
__all__ = [
"PermutedMNISTTaskIndices",
]
class PermutedMNISTTaskIndices:
"""
A mixin that overwrites `compute_task_indices` when using permutedMNIST to allow
for much faster dataset initialization. Note that this mixin may not work with
other datasets... |
from module import Module
from xml2aloe import MakeModule
import sys, os, getopt
argv = sys.argv
input_file = None
output_dir = None
try:
opts, args = getopt.getopt(argv,"hi:o:",["input_file=","output_dir="])
except getopt.GetoptError:
print argv[0] + ' -i <input_file> -o <output_dir>'
sys.exit(2)
for opt, arg... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README_LOCAL = open(os.path.join(here, 'README.rst')).read()
README_GLOBAL = open(os.path.join(here, 'README-NP.rst')).read()
requires = [
'setuptools',
'netprofile_entities >= 0.3',
'netprofile_hosts >= 0.3'
]
se... |
from misp2yara import mispevent2yara, mispattrs2yara, MISPRuleTemplate
import sys
import json
import os
from optparse import OptionParser
def rules2json_export(rules, extra_comment=''):
return json.dumps([rule2json_export(r) for r in rules])
def rule2json_export(rule, extra_comment=''):
json_dict = {
'v... |
from tests.util.base import dbloader, db, default_account |
import sys
from UM.Logger import Logger
try:
from . import ThreeMFWriter
except ImportError:
Logger.log("w", "Could not import ThreeMFWriter; libSavitar may be missing")
from . import ThreeMFWorkspaceWriter
from UM.i18n import i18nCatalog
from UM.Platform import Platform
i18n_catalog = i18nCatalog("uranium")
de... |
"""
This file contains celery tasks for sending email
"""
import logging
from celery import shared_task
from celery.exceptions import MaxRetriesExceededError
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.sites.models ... |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('ccx.tests.test_tasks', 'lms.djangoapps.ccx.tests.test_tasks')
from lms.djangoapps.ccx.tests.test_tasks import * |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('commerce.management.commands', 'lms.djangoapps.commerce.management.commands')
from lms.djangoapps.commerce.management.commands import * |
import os
import re
import subprocess
from pyload import PKGDIR
from pyload.core.utils.convert import to_str
from pyload.plugins.base.extractor import ArchiveError, BaseExtractor, CRCError, PasswordError
from pyload.plugins.helpers import renice
class UnRar(BaseExtractor):
__name__ = "UnRar"
__type__ = "extract... |
try:
from pyparsing import Literal, CaselessLiteral, Word, OneOrMore, ZeroOrMore, \
Forward, delimitedList, Group, Optional, Combine, alphas, nums, restOfLine, cStyleComment, \
alphanums, ParseException, ParseResults, Keyword, StringEnd, replaceWith
except ImportError:
print "Module pypa... |
from flumotion.common import testsuite
import os
import shutil
from flumotion.common import xdg
class TestXDGConfig(testsuite.TestCase):
def setUp(self):
self.old_home = os.environ.get('HOME')
self.old_xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
self.old_xdg_config_dirs = os.environ.... |
CommandlineUsage = """Material - Tool to work with FreeCAD Material definition cards
Usage:
Material [Options] card-file-name
Options:
-c, --output-csv=file-name write a comma seperated grid with the material data
Exit:
0 No Error or Warning found
1 Argument error, wrong or less Arguments given
Tool... |
from spack import *
class Dtcmp(Package):
"""The Datatype Comparison Library provides comparison operations and
parallel sort algorithms for MPI applications."""
homepage = "https://github.com/hpc/dtcmp"
url = "https://github.com/hpc/dtcmp/releases/download/v1.0.3/dtcmp-1.0.3.tar.gz"
version... |
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_protect
import approver.utils as utils
def error404(request):
context = {
'content': 'approver/404.html',
}
return utils.layout_render(request,context) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.