content
stringlengths
4
20k
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import numpy as np from .. import ODESys from ..util import requires from .test_core import sine, sine_jac def _test_sine(use_deriv, atol=1e-8, rtol=1e-8, forgive=1e4): odesys = ODESys(sine, sine_jac) A, k = 2, 3 ...
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="font", parent_name="choroplethmapbox.hoverlabel", **kwargs ): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_n...
""" # Parse Markdown into TSV # @author: jink """ from mdt.mdt_init import * P_T1 = r"^# (.*)" P_T2 = r"^## (.*)" P_T3 = r"^### (.*)" P_BLANK = r"^\s*$" C_TITLE = "#" def parse_md_files(fileptn): mds = glob.glob(fileptn) mds.sort() return pd.concat([parse_md_file(fn) for fn in mds], axis=0) ...
#!/usr/bin/env python """ file: si7021.py author: Chris Schwab project: High Altitude Balloon Instrumentation Platform description: Demo script for the Si7021-A20 I2C humidity sensor data-sheet: http://www.silabs.com/documents/public/data-sheets/Si7021-A20.pdf """ # sudo apt-get install python-smbus import smbus i...
# -*- coding: utf-8 -*- from flask import Markup, current_app from flask.ext.wtf import Form from flask.ext.wtf.html5 import EmailField from wtforms import (ValidationError, BooleanField, TextField, HiddenField, PasswordField, SubmitField) from wtforms.validators import (Required, Length, EqualTo, Email) from flask.e...
import json from ..models import Agent from ..exceptions import ParamError class AgentManager(): def __init__(self, params, define=True): # This parsing is kept for profile/state/agents endpoints if not isinstance(params, dict): try: params = json.loads(params) ...
"""Exports utilities helpful for dealing with distorting numpy arrays with additive white Gaussian noise. """ import numpy as np def distort_one_channel_representation(channel_in, snr, n_avg): """Handles distorting a single channel representation. Args: channel_in: The channel to be distorted. ...
""" @author: ArcGIS for Water Utilities @contact: <EMAIL> @company: Esri @version: 1.1 @description: Used to delete content from a feature service @requirements: Python 2.7.x, ArcGIS 10.2.1 @copyright: Esri, 2014 """ import gc import os import sys import arcpy from arcresthelper import feat...
from ..robotsim import * from collide import self_collision_iter from trajectory import Trajectory,HermiteTrajectory import weakref class SubRobotModel: """A helper that lets you conveniently set/get quantities for a subset of moving links on a RobotModel. This class has the same API as RobotModel, but everything ...
"""Expands a hand-written PDF testcase (template) into a valid PDF file. There are several places in a PDF file where byte-offsets are required. This script replaces {{name}}-style variables in the input with calculated results {{header}} - expands to the header comment required for PDF files. {{xref}} ...
# _*_ encoding:utf-8 _*_ from __future__ import unicode_literals from datetime import datetime from django.db import models from users.models import UserProfile from courses.models import Course # Create your models here. class UserAsk(models.Model): name = models.CharField(max_length=20, verbose_name=u"姓名") ...
from apps.data.users.models import User from apps.data.songs.models import Song from apps.data.userPlaySong.models import UserPlaySong from apps.similarities.Cosine.benchmark.models import BenchCosine_SongTitle from apps.recommenders.UserAverage.algorithm.models import UserAverage_Life from django.db.models import Sum ...
""" MIT License Copyright (c) 2016 William Tumeo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
""" Created on Tue Apr 10 17:23:07 2012 @author: Christoph Gohle ufloat package contains quantities with units for scalars and numpy arrays The basic usage is as follows: Examples -------- To create a number with unit >>> s = ufloat(1, {'s',1}) >>> m = ufloat(1, {'m',1}) numbers with units can be multiplied >>> 5*...
import json import datetime from io import StringIO import csv from uuid import uuid4 from sqlalchemy import func from sqlalchemy.exc import IntegrityError from flask import Blueprint, request, jsonify, make_response from bson.errors import InvalidId from mhn import db, csrf from mhn.api import errors from mhn.api.m...
import json import multiprocessing import socket import time import eventlet from oslo_config import cfg from oslo_log import log as logging from oslo_service import service import psutil from sqlalchemy import desc from murano.api import v1 from murano.api.v1.deployments import set_dep_state from murano.api.v1 impor...
import re import webob from nova.api.openstack import common from nova.api.openstack.compute.schemas import console_output from nova.api.openstack import wsgi from nova.api import validation from nova.compute import api as compute from nova import exception from nova.policies import console_output as co_policies cl...
"""Main Server Logic""" import logging import logging.config # from datetime import datetime from time import sleep LOG_SETTINGS = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': logging.DEBUG, 'formatter': 'detailed', }...
from .shape import Shape from .shape import mergeBoundary from .shape import offsetBoundary from .quadratic import solveMin, solveMax class Segment(Shape): def __init__(self): pass def __ne__(self, other): return not self.__eq__(other) def draw(self, drawingSystem): pass def computeBoundary(self): retur...
import os import sublime import subprocess import re try: from GitGutter import git_helper from GitGutter.view_collection import ViewCollection except ImportError: import git_helper from view_collection import ViewCollection class GitGutterHandler: def __init__(self, view): self.load_sett...
from __future__ import unicode_literals app_name = "erpnext" app_title = "ERPNext" app_publisher = "Frappe Technologies Pvt. Ltd." app_description = """## ERPNext ERPNext is a fully featured ERP system designed for Small and Medium Sized business. ERPNext covers a wide range of features including Accounting, CRM, Inve...
import os from oslo_config import cfg from oslo_log import log as logging from oslo_utils import importutils from oslo_utils import units from cinder import context from cinder import exception from cinder.i18n import _, _LI, _LW from cinder.image import image_utils from cinder import interface from cinder import obj...
import sys sys.path.append('../../python') import moose def example(): pg = moose.PulseGen('pulse') pg.delay[0] = 1.0 pg.width[0] = 0.2 pg.level[0] = 0.5 tab = moose.Table('tab') moose.connect(tab, 'requestOut', pg, 'getOutputValue') moose.setClock(0, 0.01) moose.setClock(1, 0.01) m...
""" Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. ![Example layout] (https://leetcode.com/static/images/problemset/rectangle_area.png) Assume that the total area is never beyond the maximum pos...
""" The PyQt specific implementations the action manager internal classes. """ # Standard libary imports. from inspect import getargspec # Major package imports. from enthought.qt import QtGui, QtCore # Enthought library imports. from enthought.traits.api import Any, Bool, HasTraits # Local imports. from enthought...
"""Tests for the library page and associated handlers.""" import json import os from constants import constants from core.domain import exp_jobs_one_off from core.domain import exp_services from core.domain import rating_services from core.domain import rights_manager from core.domain import user_services from core.p...
from penguin import penguin import os import shutil class TestPenguinClass: def setup(self): config_for_test = {} config_for_test['title'] = 'Title' config_for_test['posts'] = [] config_for_test['source'] = 'source_dir' config_for_test['dest'] = 'dest_dir' config_for...
import logging import datetime import authenticate import database.util as util import custom_exceptions from web.global_session import global_session from page_item import info, input, textarea, result_link from form import form, FormFactory r = global_session.database log = logging.getLogger('rebase.node') cl...
#!/usr/bin/env python import sys import string flankDict = { "tss":2000, "tes":2000, "genebody":2000, "exon":500, "cgi":500, "enhancer":1500, "dhs":1000, } pointLabDict = { "tss":"TSS", "tes":"TES", "genebody":"TSS,TES", "exon":"Acceptor,Donor", "cgi":"Left,Right", ...
# -*- coding: utf-8 -*- """Functional tests using WebTest. See: http://webtest.readthedocs.org/ """ import pytest from flask import url_for from websterton.user.models import User from .factories import UserFactory class TestLoggingIn: def test_can_log_in_returns_200(self, user, testapp): # Goes to ho...
import unittest import hangul class TestHangul(unittest.TestCase): """Return value of each test is on the left side.""" def testOrdHangul(self): self.assertEqual(0, hangul.OrdHangul('가')) self.assertEqual(1, hangul.OrdHangul('각')) self.assertEqual(4, hangul.OrdHangul('간')) self.assertEqual(6468, ...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy # class AlexscrapperItem(scrapy.Item): # link = scrapy.Field() # name = scrapy.Field() # cashback = scrapy.Field() # sid = scrapy.Field() # ...
import string class DFA: keywords = [ 'def', 'input', 'output', 'break', 'continue', 'if', 'elsif', 'else', 'switch', 'case', 'default', 'while', 'do', 'for', 'foreach', 'in', 'f...
import os import re import time from cfme.scripting.quickstart import run_cmd_or_exit IS_ROOT = os.getuid() == 0 REDHAT_RELEASE_FILE = '/etc/redhat-release' HAS_DNF = os.path.exists('/usr/bin/dnf') HAS_YUM = os.path.exists('/usr/bin/yum') HAS_APT = os.path.exists('/usr/bin/apt-get') OS_RELEASE_FILE = '/etc/os-relea...
from seamicroclient.tests import utils from seamicroclient.tests.v2 import fakes from seamicroclient.v2 import scards cs = fakes.FakeClient() class ScardsTest(utils.TestCase): def test_list_scards(self): pl = cs.scards.list() cs.assert_called('GET', '/chassis/scard') [self.assertTrue(is...
import numpy as np class KMeans: """ This class implements a standard version of the K-Means algorithm as described in the book "Pattern Recognition and Machine Learning" by Christopher M. Bishop. Attributes: clusters -- number of clusters init -- NumPy array of initial centroids centr...
import netaddr from melange.common import exception from melange.db import db_api from melange import ipam class DbBasedIpGenerator(object): def __init__(self, ip_block): self.ip_block = ip_block def next_ip(self): allocatable_address = db_api.pop_allocatable_address( ipam.mode...
import warnings import pytest WARNINGS_SUMMARY_HEADER = "warnings summary" @pytest.fixture def pyfile_with_warnings(testdir, request): """ Create a test file which calls a function in a module which generates warnings. """ testdir.syspathinsert() test_name = request.function.__name__ module_...
''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy)...
""" mbed CMSIS-DAP debugger Copyright (c) 2015-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
from .parse_endf import parse_zipfiles from cslib import units, Settings import numpy as np import os import json from urllib.request import urlopen from hashlib import sha1 from pkg_resources import resource_string, resource_filename def loglog_interpolate(x_i, y_i): """Interpolates the tabulated values. Line...
# -*- coding: utf-8 -*- import pycurl import re from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo class QuickshareCz(SimpleHoster): __name__ = "QuickshareCz" __type__ = "hoster" __version__ = "0.58" __status__ = "testing" __pattern__ = r'http://(?:[^/]*\.)?qui...
from random import choice import random import time import copy class SubGenerator_w(object): def __init__(self, streams, pt_time, valid_values): self.streams = streams self.pt_time = pt_time self.valid_values = valid_values self.cur_stream = 1 def __iter__(self): retu...
# -*- coding: utf-8 -*- """ *************************************************************************** RenderingStyleFilePanel.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***************...
from distutils.core import setup, Extension # We're skipping the metadata for now # the extension module, source was generated by SWIG from geos.i # # Note that until geos is ready to be installed, we're linking against # the pre-installed library in source/geom/.libs. extmod = Extension("_geos", ["geos_wrap.cxx"], ...
# coding=utf-8 """Dialog test. .. note:: 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 2 of the License, or (at your option) any later version. """ __author__ = '<EM...
import mitmproxy.contentviews as cv from netlib.http import Headers def test_custom_views(): class ViewNoop(cv.View): name = "noop" prompt = ("noop", "n") content_types = ["text/none"] def __call__(self, data, **metadata): return "noop", cv.format_text(data) view_...
""" airy_profile.py: calculates 1D radial intensity of the Fraunhofer diffraction of a disk aperture (Airy pattern) """ __author__ = "Manuel Sanchez del Rio" __contact__ = "<EMAIL>" __copyright = "ESRF, 2015" from scipy.special import jv import numpy # #inputs (in SI units) # # wavelength = 1e-10 # 500e-9 # 1...
from uuid import uuid4 from pyipa import IPAparser from anarcho.ipin import update_png import os def get_icon(info, ipa_parser, ipa_path): icon_bundle = next(x for x in info.keys() if 'CFBundleIcon' in x) icon_names = info.get(icon_bundle)['CFBundlePrimaryIcon']['CFBundleIconFiles'] def _check(name): ...
import os, sys import argparse from collections import defaultdict from lxml import etree from lxml.builder import ElementMaker EM = ElementMaker() ROOT = EM.text HEADER = EM.header TOKEN = EM.token DIPL = EM.dipl MODERN = EM.mod NORM = EM.norm COMMENT = EM.comment LEMMA = EM.lemma POS = EM.pos LAYOUT = EM...
"""Threadlocal OpenStruct-like cache.""" import re import fnmatch import threading class LocalStore(threading.local): """ A thread-local OpenStruct that can be used as a local cache. An instance is located at ``johnny.cache.local``, and is cleared on every request by the ``LocalStoreClearMiddleware`...
# CLASS containing the set of fromtree to access some general # time traces like current, bt, elongation, triangularity, # line-average density # central density from thomson, central temperature from thomson, # central temperature from # double filter from __future__ import print_function import tcv import matplotlib ...
from __future__ import unicode_literals from django import forms, VERSION as DJANGO_VERSION from django.contrib.auth.forms import ( ReadOnlyPasswordHashField, ReadOnlyPasswordHashWidget, PasswordResetForm as OldPasswordResetForm, UserChangeForm as DjangoUserChangeForm, ) from django.contrib.auth import get...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy import theano import theano.tensor as TT def concat_sparse(sparse1, sparse2, dim1, dim2): """Concatenates two sparse gensim vectors. The dimension of the first will be added to all keys of the second. """ result = sparse1 concat_sparse2 = ...
""" Unittests for the rpc.urlhelpers module """ import sys import unittest if sys.version_info < (2, 7): import unittest2 as unittest from rpc import urlhelp class ProtocoliseTestCase(unittest.TestCase): def test_leave_it_alone(self): """ These are already valid, leave them be""" cases = [ ...
#! /usr/bin/env python3 ''' Slurp module to replace all instances of [["versionIdentifier"]] with a version identifier. ''' from argparse import ArgumentParser import datetime from envVars import fillInValues from slurp_common.SlurpItem import SlurpItem # https://stackoverflow.com/questions/24937495/how-can-i-calcul...
import unittest from dlt.field import Field class FieldTest(unittest.TestCase): def test_field_init_without_value(self): field = Field("name") self.assertEqual(field.name, "name") self.assertEqual(len(field), 0) self.assertIsNone(field.line_number) field.add_content("value ...
import os import collections import treesoup tag_to_method = {} signatures = {} tag_to_attrs = {} tag_to_children = {} tag_to_common = {} data_to_source = {} method_to_args = {} for filename in os.listdir('methods'): xml = treesoup.parse(open('methods/' + filename).read().decode('utf8')) if not xml.resp...
import json from calvin.csparser.parser import calvin_parser from calvin.actorstore.store import DocumentationStore import json class Checker(object): # FIXME: Provide additional checks making use of # - actor_def.inport_names and actor_def.outport_names # - make use of arg_type (STRING, NUM...
class _Container: pass class AIFuncs: def __init__(self, name=None): import sys import inspect # We import the specified module name (or the caller's module prefixed with '_', if None) from the caller's context. # This is fairly hackish, but probably makes for the most convenient ...
#!/usr/bin/python """Updates the tzdata file.""" import ftplib import httplib import os import re import subprocess import sys import tarfile import tempfile # Find the bionic directory, searching upward from this script. bionic_libc_tools_zoneinfo_dir = os.path.realpath(os.path.dirname(sys.argv[0])) bionic_libc_too...
import unittest from importlib import resources from . import data01 from . import util class CommonBinaryTests(util.CommonResourceTests, unittest.TestCase): def execute(self, package, path): with resources.open_binary(package, path): pass class CommonTextTests(util.CommonResourceTests, uni...
from __future__ import print_function import sys import config from entities import global_symbols from expr import expr_eval, Variable from exprtools import parse entity_required = \ "current entity is not set. It is required to set one using " \ "the 'entity' command before evaluating any query"...
from __future__ import unicode_literals import sys from .base import BaseCommand from ..utils import uni_print from ..constants import HTTP_OK_NO_CONTENT class RbCommand(BaseCommand): command = "rb" usage = "%(prog)s <bucket> [-c <conf_file> --force]" @classmethod def add_extra_arguments(cls, pars...
import os import sqlite # Ok, let's define a user-defined type we can use with the SQLite database class Point: def __init__(self, x, y): self.x, self.y = x, y # The _quote function is currently the way a PySQLite user-defined type # returns its string representation to write to the database. ...
import numpy as np import math def sigmoid(x): return 1 / (1 + math.exp(-x)) class Neuron: def __init__(self, dim, learning_rate = 0.1): self.w = -1+2*np.random.random((dim+1)) self.learning_rate = learning_rate self.y = 0 def sum_value(self, x): # print self.w # pri...
#!/usr/bin/env python # -*- coding: utf 8 -*- """ Python installation file. """ from setuptools import setup import re verstr = 'unknown' VERSIONFILE = "striplog/_version.py" with open(VERSIONFILE, "r")as f: verstrline = f.read().strip() pattern = re.compile(r"__version__ = ['\"](.*)['\"]") mo = pattern.se...
from odoo.tests.common import SavepointCase from odoo.exceptions import ValidationError class TestProjectHr(SavepointCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user_model = cls.env['res.users'] cls.user = cls.user_model.create({ 'login': 'test_project...
from htmldiffer import diff from toggles import shingle_settings import utils class WARCCompare: def __init__(self, warc1_path, warc2_path): self.warc1 = utils.expand_warc(warc1_path) self.warc2 = utils.expand_warc(warc2_path) missing, added, modified, unchanged = utils.sort_resources(se...
import os, csv, sqlite3 def get_header_index(file): '''Return list of index values of the necessary headers''' fips = 'area_fips' own_code = 'own_code' naics = 'industry_code' year = 'year' disclosure_code = 'disclosure_code' establishments = 'annual_avg_estabs' employees = 'annual_avg_...
from __future__ import annotations from datetime import ( datetime, timedelta, ) import warnings from dateutil.relativedelta import ( # noqa FR, MO, SA, SU, TH, TU, WE, ) import numpy as np from pandas.errors import PerformanceWarning from pandas import ( DateOffset, Dat...
from itertools import izip from django.db.models.query import sql from django.db.models.fields.related import ForeignKey from django.contrib.gis.db.backend import SpatialBackend from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql import aggregates as gis_aggregates_modul...
from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .._matchesfilterbase import MatchesFilterBase #----------------...
'''Unit tests for grit.format.rc''' import os import re import sys if __name__ == '__main__': sys.path[0] = os.path.abspath(os.path.join(sys.path[0], '../..')) import tempfile import unittest import StringIO from grit import grd_reader from grit import util from grit.node import structure from grit.tool import bui...
from datetime import datetime from nomenklatura.core import db from nomenklatura.model.common import make_key class Account(db.Model): __tablename__ = 'account' id = db.Column(db.Integer, primary_key=True) github_id = db.Column(db.Integer) login = db.Column(db.Unicode) email = db.Column(db.Unico...
from typing import TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Optional from azure.core.credentials import TokenCredential from azure.core.pipeline.t...
""" Django settings for PortfolioSute project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ imp...
"""Recursive decent parser""" # pylint: disable=too-few-public-methods import json import re class State(object): """Current parser state""" text = "" position = 0 rules = [] last_expectations = [] def __init__(self, **kwargs): self.__dict__.update(kwargs) def to_json(self): ...
import unittest import asyncio import shutil import os import yarl import aiohttp from json import JSONDecodeError from snare.utils.asyncmock import AsyncMock from snare.html_handler import HtmlHandler from snare.utils.page_path_generator import generate_unique_path class TestGetDorks(unittest.TestCase): def setU...
#!/usr/bin/python import os import sys import symbol from symbol import cfg import csv import argparse import traceback if __name__ == "__main__": try: parser = argparse.ArgumentParser(description = 'Symbol generator from csv table.') parser.add_argument('--csv', type = str, help = 'CSV formatted ...
# 402. Remove K Digits # Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. # # Note: # # The length of num is less than 10002 and will be ≥ k. # The given num does not contain any leading zero. # # Example 1: # # Input: nu...
import json def instructor_to_student(instructor_ipynb): ''' Removes all the output of the cells and the code of these cells without a keep flag in their metadata, but keeps the commented lines. ''' with open(instructor_ipynb, 'r') as file_instructor: notebook = json.load(file_instruc...
from editablelistbox import * from companions import * from box import * from poujolobjs import * import wx import platform from choosename import choose_a_name class SpeculoosEditableListBox(EditableListBox): default_class = "object" def __init__(self, speculoos, parent, id, title): EditableListB...
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.d...
from heatclient import exc import keystoneclient from heat_integrationtests.functional import functional_base class ServiceBasedExposureTest(functional_base.FunctionalTestsBase): # NOTE(pas-ha) if we ever decide to install Sahara on Heat # functional gate, this must be changed to other not-installed # bu...
from Products.CMFPlone.utils import safe_unicode from bika.lims.controlpanel.bika_analysisservices import AnalysisServicesView from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from plone.app.content.browser.interfaces import IFolderContentsView from zope.interface import implements class Ac...
import requests import requests.exceptions from tieronepointfive.enums import State, Transition from tieronepointfive.evaluation_helpers.transitions import get_best_transition, TransitionRule class HttpHelper: def __init__(self, config): self._config = config def evaluate(self, tick, **kw...
# coffee_leaderboard/utils.py import math from coffee_leaderboard.database import UserProfile, CoffeeEntry def generate_xp_table(base_level=700, factor=0.85): xp_next_level = base_level # baseline of 1 cup a day? max_level = 20 xp_table = [] for i in range(1, max_level + 1): xp_...
{ 'name': 'RMA Claim (Product Return Management)', 'version': '1.1', 'category': 'Generic Modules/CRM & SRM', 'description': """ Management of Return Merchandise Authorization (RMA) ==================================================== This module aims to improve the Claims by adding a way to manage the...
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # File: training_policy.py import numpy as np from lib.progress import Progressor import sys class TrainPolicy(object): def __init__(self, train_model, valid_model, n_batches, logger, learning_rate_provider, test_model = None): self.train_m...
""" UDP support for IOCP reactor """ import socket, operator, struct, warnings, errno from zope.interface import implements from twisted.internet import defer, address, error, interfaces from twisted.internet.abstract import isIPAddress, isIPv6Address from twisted.python import log, failure from twisted...
import re from tempoiq.protocol import Device, Sensor class MigrationScheme(object): name = "MigrationScheme" db_key = "" db_secret = "" db_baseurl = "https://api.tempo-db.com/v1/" iq_key = "" iq_secret = "" iq_baseurl = "https://sandbox-matt.backend.tempoiq.com" def identity_series_...
from __future__ import print_function import frappe import pytz from frappe import _ from oauthlib.oauth2.rfc6749.tokens import BearerToken from oauthlib.oauth2.rfc6749.grant_types import AuthorizationCodeGrant, ImplicitGrant, ResourceOwnerPasswordCredentialsGrant, ClientCredentialsGrant, RefreshTokenGrant, OpenIDCon...
from fsa import * import copy def create(start, finals, edges): states = {} for e in edges: if e[1] is None: states.setdefault(e[0], ({}, []))[1].append(e[2]) else: states.setdefault(e[0], ({}, []))[0][e[1]] = e[2] states.setdefault(e[2], ({}, [])) stat...
from django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test class HypervisorViewTest(test.BaseAdminViewTests): @test.create_stubs({api.nova: ('extension_supported', ...
from BitTornado.zurllib import urlopen from urllib import quote from btformats import check_peers from BitTornado.bencode import bdecode from threading import Thread, Lock from cStringIO import StringIO from traceback import print_exc from socket import error, gethostbyname from random import shuffle from sha ...
import os from conary.lib import util from conary_test import rephelp recipe1=""" class TestTestComponent(PackageRecipe): name = 'testpkg' version = '1.0' clearBuildReqs() def setup(r): r.Run('''mkdir TestFoo; touch TestFoo/bar; touch Makefile''') ...
"""graduate work Задание: Вывести список групп в ВК в которых состоит пользователь, но не состоит никто из его друзей. В качестве жертвы, на ком тестировать, можно использовать: https://vk.com/tim_leary Входные данные: имя пользователя или его id в ВК, для которого мы проводим исследование Внимание: и имя пользователя...
'''runner for neuron morphology checks''' import logging from importlib import import_module from future.moves.collections import OrderedDict from neurom.check import check_wrapper from neurom.exceptions import ConfigError from neurom.fst import _core as fst_core from neurom.io import load_data, utils L = logging.g...
import Graph from numpy import sqrt as sqrt from collections import defaultdict def make_data_vertex(file_name, number_of_vertex): graph = Graph.Graph() with open(file_name, 'r') as f: number = f.readline().rstrip().split() nodes = defaultdict(list) edges = [] what_can = range(...