content stringlengths 4 20k |
|---|
#!/usr/bin/env python3
# Scrive il file di configurazione,
# con i dati ricevuti dal rispettivo "read*.py"
# Serve per controllare i files
import os
# Serve per il formato dati, il file di configurazione e`
# in struttura "json"
import json
# Serve per la parte di gestione html in python
import cgi
import cgitb
im... |
#!/usr/bin/env python
"""
Utility script used to set metadata on a collection after an upload.
Expects metadata in json format as in the adjoining metadata.json file. The format for an
individual subject looks like the following, and dates should be formatted as YYYY-MM-DD.
"023": {
"DOB": "2013-01-04",
"sc... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canale per eurostreaming.tv
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import urlparse
import re
import sys
from core impor... |
import re
from pseudo.code_generator import CodeGenerator, switch
from pseudo.middlewares import DeclarationMiddleware
JS_NAME = re.compile(r'[a-zA-Z][a-zA-Z_0-9]*')
OPS = {'not': '!', 'and': '&&', 'or': '||'}
def index_switch(i):
if i.index.type == 'string' and JS_NAME.match(i.index.value):
return 'strin... |
# This script is created to process attendance from a TechGirlz Event
# Get the .csv from EventBrite
#
# For each line
# Is this a new event? If yes then check if the person is already processed
# Get email (or Attendee name -- some key )
# Check if they are in there
# If yes, then increment their shows or... |
"""Collection search unit."""
from intbitset import intbitset
def search_unit(query, f, m, wl=None):
"""Search for records in collection query.
Example:
.. code-block:: text
collection:"BOOK"
collection:"Books"
"""
from invenio.legacy.search_engine import (
get_collecti... |
# -*- coding: utf-8 -*-
"""
test_django-watchman
------------
Tests for `django-watchman` views module.
"""
from __future__ import unicode_literals
import json
from _threading_local import local
from copy import copy
from django.db import connections
from django.db.utils import DEFAULT_DB_ALIAS
from django.test.te... |
"""Defines the settings dialog class for accessing the details of a Stack."""
import Tkinter
import tkFileDialog
import ventry
class StackSettings(Tkinter.Toplevel):
def __init__(self, master,
stack,
callback_update):
"""STACK is the matplotlayers.Stack to act upon."""
T... |
from js_helper import _do_test_raw, TestCase
def test_addEventListener():
"""Test that addEventListener gets flagged appropriately."""
err = _do_test_raw("""
x.addEventListener("click", function() {}, true);
x.addEventListener("click", function() {}, true, false);
""")
assert not err.failed()... |
from sos.plugins import Plugin, RedHatPlugin
class DistUpgrade(Plugin):
""" Distribution upgrade data """
plugin_name = "distupgrade"
profiles = ('system', 'sysmgmt')
files = None
class RedHatDistUpgrade(DistUpgrade, RedHatPlugin):
packages = (
'preupgrade-assistant',
'preupgr... |
import binascii
import hmac
import random
import time
import urllib.parse
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
# Generic exception class
class OAuthError(RuntimeError):
def __init__(self, message='OAuth error occured.'):
self.message = message
# o... |
from typing import Any, Optional, TYPE_CHECKING
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
from ._configuration import CdnManag... |
#!/usr/bin/env python
import sys
import collections
from tree import *
OpTypeNone = -1
OpTypeFloat = 0
OpTypeInt = 1
OpTypeName = 2
if_number = 0
def semantics(root):
stack = []
parseTreeWithRootNode(root, stack)
root.data = [' ', 'bye']
print ' '.join(root.build_stack_post())
def parseTreeWithRootNode(nod... |
import unittest
import PokeAlarm.Filters as Filters
import PokeAlarm.Events as Events
class TestEggFilter(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_egg_lvl(self):
# Create the filters
settings = {"min_egg_lvl": 2, "max_egg... |
__author__ = 'Vojda'
class User:
"""
This is the user class
"""
@classmethod
def from_dict(cls, object_dict):
return User(object_dict['username'], object_dict['password'], object_dict['admin'])
def __init__(self, username, password, admin=False):
self.username = username
... |
"""Builds user and group profiles using the steamwebapi"""
import re
import xml.etree.ElementTree as ET
from steamwebapi.api import ISteamUser, IPlayerService, ISteamUserStats, SteamCommunityXML
from steamwebapi.utils import gid_32_to_64_bit
class User(object):
VisibilityState = {1 : "Private", 2 : "Friends Only... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('catastro', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
"""bencode.py - bencode encoder + decoder."""
from bencode.BTL import BTFailure
from bencode.exceptions import BencodeDecodeError
from collections import deque
import sys
try:
from typing import Dict, List, Tuple, Deque, Union, TextIO, BinaryIO, Any
except ImportError:
Dict = List = Tuple = Deque = Union = T... |
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3,4,-4,... |
import os
import importlib
from .. import exceptions
def process(filename, **kwargs):
"""This is the core function used for parsing. It routes the filename
to the appropriate parser and returns the result.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise excepti... |
import unittest
import asyncio
import pickle
import aioredis
from unittest import mock
from aiorest.session import RedisSessionFactory
class RedisSessionTests(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.redis_pool = self.lo... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolSpendCoinbaseTest(BitcoinTestFramework):
def setup_network(self):
# Just need one node for this test
args = ["-debug=mempool"]
s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
#!/usr/bin/env python -Wd
import sys
import warnings
import django
from django.core.management import execute_from_command_line
from django.conf import settings, global_settings as default_settings
from os import path
# python -Wd, or run via coverage:
warnings.simplefilter('always', DeprecationWarning)
# Give feedba... |
#!/usr/bin/env python3
"""
Add explorer preview to file endings (textfiles)
"""
import argparse
import winreg
__version__ = 1.0
hRoot = winreg.HKEY_CLASSES_ROOT
nCont = "Content Type"
vCont = "text/plain"
nPerc = "PerceivedType"
vPerc = "text"
tStrg = winreg.REG_SZ
def getArguments():
parser = argparse.ArgumentP... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nta/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expdes... |
#!/usr/bin/python
import praw
from pprint import pprint
import networkx as nx
# try:
# import matplotlib.pyplot as plt
# except:
# raise
def recCommentGrab(graph, comment, parent, level, sub):
if ( isinstance(comment, praw.objects.MoreComments) ):
return
if ( comment.author == None ):
return
author... |
'''
Created on Jan 5, 2020
@author: johnrabsonjr
'''
import os
import sys
sys.path.append('/root/fonsa/src') # @NoMove
from my.boston.getandset import get_mdadm_output
from my.classes import ReadWriteLock
class RaidInternals:
"""The RAID Internals class.
RAIDInternals() is a class that wraps around Linux... |
import uuid
import mock
import six
import webob
import webob.exc
from ooi.api import compute
from ooi.api import helpers
from ooi import exception
from ooi.occi.core import collection
from ooi.occi.infrastructure import compute as occi_compute
from ooi.openstack import contextualization
from ooi.openstack import temp... |
"""
Helpers for testing based on command output capture.
"""
import urllib
import hashlib
import os
import sys
import pexpect
class FilteredOutputFile(object):
@staticmethod
def python_threaded_exit_crash_filter(text):
lines = text.split("\n")
res = []
for line in lines:
... |
from lib.cuckoo.common.abstracts import Signature
class FynloskiMutexes(Signature):
name = "rat_fynloski_mutexes"
description = "创建常见Fynloski/DarkComet互斥量(mutexes)"
severity = 3
categories = ["rat"]
families = ["fynloski"]
authors = ["threatlead"]
references = ["https://malwr.com/analysis/O... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import sys
import pkutils
from os import path as p
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
PARENT_DIR = p.abspath(p.dir... |
"""Contains model definitions for versions of the Oxford VGG network.
These model definitions were introduced in the following technical report:
Very Deep Convolutional Networks For Large-Scale Image Recognition
Karen Simonyan and Andrew Zisserman
arXiv technical report, 2015
PDF: http://arxiv.org/pdf/1409.15... |
import os
import shutil
import sys
import tempfile
from pyasn1.compat.octets import str2octs
from pysnmp.proto.rfc3412 import MsgAndPduDispatcher
from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, SnmpV2cMessageProcessingModel
from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel
from py... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
import math
from concise.preprocessing.sequence import DNA, RNA, AMINO_ACIDS
from concise.utils.letters import all_letters
from collections import OrderedDict
from matpl... |
import logging
from urllib import urlencode
from ckan import plugins as p
from ckan.lib.base import c, model, request, render, h, g
from ckan.lib.base import abort
import ckan.lib.maintain as maintain
import ckan.lib.search as search
from ckan.controllers.group import GroupController
from ckanext.harvest.plugin impo... |
"""API for Home Connect bound to HASS OAuth."""
from asyncio import run_coroutine_threadsafe
import logging
import homeconnect
from homeconnect.api import HomeConnectError
from homeassistant import config_entries, core
from homeassistant.const import DEVICE_CLASS_TIMESTAMP, TIME_SECONDS, UNIT_PERCENTAGE
from homeass... |
"""Middleware to replace the plain text message body of an error
response with one formatted so the client can parse it.
Based on pecan.middleware.errordocument
"""
import json
from lxml import etree
import webob
from ceilometer.api import hooks
from ceilometer.openstack.common import gettextutils
from ceilometer.o... |
"""
setup.py
If you run this script, it should install the pcsets library
to your Python distribution's site libraries.
"""
__metaclass__ = type
from setuptools import setup, find_packages
PCSETS_VERSION = '2.0.2' # <===================== (auto-substituted)
DESCRIPTION = 'Pitch Class Sets for Python.'
with ope... |
"""Test remote backup functions."""
import subprocess
from unittest import mock
from snapintime import remote_backup
@mock.patch('snapintime.remote_backup.subprocess')
def test_get_remote_latest_subvol(subprocess_mock):
subprocess_done = subprocess.CompletedProcess(args="args", returncode=0, stdout="2020-02-11\... |
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
# create planes
# Create the RenderWindow, Renderer
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer( ren )
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create pipeline
#
pl3d = vtk.vtkMulti... |
"""Test class for baremetal IPMI power manager."""
import os
import stat
import tempfile
from oslo.config import cfg
from nova import test
from nova.tests.virt.baremetal.db import utils as bm_db_utils
from nova import utils
from nova.virt.baremetal import baremetal_states
from nova.virt.baremetal import ipmi
from no... |
from django.test import TestCase
from django.urls import reverse
from django.utils.translation import activate
from faker import Faker
from ..forms import ApplicationForm
class ApplicationFormTests(TestCase):
def test_form_valid(self):
fake = Faker()
form_data = {
'answer_idea_1': fak... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Session, SessionLogStep, AgentLogStep
from django.utils.html import format_html
from django.core.urlresolvers import reverse
class AgentLogStepInline(admin.TabularInline):
model = AgentLogStep
fk_name = 'vmmaster_log_step'
def... |
import argparse
import codecs
import os
import re
import sys
import git
CONTRIBUTORS_HEAD = (
'''# This is the list of people who have contributed to this project,
# and includes those not listed in AUTHORS.txt because they are not
# copyright authors. For example, company employees may be listed
# here because t... |
"""
ts_autosign.py: Autosign tests for the test.py test suite
"""
import os,shutil
from subprocess import run
from mmgen.globalvars import g
from mmgen.opts import opt
from ..include.common import *
from .common import *
from .ts_base import *
from .ts_shared import *
from .input import *
class TestSuiteAutosign(Te... |
import rev2
import os
import signal
import subprocess
import json
import sys
from django.test import LiveServerTestCase, TestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
class FunctionalTest(StaticLiv... |
#! /usr/bin/env python
from __future__ import print_function
from openturns import *
from openturns.testing import *
TESTPREAMBLE()
PlatformInfo.SetNumericalPrecision(3)
# Kriging use case
spatialDimension = 2
# Learning data
levels = [8., 5.]
box = Box(levels)
inputSample = box.generate()
# Scale each direction
in... |
import functools
import warnings
import operator
import types
from . import numeric as _nx
from .numeric import result_type, NaN, asanyarray, ndim
from numpy.core.multiarray import add_docstring
from numpy.core import overrides
__all__ = ['logspace', 'linspace', 'geomspace']
array_function_dispatch = functools.part... |
import os
import functools
from collections import namedtuple, defaultdict
#
import pylab
#
import crosscat.utils.data_utils as du
import crosscat.utils.xnet_utils as xu
from crosscat.LocalEngine import LocalEngine
import crosscat.cython_code.State as State
import crosscat.tests.plot_utils as pu
import experiment_runne... |
import pytest
import aiohttp
from server.core.clients.gitlab_client import GitLabClient, GitLabMergeState, GitLabWebHook
async def test_glitab_get_ssh_url(loop, fixture_fake_gitlab_server):
server, port = await fixture_fake_gitlab_server
git_client = GitLabClient(marker="test_marker", base_url="http://%s:%d" ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'ImportShard.task'
db.delete_column(u'osmosis_importshar... |
def getTimesheetsFromZendesk(templateQueryContext):
# --- setup zendesk settings ---
serverURL = "https://yourZendeskHost"
userName = "yourUserName"
token = "yourZendeskToken"
# --- setup zendesk settings ---
clr.AddReference("System.Web")
clr.AddReference("System.Net.Http")
clr.AddReference("Newtonsoft.Json")... |
import chardet
import email
import os
def read_content_file(dirpath):
"""(str): (str, email.Message)
Given a directory path, figure out the file holding the content
for that directory and parse it as an email message.
Copied from old Python.org build process.
"""
# Read page content
c_ht ... |
"""Bytecode manipulation for coverage.py"""
import opcode
import types
from coverage.backward import byte_to_int
class ByteCode(object):
"""A single bytecode."""
def __init__(self):
# The offset of this bytecode in the code object.
self.offset = -1
# The opcode, defined in the `opco... |
import os
import sys
try:
from setuptools import setup, find_packages
from setuptools.extension import Extension
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
from distutils.core import setup, find_packages
from distutils.extension imp... |
from dolfin import *
from scipy.optimize import minimize
import numpy as np
import time as pyt
import pprint
coth = lambda x: 1./np.tanh(x)
from fenicsopt.core.convdif import *
from fenicsopt.examples.sc_examples import sc_setup
import fenicsopt.exports.results as rs
##################################################... |
import unittest
from gosa.backend.objects.comparator.basic import Equals, Greater, Smaller
class BasicComparatorTests(unittest.TestCase):
def test_equals(self):
comp = Equals()
(result, errors) = comp.process(None, None, ["test","test"], "test")
assert result is True
assert len(er... |
from datetime import date, datetime
from pyspark.sql.types import Row, StructType, StructField, IntegerType, StringType, TimestampType, DateType, DoubleType, ShortType, ByteType, BooleanType, BinaryType, FloatType, LongType
# Don Drake
# <EMAIL>
class SmartFrames(object):
schema = None
skipSelectFields = []
... |
""" The MIT License (MIT)
Copyright (c) 2016 Kyle Hollins Wray, University of Massachusetts
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 ... |
"""Wrappers for protocol buffer enum types."""
import enum
class LaunchStage(enum.IntEnum):
"""
The launch stage as defined by `Google Cloud Platform Launch
Stages <http://cloud.google.com/terms/launch-stages>`__.
Attributes:
LAUNCH_STAGE_UNSPECIFIED (int): Do not use this default value.
... |
import bpy
from io_scene_cs.utilities import rnaType, rnaOperator, B2CS, BoolProperty
from io_scene_cs.utilities import RemovePanels, RestorePanels
def active_node_mat(mat):
if mat is not None:
mat_node = mat.active_node_material
if mat_node:
return mat_node
else:
return mat
... |
"""
Django settings for cryptofolio project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
impor... |
#! /usr/bin/python
# coding: utf-8
'''
Add queues to Mininet using ovs-vsctl and ovs-ofctl
@Author Ryan Wallner
'''
import os
import sys
import time
import subprocess
def find_all(a_str, sub_str):
start = 0
b_starts = []
while True:
start = a_str.find(sub_str, start)
if start == -1: retu... |
from tempest.api.compute.floating_ips import base
from tempest.common.utils import data_utils
from tempest import config
from tempest.lib import exceptions as lib_exc
from tempest import test
CONF = config.CONF
class FloatingIPsNegativeTestJSON(base.BaseFloatingIPsTest):
server_id = None
@classmethod
de... |
from experiment_construction.evaluator_construction.evaluation import Evaluation
import numpy as np
class Evaluator:
gold_reader = None
logger = None
method = None
def __init__(self, gold_reader, cutoff, logger, method="macro"):
self.gold_reader = gold_reader
self.logger = logger
... |
import os
import fnmatch
import subprocess
def find(pattern, classPaths):
paths = classPaths.split(os.pathsep)
# for each class path
for path in paths:
# remove * if it's at the end of path
if ((path is not None) and (len(path) > 0) and (path[-1] == '*')) :
path = path[:-1]
... |
#!/usr/bin/env python3
###
###
###
### Jesse Leigh Patsolic
### 2017 <<EMAIL>>
### S.D.G
#
import argparse
import math
from intern.remote.boss import BossRemote
from intern.resource.boss.resource import *
import configparser
#import grequests # for async requests, conflicts with requests somehow
import requests
imp... |
"""## Hashing
String hashing ops take a string input tensor and map each element to an
integer.
@@string_to_hash_bucket_fast
@@string_to_hash_bucket_strong
@@string_to_hash_bucket
## Joining
String joining ops concatenate elements of input string tensors to produce a new
string tensor.
@@reduce_join
@@string_join
... |
"""A library of functions that help with causal masking."""
# internal imports
import tensorflow as tf
def mul_or_none(a, b):
"""Return the element wise multiplicative of the inputs.
If either input is None, we return None.
Args:
a: A tensor input.
b: Another tensor input with the same type as a.
... |
"""Matcher core."""
import copy
import six
from flask import current_app
from invenio_records import Record
from .engine import exact, free, fuzzy
from .errors import InvalidQuery, NoQueryDefined, NotImplementedQuery
from .models import MatchResult
def execute(index, doc_type, query, record, **kwargs):
"""Pars... |
from settings import *
import logging
INTERNAL_IPS = ('127.0.0.1', '192.168.10.1',)
# ALLOWED_HOSTS must be set whenever DEBUG = False
ALLOWED_HOSTS = '*'
DEBUG = True
DEV = True
TEMPLATE_DEBUG = DEBUG
SERVE_MEDIA = DEBUG
SESSION_COOKIE_SECURE = True
DEMO_UPLOADS_ROOT = '/home/vagrant/uploads/demos'
DEMO_UPLOADS_U... |
import numpy as np
from numpy import dot
from prototype.utils.utils import deg2rad
from prototype.utils.euler import euler2rot
# from mpl_toolkits.mplot3d.art3d import Line3DCollection
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
def axis_equal_3dplot(ax):
extents = np.array([getattr(ax, 'get_{}lim'.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import collections
from django.db import migrations
import mptt
import mptt.managers
def copy_regulations(apps, schema_editor):
Regulation = apps.get_model('regcore', 'Regulation')
Document = apps.get_model('regcore', 'Document')
for reg i... |
import importlib
import inspect
import logging
import pkgutil
from collections import defaultdict
from cloudbridge.cloud import providers
from cloudbridge.cloud.interfaces import CloudProvider
from cloudbridge.cloud.interfaces import TestMockHelperMixin
log = logging.getLogger(__name__)
class ProviderList(object):... |
import re
class DialplanParsingError(Exception):
pass
class DialplanParser(object):
def parse(self, fobj):
parse_result = self._do_parse(fobj)
parse_result.filename = '<fobj>'
return parse_result
def parse_file(self, filename):
with open(filename) as fobj:
pa... |
#!python
import os
import argparse
import yaml
import gdown
import tarfile
import prisim
prisim_path = prisim.__path__[0]+'/'
tarfilename = 'prisim_data.tar.gz'
def download(url=None, outfile=None, verbose=True):
if url is not None:
if not isinstance(url, str):
raise TypeError('Input url must... |
"""Check options for all agents."""
import logging
import pytest
from DIRAC.tests.Utilities.assertingUtils import AgentOptionsTest
from DIRAC import S_OK
AGENTS = [('DIRAC.AccountingSystem.Agent.NetworkAgent', {'IgnoreOptions': ['MaxCycles', 'MessageQueueURI',
... |
import numpy as nm
##
# c: 05.05.2008, r: 05.05.2008
eps = 1e-12
def set_accuracy( eps ):
globals()['eps'] = eps
##
# c: 18.10.2006, r: 05.05.2008
def match_grid_line( coor1, coor2, which ):
if coor1.shape != coor2.shape:
raise ValueError, 'incompatible shapes: %s == %s'\
% ( coor1.shape... |
import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Question
def create_question(question_text, days):
"""
Creates a question with the given `question_text` and published the
given number of `days` offset to now (negati... |
import unittest
import sys
import os
sys.path.append(os.path.join('..\..', 'src'))
from backend.db.db_obj import DBObject
class DBObjectTest(unittest.TestCase):
def setUp(self):
self.test_db_obj = DBObject()
self.id_str = "1234"
def test_id_not_set_on_init(self):
self.assertFalse(sel... |
#coding:utf-8
from db.mysql import NovaDatabase
from db.common import NovaDBConfig
from base import PlatformManager
from exception import RequestError, LoginCServerFailed
from platforms.cserver.session import CServerAPISession
from platforms.cserver.cserverplatform import CServerPlatformInstanceInfo
import uuid
from d... |
def Setup(Settings, DefaultModel):
# set5-osm-model-variable-widths-depths/set5_w256_depth4_d1.py
Settings["experiment_name"] = "set5_w256_depth4_d1"
Settings["graph_histories"] = [] # ['all','together',[],[1,0],[0,0,0],[]]
n = 0
#d1 5556x_markable_640x640 SegmentsData_marked_R100... |
from molecule.driver import base
from molecule import util
class Linode(base.Base):
"""
The class responsible for managing `Linode`_ instances. `Linode`_
is `not` the default driver used in Molecule.
Molecule leverages Ansible's `linode_module`_, by mapping variables
from ``molecule.yml`` into ... |
try:
from cs import CloudStack, CloudStackException, read_config
has_lib_cs = True
except ImportError:
has_lib_cs = False
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackTemplate(AnsibleCloudStack):
def __init__(self, module):
super(AnsibleClou... |
"""
The comannd module provides a small CLI utility that allows detection of image
features directly in the command line. This module is built using the Click
library.
"""
import click
import logging
import pandas as pd
from skimage import transform
import mia
from mia.reduction.reducers import *
logging.basicConfi... |
from django.conf import settings
from social.backends.appdotnet import AppDotNetOAuth2
class MXMLAppDotNetOAuth2(AppDotNetOAuth2):
# TODO figure out what actual constants to distribute, we can't use PARENT_HOST here
# AUTHORIZATION_URL = "%s/oauth/authenticate" % settings.SOCIAL_AUTH_APPDOTNET_OAUTH_BASE
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Device) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class Device(domainresource.DomainResource):
""" Item used in healthcare.
A type of a manufacture... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import ieee802_15_4_swig as ieee802_15_4
class qa_frame_buffer_cc (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self):
# set up fg
pr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import challenges.models
from django.conf import settings
from datetime import date
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_U... |
import numpy as np
import philipp as p
import kordian as k
import anna as a
import parser
import sys
import itertools
def print_combination(combination):
used_caches = sorted([k for k,v in combination.items() if v[0]!=0])
print(len(used_caches))
for used_cache in used_caches:
videos_str = " ".join(... |
import numpy
class TimeAxis:
def __init__(self, timescale):
self.timescale = timescale
def _get_time(self):
return numpy.arange(-300.0/50*self.timescale, 300.0/50*self.timescale, self.timescale/50.0)
def get_time_axis(self):
time = self._get_time()
if (time[59... |
# -*- coding: utf-8 -*-
import datetime
import functools
import logging
import urllib
import markdown
import pytz
from addons.base.models import BaseNodeSettings
from bleach.callbacks import nofollow
from django.db import models
from django.utils import timezone
from framework.forms.utils import sanitize
from markdown... |
from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey
from sqlalchemy import Integer, MetaData, String, Table, Text
from senlin.db.sqlalchemy import types
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
profile = Table(
'profile', meta,
Column('id',... |
import sys
__all__ = ['AutoFinalizedObject']
class _AutoFinalizedObjectBase(object):
"""
Base class for objects that get automatically
finalized on delete or at exit.
"""
def _finalize_object(self):
"""Actually finalizes the object (frees allocated resources etc.).
Returns: None... |
# -*- coding: utf-8 -*-
import tkinter as Tk
from PIL import Image, ImageDraw, ImageTk, ImageEnhance
import os
import time
from Entity import Player, Monster
__author__ = 'Yoann'
# *****************************************************************************
# ** Classe dérivant du Player po... |
#!/bin/env python
"""
#######################################################################
# #
# Copyright (c) 2012, Prateek Sureka. All Rights Reserved. #
# This module provides an idempotent mechanism to remotely configure #
# web prox... |
"""Targets class describes which languages/platforms we support."""
__author__ = '<EMAIL> (Will Clarkson)'
import os
from googleapis.codegen.anyjson import simplejson
class Selection(object):
"""Represents a selection of one target."""
def __init__(self, api_name, api_version, language, platform,
... |
import urlparse
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, QueryDict
from django.template.response import TemplateResponse
from django.utils.http import base36_to_int
from django.utils.translation import ugettext as _
from django.views.de... |
from django.forms import *
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.encoding import StrAndUnicode, force_unicode
import httplib, urllib
class RecaptchaWidget(Widget):
def __init__(self, theme=None, tabindex=None):
'''
From http://reca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.