content stringlengths 4 20k |
|---|
import re
import os
import glob
import sys
import platform
processlib_includes = set()
processlib_dirs = ['core',
'tasks',
]
def init() :
base_script_path,_ = os.path.split(os.path.realpath(__file__))
for processlib_include_path in processlib_dirs:
includes = glob.gl... |
import logging
from coapthon import defines
from coapthon.messages.request import Request
from coapthon.messages.response import Response
logger = logging.getLogger(__name__)
__author__ = 'Giacomo Tanganelli'
class BlockItem(object):
def __init__(self, byte, num, m, size, payload=None, content_type=None):
... |
#!/usr/bin/env python
# coding: utf-8
# Advanced: passband versioning & updates
# ==============================
# Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
# In[1]:
#!pip install -I "phoebe>=2.3,<2.4"
# ... |
import os
import glob
from django.conf import settings
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import Instance
from onadata.apps.logger.import_tools import import_instances_from_zip
CUR_PATH = os.path.abspath(__file__)
CUR_DIR = os.path.dirname(CUR_PATH)
DB_FIXTURES_PAT... |
'''
Created on Dec 3, 2012
@author: yupeng
'''
import nltk
import dynamic_pcfg
from nltk import *
from nltk.corpus import treebank
from nltk.treetransforms import *
"""
This file contains some useful utilities for probabilistic parsing in Lab 2.
"""
def learn_treebank(files=None, markov_order=None):
"""
... |
"""
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the p... |
# lib for vkstore stuff
# -*- coding: utf-8 -*-
__version__ = "$Id$"
__author__ = 'Jeroen Baten'
__copyright__ = "Copyright 2016, Deltares"
import sys
import os
# add current working directory to PYTHONPATH to be able to find models
sys.path.insert(0, os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ic... |
import json
from PyQt5.QtWidgets import QWidget
import tribler_core.utilities.json_util as json
from tribler_gui.tribler_request_manager import TriblerNetworkRequest
from tribler_gui.utilities import format_votes
class SubscriptionsWidget(QWidget):
"""
This widget shows a favorite button and the number of ... |
f = CurrentFont()
g = CurrentGlyph()
layer = Glyphs.font.selectedLayers[0] # current layer
def draw_circle(xxx_todo_changeme, diameter):
(origin_x, origin_y) = xxx_todo_changeme
pen = g.getPen()
d = diameter #diameter
r = d / 2 #radius
h = r * 0.55229 #handle size
x0, y0 = origin_x, origin_y #origin
#sinc... |
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from django.template import Template, Context
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from wagtail.tests.utils import WagtailTestUtils
... |
#!/usr/bin/python
import random
import datetime
import os
scriptname = os.path.basename(__file__)
"""
Copyright (c) 1987-2014 by Frank Holger Rothkamm. Forth/Coldfusion/Python
psychostochastics - Classic Csound - humanized random distributions
--------------------------------------------------------------... |
#encoding:utf-8
"""
pythoner.net
Copyright (C) 2013 PYTHONER.ORG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program... |
'''This file generates shell code for the setup.SHELL scripts to set environment variables'''
from __future__ import print_function
import argparse
import copy
import errno
import os
import platform
import sys
CATKIN_MARKER_FILE = '.catkin'
system = platform.system()
IS_DARWIN = (system == 'Darwin')
IS_WINDOWS = (sy... |
# -*- coding: iso-8859-1 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para linkbucks
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re, sys
import urlparse, urllib, urllib2
from... |
'''
Learn how to setup and use DeviceDaemon and DeviceService to readout input data
from a HIDInput device.
This example manipulates the position of a displayed sphere
based on the output the device specified in mouse-daemon.py generates.
'''
import avango.daemon
import avango.script
import avango.osg.simpleviewer
#... |
#!/usr/bin/env python
# -*- coding:UTF-8
from ssj.lib.queue import Queue
__author__ = 'shenshijun'
"""
一个使用邻接链表实现的带权有有向图
"""
class Node(object):
"""
带权图的中存储元素的节点
"""
def __init__(self, key, weight):
"""Constructor for """
self.key = key
self.weight = weight
def __cmp__(s... |
"""This module is deprecated. Please use :mod:`airflow.providers.papermill.operators.papermill`."""
import warnings
from airflow.providers.papermill.operators.papermill import PapermillOperator # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.papermill.operators.papermill`.",
... |
"""Check symbol names against Unicode character names.
Verify that
- for symbols unified with existing characters the names match
- for new symbols the names are different from existing ones
- for new symbols the names are unique
"""
__author__ = "Markus Scherer"
import re
import unittest
import emoji4unicode
import... |
# coding=utf8
import colorsys
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import BooleanField, ForeignKey
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from frontend.models import Presentation
from .mo... |
import os
import subprocess
import sys
import click
from polyaxon.cli.errors import handle_cli_error
from polyaxon.deploy.operators.conda import CondaOperator
from polyaxon.exceptions import (
PolyaxonClientException,
PolyaxonException,
PolyaxonHTTPError,
PolyaxonShouldExitError,
)
from polyaxon.utils... |
import bson.json_util
import re
import six
from pymongo import MongoClient
from girder import logger as log
from . import base
from .base import DatabaseConnectorException
MongoOperators = {
'eq': '$eq',
'ne': '$ne',
'gt': '$gt',
'gte': '$gte',
'lt': '$lt',
'lte': '$lte',
'in': '$in',
... |
import sys, os, warnings, logging, argparse
warnings.simplefilter("ignore", DeprecationWarning)
from ncclient import manager
LEVELS = {
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'critical':logging.CRITICAL,
... |
import numpy as np
from gpaw.utilities import fact
from gpaw.sphere import lmfact
from gpaw.sphere.legendre import ilegendre, legendre, dlegendre
# Define the Heaviside function
heaviside = lambda x: (1.0+np.sign(x))/2.0
# Define spherical harmoncics and normalization coefficient
C = lambda l,m: (-1)**((m+abs(m))//2... |
import logging
import webob
import webob.dec
import webob.exc
from routes.middleware import RoutesMiddleware
from ztpserver.serializers import dumps
from ztpserver.constants import CONTENT_TYPE_HTML, HTTP_STATUS_OK
log = logging.getLogger(__name__)
class WSGIController(object):
def index(self, request, **kwar... |
import re
from collections import OrderedDict
from . import core
from ...extern import six
from ...table import Table
from . import cparser
from ...extern.six.moves import zip
from ...utils import set_locale
@six.add_metaclass(core.MetaBaseReader)
class FastBasic(object):
"""
This class is intended to handle ... |
"""
Provides widget classes and functions.
.. warning:: All PyQt4/PySide gui classes are exposed but when you use
PyQt5, those classes are not available. Therefore, you should treat/use
this package as if it was ``PyQt5.QtWidgets`` module.
"""
import os
from . import QT_API
from . import PYQT5_API
from . impor... |
#!/usr/bin/env python
#-*- coding=utf-8 -*-
#通过header中的信息获取网页声明的编码格式
import urllib
url_list = ["http://www.163.com","http://www.jd.com","http://www.baidu.com","http://www.youku.com"]
for url in url_list:
print url
html_info = urllib.urlopen(url).info()
# print html_info
# print dir(html_info)
#参看htm... |
import time
import pytest
from trezorlib import device, messages as proto
from .common import TrezorTest
@pytest.mark.skip_t1
class TestMsgRecoverydeviceT2(TrezorTest):
def test_pin_passphrase(self):
mnemonic = self.mnemonic12.split(" ")
ret = self.client.call_raw(
proto.RecoveryDev... |
"""Implementation of gcloud genomics readgroupsets describe.
"""
from googlecloudsdk.api_lib import genomics as lib
from googlecloudsdk.api_lib.genomics import genomics_util
from googlecloudsdk.calliope import base
class Describe(base.Command):
"""Returns details about a read group set.
"""
@staticmethod
de... |
"""GEMM Convolution schedule on ARM"""
import tvm
from tvm import te
from tvm.topi import nn
from tvm.autotvm.task.space import AnnotateEntity, ReorderEntity, OtherOptionEntity
from ..util import get_const_tuple, get_const_int
from ..nn.util import get_pad_tuple
from .tensor_intrin import (
gemm_quantized,
gemm... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import *
import sys
import datetime
datafile="life_acc_mpi.out"
if len(sys.argv) > 1:
datafile=sys.argv[1]
plotfile=datafile+".png"
data = loadtxt(datafile)
today = datetime.date.today()
fig = plt.figure() # apre una nuova figura... |
import mxnet as mx
import numpy as onp
from mxnet import gluon, autograd
from mxnet.test_utils import assert_almost_equal, default_context
from numpy.core.fromnumeric import size
from common import xfail_when_nonstandard_decimal_separator
import unittest
@mx.util.use_np
@xfail_when_nonstandard_decimal_separator
def t... |
from CThread import *
from globalfunctions import getScriptDirs, getServerConnection
class BackgroundRoutineRunner(CThread):
def __init__(self, routine):
CThread.__init__(self)
self.routine = routine
self.setName(routine.__class__.__name__)
def run(self):
self.routine.call_run... |
"""
Abstraction of CLI Input.
"""
from __future__ import unicode_literals
from .utils import DummyContext, is_windows
from abc import ABCMeta, abstractmethod
from six import with_metaclass
import os
import sys
if is_windows():
from .terminal.win32_input import raw_mode, cooked_mode
else:
from .terminal.vt100... |
import unittest
from unittest import mock
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.batch_client import AwsBatchClientHook
from airflow.providers.amazon.aws.operators.batch import AwsBatchOperator
# Use dummy AWS credentials
AWS_REGION = "eu-west-1"
AWS_ACCESS_KEY_ID = "a... |
import os
from struct import unpack_from
import subprocess
__author__ = '<EMAIL> (Stephane Thiell)'
def vpd_decode_pg83_lu(pagebuf):
"""
Get the addressed logical unit address from the device identification
VPD page buffer provided (eg. content of vpd_pg83 in sysfs).
"""
vpd_assoc_lu = 0
sz =... |
# $language = "python"
# $interface = "1.0"
import os
import sys
import logging
import csv
# Add script directory to the PYTHONPATH so we can import our modules (only if run from SecureCRT)
if 'crt' in globals():
script_dir, script_name = os.path.split(crt.ScriptFullName)
if script_dir not in sys.path:
... |
# -*- coding: utf-8 -*-
"""
Validator classes for individual strings.
"""
import re
from polib import escape # TODO: Fix the regex
from django.conf import settings
from django.utils.translation import ugettext as _
from transifex.txcommon import import_to_python
class ValidationError(Exception):
pass
cl... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
Autore: Amedeo Salvati
email: <EMAIL>
Copyright (C) 2014 Amedeo Salvati. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Pub... |
import os
import sys
import tempfile
import unittest
from datetime import date
from copy import deepcopy
from pyprint.ConsolePrinter import ConsolePrinter
from coalib.output.ConfWriter import ConfWriter
from coala_quickstart.coala_quickstart import _get_arg_parser
from coala_quickstart.generation.Settings import writ... |
from spack import *
class PyPymatgen(PythonPackage):
"""Python Materials Genomics is a robust materials analysis code that
defines core object representations for structures and molecules with
support for many electronic structure codes. It is currently the core
analysis code powering the Materials Pr... |
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" executio... |
# Added Fortran compiler support to config. Currently useful only for
# try_compile call. try_run works but is untested for most of Fortran
# compilers (they must define linker_exe first).
# Pearu Peterson
from __future__ import division, absolute_import, print_function
import os, signal
import warnings
import sys
fr... |
import xbmcgui
import urllib
import time
def download(url, dest, dp = None):
if not dp:
dp = xbmcgui.DialogProgress()
dp.create("Status...","Downloading Content",' ', ' ')
dp.update(0)
start_time=time.time()
urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_... |
from sqlalchemy import Column
from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.orm import relationship
from sqlalchemy import String
from nailgun.db.sqlalchemy.models.base import Base
from nailgun.db.sqlalchemy.models.fields import JSON
c... |
"""The grid class allows graphs to be arranged in a regular grid.
The graphs may share axes if they are stored in the grid widget.
"""
from .. import document
from .. import setting
from .. import qtall as qt
from . import widget
from . import graph
from . import controlgraph
def _(text, disambiguation=None, context... |
# -*- coding: utf-8 -*-
import hashlib
from urllib.parse import quote, urlunparse
from base64 import urlsafe_b64encode
from ._version import __version__
class UrlHelper(object):
"""
Helper class to create single domain imgix URLs. Example:
>>> str(UrlHelper('demos.imgix.net', '/bridge.png', params={'w... |
from flask import Blueprint, abort, request
from watchDB import watchSession, watch, watchManager, block, zone
import time, json
from random import randrange
watchAPI = Blueprint('watchAPI', __name__,
template_folder='templates')
savepath="../uploads/"
@watchAPI.route('/')
def show():
... |
import datetime
from django.conf import settings
from django.test import TestCase
from django.utils import timezone
from ..models import convert_tstamp
from .. import settings as app_settings
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1... |
from dmutils.audit import AuditTypes
from flask import jsonify, abort, request, current_app
from sqlalchemy.exc import IntegrityError
from sqlalchemy import asc
from sqlalchemy.types import String
from .. import main
from ... import db
from ...utils import drop_foreign_fields, json_has_required_keys
from ...validatio... |
from __future__ import division, absolute_import, print_function, unicode_literals
from awlsim.common.compat import *
from awlsim.core.instructions.main import * #@nocy
from awlsim.core.operators import *
#from awlsim.core.instructions.main cimport * #@cy
class AwlInsn_SSD(AwlInsn): #+cdef
__slots__ = ()
def __i... |
# -*-coding:Utf-8 -*
from abcmodels import AModel
from mplotlab.utils.abctypes import STRING,INT,RegisterType
import socket
from numpy import *
class ASource(AModel):
CallLater=None
# wx.CallLater(time_in_ms,callable)
def __init__(self,*a,**k):
AModel.__init__(self,*a,**k)
... |
import random
import names
import csv
from django.db import IntegrityError
from django.template.defaultfilters import slugify
from orcamentos.utils.gen_random_values import gen_string
from orcamentos.crm.models import Employee, Customer, Person, Seller, Occupation
from orcamentos.proposal.models import Entry, Work
from... |
#!/usr/bin/env python
# Shine.Lustre.Server test suite
# Written by A. Degremont 2009-08-03
"""Unit test for Server"""
import unittest
import socket
from Shine.Lustre.Server import Server, ServerGroup
# No direct dependancies to NodeSet. This should be fixed.
from ClusterShell.NodeSet import NodeSet
class ServerTe... |
import sys
import json
import types
from os import path
import artifacts
from templates import TaskTemplate
class ConfigError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
class DatamakeConfig(object):
def __init__(self):
self.config =... |
#!/usr/bin/python
"""
Name: pytonLineCounter.py (originally plc.py)
Purpose: A Python line counter. Reports how many lines are in the given
input files, broken down into code, comment and blank lines.
Author: Wayne Koorts
Created: 31/03/2009
Copyright: Copyright 2009 Wayne Koorts
Licence:... |
#coding=utf-8
"""
Django settings for ttsx project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
#... |
import res_company
import stock
import wizard |
__author__ = 'Tom Schaul, <EMAIL>'
from scipy import array, zeros
from random import random
from maze import MazeTask
from pybrain.rl.environments.mazes import PolarMaze
class ShuttleDocking(MazeTask):
"""
#######
#. *#
#######
The spaceship needs to dock backwards into the goal station.
... |
"""
This file contains graph integration tests
"""
import unittest
from configuration.config import Config
from data_structures.graph import Graph
from utils.helpers import get_full_class_name
try:
from mock import patch, mock_open, mock, PropertyMock
except ImportError:
from unittest.mock import patch, mock_... |
# Zulip Settings intended to be set by a system administrator.
#
# See http://zulip.readthedocs.io/en/latest/settings.html for
# detailed technical documentation on the Zulip settings system.
#
### MANDATORY SETTINGS
#
# These settings MUST be set in production. In a development environment,
# sensible default values w... |
import unittest
import rospy
import rostest
import sys
from std_msgs.msg import *
class LatchedSub(unittest.TestCase):
def msg_cb(self, msg):
self.success = True
def test_latched_sub(self):
rospy.init_node('random_sub')
self.success = False
rospy.sleep(rospy.Duration.from_sec(5.0))
sub = ... |
import unittest
import subprocess
import tempfile
from os import mkdir
from os.path import abspath, dirname, join
from integrationtest_support import IntegrationTestSupport
class Test (IntegrationTestSupport):
def test(self):
test_dir = tempfile.mkdtemp()
self.write_stub_configurations_json_fil... |
"""
-------------------------------------------------------------------------------
Name: test module
Purpose: test purpose
Idea: how to solve it
Author: Tian Zhou
Email: zhou338 [at] purdue [dot] edu
Created: 19/11/2015
Copyright: (c) Tian Zhou 2015
----------------------------------... |
from django.db import models, migrations
import datetime
import django.db.models.deletion
from django.conf import settings
import django.core.files.storage
import dvcs.models
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('cover', '0001_initial'),
migra... |
"""
Retrieve tiles from different tile servers (TMS/TileCache/etc.).
"""
import sys
from mapproxy.image.opts import ImageOptions
from mapproxy.source import SourceError
from mapproxy.client.http import HTTPClientError
from mapproxy.source import InvalidSourceQuery
from mapproxy.layer import BlankImage, map_extent_from... |
import abc
import base64
import io
import os
import pathlib
from typing import Optional, TextIO
import configparser
from . import errors
class Config(abc.ABC):
def __init__(self) -> None:
self.parser = configparser.ConfigParser()
self.load()
@abc.abstractmethod
def _get_section_name(sel... |
# -*- coding: utf-8 -*-
from module.common.json_layer import json_loads
from module.network.RequestFactory import getURL
from module.plugins.internal.MultiHoster import MultiHoster
class UnrestrictLi(MultiHoster):
__name__ = "UnrestrictLi"
__type__ = "hook"
__version__ = "0.02"
__config__ = [(... |
from django.contrib import admin
from .models import Quiz, Question, Answer, Tracker
class QuizAdmin(admin.ModelAdmin):
list_display = [
"id", "description", "active",
"created_at", "updated_at", "created_by", "updated_by"]
list_filter = ["active", "created_at"]
search_fields = ["descript... |
"""Interface that describes the 'macros' attribute of a PageTemplate.
$Id: interfaces.py 26186 2004-07-07 20:22:09Z fdrake $
"""
from zope.interface import Interface, Attribute
class IPageTemplate(Interface):
"""Objects that can render page templates
"""
def __call__(*args, **kw):
"""Render a pa... |
import numpy as np
from datetime import datetime, timedelta
import pytest
import pandas as pd
import pandas.util.testing as tm
import pandas.core.indexes.period as period
from pandas.compat import lrange
from pandas._libs.tslibs.ccalendar import MONTHS
from pandas import (PeriodIndex, Period, DatetimeIndex, Timestam... |
import numpy as np
import librosa
from mediaio.audio_io import AudioSignal
class MelConverter:
def __init__(self, sample_rate, n_fft=2048, hop_length=512, n_mel_freqs=128, freq_min_hz=0, freq_max_hz=None):
self._SAMPLE_RATE = sample_rate
self._N_FFT = n_fft
self._HOP_LENGTH = hop_length
self._N_MEL_FREQS ... |
import json
from apiclient.discovery import build
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
def GetAllUsersInAccount(customerId, superAdmin, jsonKey):
'''
This issues 1 call to the Admin SDK API to get a list of all active users in the Apps account.
The return value is a... |
from heat.common import exception
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.openstack.neutron import neutron
class VPC(resource.Resource):
PROPERTIES = (
CIDR_BLOCK, INSTANCE_TENANCY, T... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import sys
from collections import namedtuple
from colors import red
from six import string_types
from pants.reporting.report import Report
from pants.reporting.repo... |
import testtools
import yaql
from yaql.language import factory
from yaql import legacy
class TestCase(testtools.TestCase):
_default_engine = None
_default_legacy_engine = None
engine_options = {
'yaql.limitIterators': 100,
'yaql.memoryQuota': 20000,
'yaql.convertTuplesToLists': T... |
from amoco.system.macho import *
from amoco.system.core import CoreExec
from amoco.code import tag
import amoco.arch.x64.cpu_x64 as cpu
# ------------------------------------------------------------------------------
class OS(object):
"""OS class is a provider for all the environment in which a Task runs.
It... |
import sys
import math
try:
from osgeo import gdal
from osgeo import osr
except:
import gdal
import osr
#/************************************************************************/
#/* Usage() */
#/*********************************************... |
"""
Stress tests for switching the master storage domain.
Usage:
1. Have two storage domains: one is the current master domain,
and the other will be the new master domain.
2. Run this on the SPM host:
python3 switch_master.py --pool-id XXX --new-master YYY --old-master ZZZ
If there were no errors, the master r... |
from __future__ import with_statement
from django.core.management.base import BaseCommand # , CommandError
from django.apps import apps
from django.db import connection
from constance import config
import shutil
import django.db.utils
import firmware_flash.models
# For monkey patching (see below)
from django.db.b... |
__revision__ = "test/MSVC/PCHSTOP-errors.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
# Test error reporting
"""
import re
import TestSCons
test = TestSCons.TestSCons(match = TestSCons.match_re)
test.skip_if_not_msvc()
SConstruct_path = test.workpath('SConstruct')
test.write(SConstruct_path, ... |
import os
import sys
import py
import tempfile
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
if sys.version_info < (3,0):
class TextIO(StringIO):
def write(self, data):
if not isinstance(data, unicode):
data = unicode(data, getattr(self,... |
import puf_sram_if
import numpy
def min_erntropy(all_meas):
p1 = numpy.zeros(len(all_meas[0]))
# number of ones for each bit
for i in range(0, len(all_meas[0])):
tmp = list(map(lambda x: int(x[i]), all_meas))
p1[i] = numpy.count_nonzero(tmp)
# probability of ones
p1 = numpy.divide... |
# coding=utf-8
import threading
class SettingsLocal(threading.local):
USING_SQLALCHEMY = False # If SQLAlchemy is installed, set to True to use it
# Ignore these
BOARD = None
CONN = None
MODBROWSE = False
IS_TOR = None
IS_PROXY = None
HOST = None
class Settings(object):
LANG = ... |
import ert
import ert.ecl.ecl as ecl
from ert.ecl.ecl import *
from ert.util.tvector import DoubleVector
from ert.util.tvector import DoubleVector
def load_grid( grid_file ):
grid = ecl.EclGrid( grid_file )
return grid
def load_egrid( egrid_file ):
grid = ecl.EclGrid( egrid_file )
return grid... |
# -*- encoding: utf-8 -*-
"""
Kupfer's Contacts API
Main definition and *constructor* classes.
Constructor classes such as EmailContact are used to conveniently construct
contacts with common traits. To *use* contacts, always use ContactLeaf, asking
for specific slots to be filled.
"""
import re
from kupfer import i... |
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.serializers import Serializer
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization
from qualitio import require
from qualitio import store
from qualitio import execute
from q... |
"""A thin wrapper for OpenGL framebuffer objets. For implementation use only"""
from __future__ import division, print_function, unicode_literals
__docformat__ = 'restructuredtext'
import ctypes as ct
from pyglet.gl import *
class FramebufferObject (object):
"""
Wrapper for framebuffer objects. See
h... |
import gdb
import re
import itertools
class EigenMatrixPrinter:
"Print Eigen Matrix of some kind"
def __init__(self, val):
"Extract all the necessary information"
# The gdb extension does not support value template arguments - need to extract them by hand
type = val.type
if type.code == gdb.TYPE_CODE_REF:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import utils.validators
class Migration(migrations.Migration):
dependencies = [
('user_managements', '0025_remove_iuser_p_nr'),
]
operations = [
migrations.AlterField(
mo... |
import unittest
from swanson.decorators import step, given, when, then
from swanson.handlers import Matcher, StepHandler
class DecoratorTestCase(unittest.TestCase):
def test_step(self):
@step(r'^pattern$')
def my_handler():
pass
self.assertIsInstance(my_handler, StepHandler)
... |
"""
Loading a cube from a custom file format
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This example shows how a custom text file can be loaded using the standard Iris
load mechanism.
The first stage in the process is to define an Iris :class:`FormatSpecification
<iris.io.format_picker.FormatSpecification>` for the fil... |
"""The test for remote device automation."""
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import (
_async_get_device_automations as async_get_device_automations,
)
from homeassistant.components.remote import DOMAIN
from homeassistant.const i... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
def csv2dict(csvfile):
import csv
count = 0
with open(csvfile, mode='rbU') as infile:
reader = csv.reader(infile)
with open(csvfile.replace('.csv','_dict.csv'), mode='w') as outfile:
writer = csv.writer(outfile)
count += ... |
from functools import wraps
import inspect
import logging as log
import requests
import time
import sys
from qubell.api.private.exceptions import ApiError, api_http_code_errors
log.getLogger("requests.packages.urllib3.connectionpool").setLevel(log.ERROR)
_routes_stat = {}
def route(route_str): # decorator param
... |
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------
'''
Created on 20 sept. 2014
@author: Seko
@summary: UltraStream Service
'''
#---------------------------------------------------------------------
# ____________________ CHECK ULTRASTREAM ... |
import numpy as np
import scipy as sp
import nibabel as nib
from numpy.testing import (assert_array_equal,
assert_array_almost_equal,
assert_almost_equal,
assert_equal)
from dipy.core import geometry as geometry
from dipy.data import get_d... |
"""
Events:
always
daily
monthly
weekly
"""
from __future__ import unicode_literals, print_function
import frappe
import json
import schedule
import time
import frappe.utils
import os
from frappe.utils import get_sites
from datetime import datetime
from frappe.utils.background_jobs import enqueue, get_jobs, queue... |
"""
URLs for static_template_view app
"""
from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import url
from static_template_view import views
urlpatterns = [
# Semi-static views (these need to be rendered and have the login bar, but don't change)
url(r'^404$', vie... |
from email.mime.multipart import MIMEMultipart
import os
from tests.BaseTestClasses import Email2PDFTestCase
class AttachmentDetection(Email2PDFTestCase):
def setUp(self):
super(AttachmentDetection, self).setUp()
self.msg = MIMEMultipart()
def test_pdf_as_octet_stream(self):
self.ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.