content
stringlengths
4
20k
from datetime import datetime from django.core.urlresolvers import resolve from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from django.utils.translation imp...
# -*- coding: utf-8 -*- from functools import wraps from threading import RLock from types import MethodType from _thread import start_new_thread from ..threads.addon_thread import AddonThread from ..utils.struct.lock import lock from .plugin_manager import literal_eval def try_catch(func): @wraps(func) d...
# Client program from socket import socket, AF_INET, SOCK_STREAM from json_creator import \ json, \ get_presence_message, \ get_message, \ get_all_contacts_message, \ get_contacts_message, \ get_contact_name, \ get_add_friend_message, \ get_message_type, \ get_message_sendfrom, \ ...
import os from types import StringType, UnicodeType import datetime from PyQt4 import QtSql from PyQt4 import QtCore ## import warnings ## warnings.filterwarnings("ignore", ## "DB-API extension", ## UserWarning, ## "sqlite") ...
"""Tests for classification network.""" # Import libraries from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.vision.beta.modeling import backbones from off...
import base64 import re import urllib import urlparse from BeautifulSoup import BeautifulSoup from ..import proxy from ..common import replaceHTMLCodes, clean_title from ..scraper import Scraper import xbmcaddon import xbmc class Watchfree(Scraper): domains = ['watchfree.to'] name = "watchfree" def __ini...
# -*- coding: utf-8 -*- from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rules', '0042_rule_state_in_source'), ] operations = [ migrations.CreateModel( name='Threshold', fields=[ ...
#!/usr/bin/python3 from json import loads from os import system from time import sleep import requests import os, pwd, grp def drop_privileges(uid_name='nobody', gid_name='nogroup'): if os.getuid() != 0: # We're not root so, like, whatever dude return # Get the uid/gid from the name running_uid = pwd.g...
# -*- coding: utf-8 -*- """Module handling schedules""" from functools import partial from cfme.fixtures import pytest_selenium as sel from cfme.intelligence.reports.ui_elements import Timer from cfme.web_ui import (EmailSelectForm, Form, CheckboxTable, Select, ShowingInputs, accordion, fill, flash, toolbar, form_...
"""Unit tests for Superset""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from datetime import datetime import json import unittest from mock import Mock, patch from superset import db, sm, security from superset...
# encoding: utf-8 import json import datetime import re import bleach from django import template from django import forms from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from django.utils.encoding import force_unicode from django.utils.timezone import now as...
#!/usr/bin/env python """ HappyBoom client using a wrapper to the command line "awale" program to create an Awale IA. This client is written by Victor Stinner and distributed under the GNU GPL license. -- Awale program is written by Laurent Le Bot, Alain Le Bot and Diana Martin de Argenta and distributed under the G...
# -*- coding: utf-8 -*- import re from unittest import TestCase from forgery_py.forgery import address from forgery_py.dictionaries_loader import get_dictionary class AddressForgeryTestCase(TestCase): def test_street_name(self): result = address.street_name() assert result + '\n' in get_dictiona...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re from pants.base.build_environment import get_buildroot from pants.util.contextutil import temporary_dir from pants.util.dirutil import safe_rmtree...
from imagetools import assert_images, ImageFactory def test_no_images_removed(docker_client, image_factory, docker_rotate): assert_images(docker_client) id1 = image_factory.add('image_1', 'latest') id2 = image_factory.add('image_2', 'latest') docker_rotate(['images', '--keep', '3']) assert_image...
import numpy as np from multiprocessing import Process from sklearn.neighbors import KNeighborsClassifier from scipy.spatial.distance import euclidean def filter_data(input, output, x, y, comparator): training = [] result = [] size_x = input.shape[0] size_y = input.shape[1] for a in xrange(0, size_x): ...
import cloud from cloudferrylib.os.identity import keystone from cloudferrylib.os.network import neutron from cloudferrylib.os.compute import nova_compute from cloudferrylib.utils import utils LOG = utils.get_log(__name__) class Grouping(object): def __init__(self, config, group_file, cloud_id): self.c...
# class MoodleDestroyerCommand: # def __init__(self, name, help_text): # self.name = name # self.help = help_text # # def __str__(self): # return self.name + ' ' + self.help # # @property # def version(self): # return '0.1.0' # TODO, internal commands do return mdt versi...
# stageDefaults contains the default options which are applied to each stage (command). # This section is required for every Rubra pipeline. # These can be overridden by options defined for individual stages, below. # Stage options which Rubra will recognise are: # - distributed: a boolean determining whether the tas...
""" Nose plugin to restrict access to blacklisted os modules. Activate by running nosetests --with-ospatch or like this in local settings: NOSE_PLUGINS = [ 'amo.tests.ospatch.OSPatch', ] NOSE_ARGS = [ '--with-ospatch', ] This was originally made to help identify code that needed ...
# -*- coding: utf-8 -*- """ Created on Fri Feb 26 19:57:32 2016 @author: ORCHISAMA """ from __future__ import division import numpy as np from scipy.io.wavfile import read from LBG import lbg from mel_coefficients import mfcc from LPC import lpc import matplotlib.pyplot as plt import os def training(nfiltbank, orde...
import time import private.pw import pyzmail class SendMail: def __init__(self): # TODO: make these settings configurable self.sender = (u'Yafa!', '<EMAIL>') self.recipients = [(u'Nico Lugil', '<EMAIL>')] self.default_charset = 'iso-8859-1' self.encoding = 'us-ascii' ...
#A list of all available Tequilas, to show the user when they type "help" #all lowercase values of these exact phrases are stored in the weights dictionary #The script should take upper and lower case values of these exact strings tequila_list = ["Jose Cuervo", "JLP", "Herradura", "El Jimador", "Arette", "Casa Noble...
from plugin import plugin import time import random import sys @plugin('memory') class Memory: """ Welcome to the Short-Term Memory Trainer! Here you can find all the functionalities of this plugin. Usage: Type memory, press enter and follow the instructions Functionalities: You can train your mem...
import logging from contextlib import contextmanager import pytest from flask import Flask from hades_logs import HadesLogs, hades_logs from hades_logs.exc import HadesOperationalError @contextmanager def assert_unconfigured(caplog, level=logging.WARNING): with pytest.raises(KeyError) as exc_cm, \ cap...
""" Evaluate the perplexity of a trained language model. """ import logging import math import os import sys from argparse import Namespace from typing import Iterable, List, Optional import torch import fairseq from fairseq import checkpoint_utils, distributed_utils, options, tasks, utils from fairseq.dataclass.util...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.shortcuts import get_object_or_404 from service_order.models import Service_Order from ser...
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ Scrape admin module for Liberia Media Collection author: Nathan Danielsen email: <EMAIL> """ import os import csv import datetime import time from scrape import Collector class Scraper_Admin(object): """ Simple control for the scraper function Takes a list...
import re import time import logging import traceback import colored from dnutils import out, ifnone from collections import defaultdict import random from functools import reduce # math functions USE_MPMATH = True try: if not USE_MPMATH: raise Exception() import mpmath # @UnresolvedImport mp...
from eos.exception import EosError class ItemError(EosError): """All item-related exceptions are based on this class.""" ... class NoSuchSideEffectError(ItemError): """Raised if user manipulates side-effect which doesn't exist on item.""" ... class NoSuchAbilityError(ItemError): """Raised if u...
import sys from pyspark import SparkConf, SparkContext from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.feature import HashingTF from pyspark.mllib.classification import LogisticRegressionWithSGD ########################################################################## # Main ##################...
from flask import session from indico.core.config import Config from MaKaC.errors import MaKaCError from indico.util.importlib import import_module class AuthenticatorMgr: def __init__(self): self._authenticator_list = [] for auth, config in Config.getInstance().getAuthenticatorList(): ...
"""Module to train CF embedding models.""" import tensorflow.compat.v2 as tf from hyperbolic.tree_based.learning import tree_losses as losses class CFTrainer(object): """CF embedding trainer object.""" def __init__(self, sizes, args): """Initialize CF trainer. Args: sizes: Tuple of size 2 contain...
import os, sys import fio, myfun import vtktools import numpy as np import matplotlib as mpl mpl.use('ps') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec ## READ archive (too many points... somehow) # args: name, dayi, dayf, days label = sys.argv[1] basename = sys.argv[2] dayi = int(sys.arg...
import unittest import logging from test.custom import CustomAssertions class TestProperties: def __init__(self): self._properties = {} def set_property(self, name, value): self._properties[name] = value def has_property(self, name): if name in self._properties: retu...
# -*- coding: utf-8 -*- from tests import settings from .resources import Transfer, Transaction from .test_base import BaseTest from mangopay.utils import Money from datetime import date import responses import time class TransactionsTest(BaseTest): @responses.activate def test_retrieve_transactions(self):...
import os import sys, getopt import time import numpy import theano import theano.tensor as T from sklearn import preprocessing from cnn import CNN import pickle as cPickle from logistic_sgd import LogisticRegression def fit(data, labels, filename = 'weights_v5.pkl'): fit_predict(data, labels, filename = filename...
from hqlib.sql import Base from sqlalchemy import Column, Integer, String, ForeignKey, PickleType, Text, DateTime from sqlalchemy.orm import relationship from datetime import datetime from sqlalchemy.ext.orderinglist import ordering_list from hqlib.sql.customtypes.enumtype import DBEnum from hqlib.sql.customtypes.textp...
from mantid.simpleapi import GroupWorkspaces from Muon.GUI.Common.ADSHandler.ADS_calls import check_if_workspace_exist # A singleton metaclass, required for the WorkspaceGroupDefinition class. class Singleton(type): """ A singleton metaclass, required for the WorkspaceGroupDefinition class. """ _insta...
#!/usr/bin/env python #coding=utf-8 ''' 缺省全局设置 @author: 15th @data: 2017.2.28 ''' # 版本信息 PROGNAME = 'Simpleat' MAJOR_VERSION = '0.1.0' MINOR_VERSION = '0b61b58f10' VERSION = '.'.join([MAJOR_VERSION, MINOR_VERSION]) PROGINFO = ' '.join([PROGNAME, MAJOR_VERSION]) DATE = '02.2017' AUTHOR = '15th' # 全局 SPLITLINE = '--...
from unittest.mock import MagicMock from api.subtitle.model import Subtitle from domain.load import Loader def test_load(): subtitles = [ MagicMock(spec=Subtitle, id='A', encoding='c', format='srt', partial=False, downloads=100, text='<text>'), ] api_mock = MagicMock() api_...
import mock from openstackclient.common import commandmanager from openstackclient.tests import utils class FakeCommand(object): @classmethod def load(cls): return cls def __init__(self): return FAKE_CMD_ONE = FakeCommand FAKE_CMD_TWO = FakeCommand FAKE_CMD_ALPHA = FakeCommand FAKE_CMD_...
""" abstract vpp object and object registry """ import abc class VppObject(metaclass=abc.ABCMeta): """ Abstract vpp object """ @abc.abstractmethod def add_vpp_config(self) -> None: """ Add the configuration for this object to vpp. """ pass @abc.abstractmethod def query_vpp_confi...
""" Helpers for using libcloud. """ from zope.interface import ( Attribute as InterfaceAttribute, Interface, implementer) from characteristic import attributes, Attribute from flocker.provision._ssh import run_remotely, run_from_args def get_size(driver, size_id): """ Return a ``NodeSize`` corresponding...
STUDENT_ID = '' # 你的学号 IDS_USERNAME = STUDENT_ID # ids.xidian.edu.cn的用户名,一般来说是学号 IDS_PASSWORD = '' # ids.xidian.edu.cn的密码,一般是身份证后六位 WX_USERNAME = STUDENT_ID # wx.xidian.edu.cn/wx_xdu的用户名 WX_PASSWORD = IDS_PASSWORD # wx.xidian.edu.cn/wx_xdu的密码,和ids同步 # 在ids上改密码这边的也会变,所以不要单独改 XDOJ_USERNAME = STUDENT_ID # 202.117.12...
#! /usr/bin/env python from iwi.core import classify from iwi.core import Post from iwi.threading import Pool from iwi.web import boards from common import logger from common import parameters def find_hashes (*links): """ Finds unique tripcodes. If no URLs are given it will attempt to s...
from cwatm.management_modules.data_handling import * class snow_frost(object): """ RAIN AND SNOW Domain: snow calculations evaluated for center points of up to 7 sub-pixel snow zones 1 -7 which each occupy a part of the pixel surface Variables *snow* and *rain* at end of this module are the pix...
from __future__ import unicode_literals from django.test import SimpleTestCase from localflavor.il.forms import ILIDNumberField, ILMobilePhoneNumberField, ILPostalCodeField class ILLocalFlavorTests(SimpleTestCase): def test_ILPostalCodeField(self): error_format = ['Enter a postal code in the format XXXX...
"""Provides device automations for deconz events.""" import voluptuous as vol import homeassistant.components.automation.event as event from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) fro...
_DEVICE_CONFIGS = {} def get_config(module, target='commands'): cmd = ' '.join(['show configuration', target]) try: return _DEVICE_CONFIGS[cmd] except KeyError: rc, out, err = module.exec_command(cmd) if rc != 0: module.fail_json(msg='unable to retrieve current config',...
# -*- coding: utf-8 -*- """ *************************************************************************** SagaParameters.py --------------------- Date : December 2018 Copyright : (C) 2018 by Nyall Dawson Email : nyall dot dawson at gmail dot com *************...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import traceback from uuid import uuid4 from six import string_types from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import STATUS_CODE_TEXT from django.shortcuts import resolve_url from django.test...
import traceback import warnings import sys import os from . import exif AVAILABLE_LIBRARIES = [] USE_VIPS = False os.environ['VIPS_WARNING'] = "0" if not os.environ.get("FORCE_PIL", None): try: import gi gi.require_version("Vips", '8.0') from gi.repository import Vips Vips.cache_...
from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Div from django import forms from django.contrib.auth.models import User from django.core.validators import validate_email from django.urls import reverse from django.utils.translation import ugettext as _ from profile.models im...
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.log import enable_pretty_logging import sys, csv, io, argparse, ConfigParser, unicodecsv, StringIO, json sys.path.append("../common") sys.path.append("../profiler") from MetaModel import Met...
# Setup list of patches and books to use # import os import sys # LOGGING import sharedLogger bookKeys = { 'FRT': '000', 'GEN': '001', 'EXO': '002', 'LEV': '003', 'NUM': '004', 'DEU': '005', 'JOS': '006', 'JDG': '007', 'RUT': '008', '1SA': '009', '2SA': '010', '1KI': '011', '2KI': '012', '1CH': '013', '2CH': '014', ...
from __future__ import print_function from flask import jsonify, request, Response, json, g from orlo.app import app from orlo import queries from orlo.exceptions import InvalidUsage from orlo.user_auth import token_auth from orlo.orm import db, Release, Package, PackageResult, ReleaseNote, \ ReleaseMetadata, Platf...
from django.core.exceptions import ImproperlyConfigured from django.core.paginator import InvalidPage, Paginator from django.db.models.query import QuerySet from django.http import Http404 from django.utils.translation import ugettext as _ from django.views.generic.base import ContextMixin, TemplateResponseMixin, View ...
import logging import threading import time import re from os import environ, getpid, getuid from subprocess import Popen, PIPE from pilot.common.exception import PilotException, ExceededMaxWaitTime from pilot.util.auxiliary import check_for_final_server_update from pilot.util.config import config from pilot.util.cons...
"""Convert iCal files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/ical2po.html for examples and usage instructions. """ import sys import logging from translate.storage import po from translate.storage import ical logger = logging.getLogger(__n...
import decimal from unittest import TestCase from StringIO import StringIO import json from collections import OrderedDict class TestDecode(TestCase): def test_decimal(self): rval = json.loads('1.1', parse_float=decimal.Decimal) self.assertTrue(isinstance(rval, decimal.Decimal)) self.asser...
import collections import functools from ..defer import Deferred, DeferredDict, DeferredList, defer, succeed from ..error import GraphQLError from ..language import ast from ..language.parser import parse from ..language.source import Source from ..type import GraphQLEnumType, GraphQLInterfaceType, GraphQLList, GraphQ...
from collections.abc import Mapping, Hashable from itertools import chain from pyrsistent._pvector import pvector from pyrsistent._transformations import transform class PMap(object): """ Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instanti...
""" This file ... """ from libsignetsim.sedml.Change import Change from libsignetsim.sedml.container.ListOfParameters import ListOfParameters from libsignetsim.sedml.container.ListOfVariables import ListOfVariables from libsignetsim.sedml.math.MathFormula import MathFormula from libsignetsim.settings.Settings impor...
import xbmcgui, urllib, sys, time, uservar import wizard as wiz ADDONTITLE = uservar.ADDONTITLE COLOR1 = uservar.COLOR1 COLOR2 = uservar.COLOR2 urllib.URLopener.version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0' def...
from tvrenamer.core import patterns def _get_season_no(match, namedgroups): if 'seasonnumber' in namedgroups: return int(match.group('seasonnumber')) return 1 def _get_episode_by_boundary(match): # Multiple episodes, regex specifies start and end number start = int(match.group('episodenumbe...
import chainer from chainer import backend from chainer import function_node from chainer.utils import type_check class CReLU(function_node.FunctionNode): """Concatenated Rectified Linear Unit.""" def __init__(self, axis=1): if not isinstance(axis, int): raise TypeError('axis must be an ...
#!/usr/bin/python # -*- coding: utf-8 -*- import time import Axon import Axon import time from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Chassis.Graphline import Graphline from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Util.PureTransformer import PureTransformer ...
# -*- coding: utf-8 -*- """ Fantastic Add-on 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 pro...
import sys import time from pandaserver.config import panda_config from pandaserver.taskbuffer.TaskBuffer import taskBuffer from pandaserver.configurator import db_interface as dbif from pandacommon.pandalogger import logger_utils from pandaserver.configurator import Configurator as configurator_module from pandaserve...
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer, JMESPathCheck, NoneCheck, api_version_constraint) from azure.cli.core.profiles import ResourceType from ..storage_test_util import StorageScenarioMixin @api_version_constraint(ResourceType.MGMT_S...
from __future__ import unicode_literals import erpnext.education.utils as utils import frappe no_cache = 1 def get_context(context): # Load Query Parameters try: program = frappe.form_dict['program'] content = frappe.form_dict['content'] content_type = frappe.form_dict['type'] course = frappe.form_dict['cou...
# flake8: noqa import os from datetime import datetime import warnings import nose import pandas as pd from pandas import compat from pandas.util.testing import network, assert_frame_equal, with_connectivity_check from numpy.testing.decorators import slow import pandas.util.testing as tm if compat.PY3: raise nos...
import numpy as np import pytest from pandas import DataFrame, MultiIndex from pandas.core.groupby.base import reduction_kernels from pandas.util import testing as tm @pytest.fixture def mframe(): index = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0,...
import os import json import web from influxhtm import InfluxHtmClient INFLUX_DATABASE = os.environ["INFLUX_DB"] DEFAULT_PORT = 8080 ihtmClient = InfluxHtmClient(INFLUX_DATABASE, verbose=True) ################# # HTTP Handlers # ################# urls = ( '/', 'Index', '/_models/?', 'Models', '/_data/senso...
from django.http import Http404 from rest_framework import exceptions from rest_framework.settings import api_settings from rest_framework.utils.mediatypes import order_by_precedence, media_type_matches class BaseContentNegotiation(object): def select_parser(self, request, parsers): raise NotImplementedEr...
from __future__ import unicode_literals import rdw_config import db_sql from rdw_helpers import encode_s, decode_s """We do no length validation for incoming parameters, since truncated values will at worst lead to slightly confusing results, but no security risks""" class sqliteUserDB: def __init__(self, conf...
#! /usr/bin/python2 import subprocess import sys import os import time from subprocess import PIPE import socket curdir_name = os.getcwd() print ("Current working directory: "+curdir_name) # CFL parameter CFL=0.5 output_file_prefix = "run_" # # run for 1 seconds # max_time = 1000 # # order of time step for RK ...
""" utility functions for Yubico modules """ # Copyright (c) 2010, Yubico AB # See the file COPYING for licence statement. __all__ = [ # constants # functions 'crc16', 'validate_crc16', 'hexdump', 'modhex_decode', 'hotp_truncate', # classes ] import sys import string from .yubico_vers...
""" Nagios Plugin resource(s). """ from logging import getLogger from nagiosplugin import ( CheckError, Metric, Resource, ) COUNT = "count" MEAN = "mean" VALUES = "values" class Measurements(Resource): """ Count and mean metrics for a simple InfluxDB measurement query. """ def __init__(...
""" Module implementing class definitions for monitoring strategies. """ import heapq import itertools import logging __all__ = ['ApplicationState', 'UserEvent', 'StrategyEnforcer', 'ManagementStrategy', 'InvalidStrategyException', 'InvalidServiceException'] cl...
import serial.tools.list_ports import fermentrack_django.settings import os import pickle # from . import udev_integration DEVICE_CACHE_FILENAME = fermentrack_django.settings.ROOT_DIR / 'device.cache' known_devices = { 'arduino': [ # Those with 'generic': False are virtually guaranteed to be Arduinos ...
#!/usr/bin/python from __future__ import division import io, os, time, datetime, cv2, sys, picamera import numpy as np class PiEye(): def __init__(self): self.debug = True self.image_directory = "images" self.last_report = None self.prev_image = None self.width = 288 self.height = 192 se...
import json from urllib.parse import urlencode from tests.fixtures.factories import ( StudentFactory, ProfessorFactory, SectionFactory, CourseFactory, EvaluationFactory, VoteFactory, QuarterFactory, DepartmentFactory ) from scuevals_api.models import db, Vote from tests import TestCase, use_data, assert_valid_...
import unittest from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distance from alfpy.utils import distmatrix from . import utils class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*a...
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import Flask, render_template, request from elasticsearch import Elasticsearch era_search = Flask(__name__) # TODO: Configuration host = "http://localhost:9200" index_name = "eracareers" aggregation_fields = ["city", "vacancies", "contract", "main_field", "sub_fie...
import warnings import numpy as np from numpy.testing import assert_allclose from menpo.image import Image, MaskedImage from menpo.shape import TriMesh, TexturedTriMesh, ColouredTriMesh from menpo.testing import is_same_array def test_trimesh_creation(): points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1...
# python standard library from collections import OrderedDict import textwrap import importlib # third party from configobj import ConfigObj from validate import Validator # this package from base_plugin import BasePlugin, BaseConfiguration from theape.parts.dummy.dummy import DummyClass from theape.parts.dummy.dummy...
from .services.lookup_service import LookupServiceClient from .services.lookup_service import LookupServiceAsyncClient from .services.registration_service import RegistrationServiceClient from .services.registration_service import RegistrationServiceAsyncClient from .types.endpoint import Endpoint from .types.lookup_s...
# -*- coding: utf-8 -*- """ Dealing with cfx files """ import os import re import fnmatch # from config import config # TODO: move this func to tools/utils module def ra_code(string): """ find RA code in string """ code_pattern = 'ra{0,1}[efgk]s{0,1}\d{2}[a-z][0-9a-z]{0,1}' code = re.search(code_pattern,...
__author__ = 'zoorobmj' import math from sklearn import metrics import numpy as np import pandas as pd from random import randint def clustering(array): pairs = [] for list in array: print list for distance in list: current = None if distance == 0: ...
#!/usr/bin/env python import argparse import gzip import sys def is_header(line): """Check if a line is header.""" return line.startswith('#') def has_END(line): """Check if a line has the 'END=' tag.""" return 'END=' in line # FIELD index # CHROM 0, POS 1, REF 3, QUAL 5, INFO 7, FORMAT 8, sample ...
"""Interface to the Mindwave EEG ThinkGear Connector.""" import time import json import socket import logging from genutils.strings import to_bytes, to_str PORT = 13854 URL = '127.0.0.1' BUFFER_SIZE = 1024 MAX_QUALITY_LEVEL = 200 POOR_SIGNAL_LEVEL = 'poorSignalLevel' class MindWaveInterface(object): """Interf...
import os import theano import time import numpy as np import pandas as pd import keras.layers.core as core import keras.layers.convolutional as conv import keras.models as models import keras.utils.np_utils as kutils from keras.layers.embeddings import Embedding from keras.layers.recurrent import LSTM fro...
#!/usr/bin/env python #------------------------------------------------------------------------------ # plot_imsrg_flow.py # # # tested with Python v2.7 # #------------------------------------------------------------------------------ from sys import argv import matplotlib.pyplot as plt from matplotlib.ticker impo...
""" Compute derived parameters from random samples from your chain. We also histogram the masses Will add histogram of initial phi vals as well There is now an option to get derived with your chain, so that step can be eliminated. (Derived params option in latest Mtheory Gaussian MCMC) This is still useful to histogra...
import numpy import six import chainer from chainer import cuda from chainer import function from chainer.utils import type_check class SelectItem(function.Function): """Select elements stored in given indices.""" def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) ...
from oslo_log import log from tempest.common.utils import data_utils from tempest.common import waiters from tempest import config from tempest.scenario import manager from tempest import test CONF = config.CONF LOG = log.getLogger(__name__) class TestVolumeBootPattern(manager.ScenarioTest): """ This test...
#!/usr/bin/python # -*- coding: utf-8 -*- """ pyforms.gui.Controls.ControlEventTimeline.TimelineDelta """ from PyQt4 import QtGui from pyforms.gui.Controls.ControlEventTimeline.Track import Track __author__ = ["Ricardo Ribeiro", "Hugo Cachitas"] __credits__ = ["Ricardo Ribeiro", "Hugo Cachitas"] __license__ = "MIT"...
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class User(models.Model): name = models.TextField() last_name = models.TextField() groups = models.ManyToManyField('Group', related_name='users') per...