content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ SQLAlchemy-SQLSchema ----------------------- Provides a contextmanager with the capability to set the SQL schema for a connection or session. The schema will persist through multiple transactions. """ import sys import os from setuptools import setup if sys.version_info < (2, 6): raise...
# BS mark.1-55 # /* coding: utf-8 */ # BlackSmith plugin # timer_plugin.py # Coded by: WitcherGeralt (WitcherGeralt@jabber.ru) # http://witcher-team.ucoz.ru/ TCMDS = [u'пинг', u'тест', u'сказать', u'чисть', u'анекдот', u'тык', u'ботап', u'топик', u'призвать', u'участник'] TIMERS = {'col': 0, 'tmrs': {}} def time...
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved # # 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 applic...
''' Created on 27 Apr 2018 @author: shashwatjain ''' from math import atan2, cos, sin, acos, pi import numpy as np d_base = 0.75 a_1 = 0.35 a_2 = 1.25 a_3 = -0.054 d_3 = 1.5 d_6 = 0.303 # theta1, theta2, theta3, alpha2, beta2, alpha3 = arm_IK(2, 1, 2) def limit_angle(theta, min, max): ''' Check that angles are...
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.connsql, name='connsql'), path('loginuser',views.loginuser, name='loginuser'), ]
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from ..utils.vocab import Vocab class MultiChannelEmbedding(nn.Module): """MultiChannelEmbedding class""" def __init__(self, vocab: Vocab) -> None: """Instantiating MultiChannelEmbedding class Args:...
import omi from omi import * import schema def Load (module, context): be = BookEnd ('Load (OMI_Tester module)') context.PostResult (MI_RESULT_OK) def Unload (module, context): be = BookEnd ('Unload (OMI_Tester module)') context.PostResult (MI_RESULT_OK) def OMI_Tester_Load ( module, context)...
""" Helper functions for probability distributions. """ import os from .cupy_utils import betaln, erf, xp def beta_dist(xx, alpha, beta, scale=1): r""" Beta distribution probability .. math:: p(x) = \frac{x^{\alpha - 1} (x_\max - x)^{\beta - 1}}{B(\alpha, \beta) x_\max^{\alpha + \beta + 1}} ...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import Candidacy, Applicant, CustomUser, Company, Opportunity class CompanySingupForm(UserCreationForm): name = forms.CharField(required=True, label="Nome da Empresa") cnpj = forms.Ch...
import os import requests #请求库 from urllib import request # 下载图片用 from lxml import etree #网络解析库 from queue import Queue #队列 import threading import re import csv #生产者 页面队列取出 然后下载页面中的 图片url 放入图片队列 class Producer(threading.Thread): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Appl...
import example_lib from dt_gui_base import gui_context_object as base_gui_context_object class gui_context_object(base_gui_context_object, example_lib.cli_context_object): def __init__(self, args, db_def, glade_files): example_lib.cli_context_object.__init__(self, args, db_def) base_gui_context_o...
from Utility.Types.Enums.Camera_Model_Types import CameraModelTypes from Utility.Classes.Frozen_Class import FrozenClass class CalibrationParameter(object): def assert_float_or_int(self, value): assert type(value) == float or type(value) == int def __init__(self, sc, camera_model_type, f, fx, fy, cx,...
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
""" .. currentmodule:: flytekitplugins.kftensorflow This package contains things that are useful when extending Flytekit. .. autosummary:: :template: custom.rst :toctree: generated/ TfJob """ from .task import TfJob
import apricot import math import numpy as np import torch from scipy.sparse import csr_matrix from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.utils.data import Subset from torch.utils.data.sampler import SubsetRandomSampler from .calculate_class_budgets import calculate_class_...
from __future__ import absolute_import import sys def main(argv): arg1 = sys.argv[1]
# A program that calculates the dimensions of a shape (Area, Perimeter, Volume) with user specifics. # Made by Aryan Takalkar # importing import pyttsx3 as speech from time import sleep # Initializing class UI class UI(): def __init__(self): self.running = True self.speechEngine = s...
""" 8. scatter 散点数据 """ import matplotlib.pyplot as plt import numpy as np n = 1024 # 中位数是0,方差是1,一共n个数 X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(Y,X) # for color value plt.scatter(X, Y, s=75, c=T, alpha=0.5) plt.xlim((-1.5, 1.5)) plt.ylim((-1.5, 1.5)) plt.xticks(()) plt.yticks(()) pl...
""" Copyright 2020 Fazt Community ~ All rights reserved. MIT license. """ import logging logging.basicConfig( filename="latest.log", filemode="w", level=logging.DEBUG, format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:%(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) console = logging.StreamHandl...
def func(n): f1, f2 = 1, 1 remains = n while remains > 2: f1, f2 = f1+f2, f1 remains -= 1 return f1 def main(): f10 = func(10) print(f10) if __name__ == '__main__': main() # import cProfile # cProfile.run('main()')
t = int(input()) for cont in range(t): si = input() teste = si[4] if not teste.isdigit(): print("Novo") else: print("Antigo")
# import unittest # # from classifier.prediction.models.DatasetWrapper import DatasetWrapper # # # class DatasetWrapperTests(unittest.TestCase): # # if __name__ == '__main__': # unittest.main() # # def testsDatasetWrapper(self): # X = [[1,10], [2, 20], [3, 30]] # Y = [[101, 110], [102, 1...
# used for validating multiple keys when one changes import operator from functools import reduce from typing import List, Set, Optional, Union, Any, Dict, Iterable from django.contrib.auth.models import User from django.db.models import Q from classification.enums import SpecialEKeys from classification.models.evide...
import maya.cmds as mc do_not_remove = ['MayaWindow', 'nextFloatWindow'] def do_it(): for _w in mc.lsUI(windows=1): if _w not in do_not_remove: mc.deleteUI(_w) mc.windowPref(_w, remove=1) print('# cleanup ui ', _w)
'''Runs all of the plotting codes for clusters''' import matplotlib.pyplot as plt import initialize_mosdef_dirs as imd from astropy.io import ascii from bpt_clusters import plot_bpt_cluster from emission_measurements import read_emission_df from plot_mass_sfr import plot_mass_sfr_cluster, read_sfr_df, get_all_sfrs_mas...
from MyDbTransactionerMeta import MyDbTransactionerMeta #from Transactioner import Transactioner class MyDbTransactioner(metaclass=MyDbTransactionerMeta): #T = Transactioner('sqlite:///mydb.db') @T.transact() def CreateTable(self, db, table_name, **name_types): columns = ', '.join(k+' '+v for ...
# coding: utf-8 # In[1]: import numpy as np import csv import os import random import matplotlib.pyplot as plt get_ipython().magic(u'matplotlib inline') # In[21]: a = np.ones(shape=[3,2]) b = np.random.rand(3,2) print a print b c = b>0.5 print c m = np.multiply(b,c) print m # In[4]: sizes = [10,5,2,2] W = ...
from .syzygy import SyzygyAuthenticator from jupyterhub.handlers import BaseHandler from tornado import web from traitlets import Unicode, Set class RemoteUserLoginHandler(BaseHandler): async def get(self): self.statsd.incr('login.request') user = await self.get_current_user() if user: ...
import numpy import six import cupy from cupy import core from cupy import internal from cupy.linalg.solve import inv from cupy.util import collections_abc matmul = core.matmul def dot(a, b, out=None): """Returns a dot product of two arrays. For arrays with more than one axis, it computes the dot product...
""" Useful constant variables """ from pathlib import Path PROJECT_ROOT = Path(__file__).parent ASSETS_PATH = PROJECT_ROOT / 'tmp' / 'articles' CRAWLER_CONFIG_PATH = PROJECT_ROOT / 'scrapper_config.json' HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' ...
#!/usr/bin/env python3 import uuid from setuptools import setup, find_packages from pip.req import parse_requirements # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements("requirements.txt", session=uuid.uuid1()) # reqs is a list of requirement # e.g. ['djan...
""" Fuzzy Set Operations """ from typing import Dict, List def union(set1: Dict[str, int], set2: Dict[str, int]) -> Dict[str, int]: elements1 = {key for key, value in set1.items()} elements2 = {key for key, value in set2.items()} elements = elements1.union(elements2) result = {} for e in elements...
from bs4 import BeautifulSoup import urllib.request as req def getResponse(url): response = req.urlopen(url) data = response.read() soup = BeautifulSoup(data, "html.parser") # print(soup.prettify("utf-8")) return soup def get_movie_name(genre): movieList = [] url = "https://www.imsdb.com...
import torch.nn as nn from cnn_adaout import adaout, LinearScheduler import torch.nn.init as init class Block(nn.Module): def __init__(self, inplanes, planes): super(Block, self).__init__() self.conv = nn.Conv2d(inplanes, planes, kernel_size=5, stride=1, padding=2) self.bn = nn.BatchNorm2...
# Cat class class Cat: # constructor def __init__(self, name, color): self.name = name self.color = color # cry method def cry(self): return "Meow! Meow!!" # sam, an instance of the Cat class sam = Cat("Sam", "brown"); print(f"Hello, my name is {sam.name}") print(f"{sam.name}, which is me, is {sam.color}...
# Definition for a binary tree node class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return "{}".format(self.val) class Solution: def lowestCommonAncestor(self, root, p, q): """ :type root: ...
import threading import time from datetime import datetime import pyodbc import board import busio import adafruit_bme280 #weather variables minTemp = 1000 maxTemp = 0 temp9am = 0 temp3pm = 0 humidity9am = 0 humidity3pm = 0 pressure9am = 0 pressure3pm = 0 mlp = 0.0 tl = 0 now = datetime.now().time() i2c = busio.I2C(...
from urllib.request import urlopen from bs4 import BeautifulSoup import csv our_url = "https://www.census.gov/programs-surveys/popest.html" html = urlopen(our_url) # Insert your URL to extract bsObj = BeautifulSoup(html.read()); i = 0 foo_bar = "" for link in bsObj.find_all('a', href=True): i += 1 link_end...
"""Config flow for Vconnex integration.""" from __future__ import annotations import logging from typing import Any from .py_vconnex.api import VconnexAPI import voluptuous as vol from homeassistant import config_entries from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResul...
""" Code to enable coverage of any external code called by the notebook. """ _python_setup = """\ import coverage __cov = coverage.Coverage(source=%r, config_file=%r, data_suffix='nbval') __cov.start() """ _python_teardown = """\ __cov.stop() __cov.save() """ def setup_coverage(config, kernel, floc, output_loc=None...
mindsdb_version="0.7.2"
from django import forms from django.contrib.auth.forms import AuthenticationForm, UsernameField, UserCreationForm from django.contrib.auth.models import User from News.models import Post, Category, Comment class PostEditForm(forms.ModelForm): class Meta: model = Post exclude = [ 'pub...
from django.conf import settings from lego.apps.action_handlers.handler import Handler from lego.apps.action_handlers.registry import register_handler from lego.apps.companies.models import CompanyInterest from lego.apps.companies.notifications import CompanyInterestNotification from lego.apps.feeds.activity import Ac...
from django.conf.urls import url from django.contrib.auth.views import logout_then_login urlpatterns = [ # Authentication url(r'^login/$', 'cripts.core.views.login'), url(r'^logout/$', logout_then_login), # Buckets url(r'^bucket/list/$', 'cripts.core.views.bucket_list'), url(r'^bucket/list/(?...
from util.functions import print3 print("Input all correct ways to write a simple program which prints a string in Python.") print("1") print('print("Hello")') print("2") print(' print("Hello") ') print("3") print('print(Hello)') print("4") print("print('Hello')") print("Hint: Here there are two right ways to pr...
# Route imports from api.routes.Stories import StoriesHandler from api.routes.Story import StoryHandler # UNUSED (delete?). from api.routes.Stories import StoriesByUserHandler from api.routes.Users import UsersHandler, UserHandler from api.routes.Categories import CategoriesHandler, CategoryHandler, CategoryTopicsHandl...
from .iode import *
#!/usr/bin/env python ## Program: Pype Pad ## Module: $RCSfile: pypepad.py,v $ ## Language: Python ## Date: $Date: 2006/05/26 12:36:30 $ ## Version: $Revision: 1.6 $ ## Copyright (c) Luca Antiga, David Steinman. All rights reserved. ## See LICENCE file for details. ## This software is distribut...
import cv2 as cv import numpy as np R, G, B = (0x00, 0x00, 0xFF), (0x00, 0xFF, 0x00), (0xFF, 0x00, 0x00) def detect(frame, hog): # 3B locs, _ = hog.detectMultiScale(frame, finalThreshold=3) trackers, are_tracked = [], [] result = frame.copy() for (x, y, w, h) in locs: x, y, w, h = x + w * 1 ...
from django.shortcuts import redirect from django.test import TestCase from django.urls import reverse from gogoedu.models import myUser, Lesson, Word, Catagory, Test, UserTest, Question, Choice, UserAnswer, UserWord,TestResult class CatagoryListViewTest(TestCase): @classmethod def setUpTestData(cls): #...
import copy import unidecode import unicodedata import itertools import re import json import gensim import cPickle as pkl import codecs import string import nltk import sys import csv import spacy from regex4dummies import regex4dummies from regex4dummies import Toolkit from annoy import AnnoyIndex tool_tester = Toolk...
import requests import pandas as pd import numpy as np from stock.lib.daily import daily_adjusted_ohlc from stock.lib.intraday import intraday_ohlc from stock.lib.technicals.indicators import sma, bbands from stock.lib.fundamentals.company_info import * from stock.lib.fundamentals.earnings import * def main(): d...
# Copyright 2016 Stanford University # # 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 law or agreed to in w...
# coding=utf-8 from gensim.models import word2vec import pandas as pd from gensim.test.utils import get_tmpfile import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) txt=pd.read_csv('./out/020train_w2v_temp_data.txt',sep='\t',header=None) words=[] for i i...
""" SideChainNet A protein structure prediction data set that includes sidechain information. Directly extends ProteinNet by Mohammed AlQuraishi. """ import os _ROOT = os.path.abspath(os.path.dirname(__file__)) def get_data(path): """Return absolute path to specified package resource. Args: path (s...
import sys import json ################################################ import network import utils from utils import printflush as pf ################################################ MAX_ARGS = 10 ################################################ ints = [None] * MAX_ARGS floats = [None] * MAX_ARGS def get_int(i...
# Copyright 2017 DiCITS UGR # # 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 law or agreed ...
# -*- coding: utf-8 -*- """ Created on Fri Jun 01 15:21:46 2018 @author: Daniel Streater, Suhas Somnath """ from __future__ import division, print_function, absolute_import, unicode_literals from os import path, remove import sys import numpy as np import h5py from sidpy.sid import Translator from sidpy.hdf.hdf_util...
# -*- coding: utf-8 -*- import tornado.web from .base import BaseHandler class MainPageHandler(BaseHandler): @tornado.web.authenticated def get(self): sources = [(v[0], v[2], v[3]) for v in self.videos] self.render('index.html', sources=sources) class SourcePageHandler(BaseHandler): ...
from colosseum.mdps.river_swim.episodic.mdp import RiverSwimEpisodic MDP = RiverSwimEpisodic
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models import CMSPlugin from filer.fields.image import FilerImageField from filer.fields.file import FilerFileField from django.utils.encoding import smart_unicode class Stripe(models.Model): nam...
#!/usr/bin/env python3 import os import json from templates import login_page import cgitb cgitb.enable() print("Content-Type: text/html\n") print() print("<!doctype html><title>Hello</title><h2>CGI LAB</h2>") #Q2: What environment variable contains the query parameter data? #print("Content-Type: application/json") ...
from django_markup.filter import MarkupFilter class TextileMarkupFilter(MarkupFilter): title = 'Textile' def render(self, text, **kwargs): from textile import textile return textile(text, **kwargs)
''' A simple greeting module ''' def hello(name='World'): ''' >>> hello() Hello World! >>> hello('buddy') Hello buddy! ''' print(f'Hello {name}!')
from .. import force from .. import geometry class slipFactor: ''' Attributes sFactor:Slipping safety factor ''' def __init__(self,upstreamWaterPressure,downstreamWaterPressure,maxFriction): self.sFactor=abs(maxFriction.f/(upstreamWaterPressure.fx+downstreamWaterPressure.fx)) ...
import os import sys import time import threading import json import datetime import random from pathlib import Path import zipfile class Watcher(object): running = True refresh_delay_secs = 1 # Constructor def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs): ...
import sys import json print(sys.argv) #AthleticsNewsTableArn=sys.argv[1] #BlogsTableArn=sys.argv[2] #ClubsTableArn=sys.argv[3] #EventsTableArn=sys.argv[4] #GetESDocumentsLambdaArn=sys.argv[5] #NewsTableArn=sys.argv[6] GetESDocumentsLambdaArn=sys.argv[1] DocumentsTableArn=sys.argv[2] #arnList=[AthleticsNewsTableArn,...
from __future__ import annotations from dataclasses import dataclass @dataclass class Node: """ ## Fields: ```py value: any next: Node | None prev: Node | None ``` """ value: any next: Node | None prev: Node | None __slots__ = "value", ...
# Create your views here. from rest_framework import status, viewsets from products import models from .serializers import ProductSerializer, ProductAttributeSerializer, ProductPriceSerializer from rest_framework.response import Response from rest_framework.decorators import action from django.core import serializers ...
#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko import sys reload(sys) sys.setdefaultencoding("utf-8") hostname = '192.168.125.126' username = 'root' password = '123456' port=22 try: t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPCli...
""" implements geometry purification for the distance geometry algorithm This is used to clean up the structure of the molecule and enforce correct chirality, by minimizing an error function. The error function is minimized using the conjugate gradients method: 1. Calculate the steepest direction: dn = - grad(Er...
########################################################################## # NSAp - Copyright (C) CEA, 2016 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ##########...
from __future__ import absolute_import, unicode_literals from django.db import models from wagtail.core import blocks from wagtail.core.models import Page from wagtail.core.fields import RichTextField, StreamField from wagtail.images.blocks import ImageChooserBlock class HomePage(Page): pass class BlogPage(Pa...
import mock from olympia.amo.tests import addon_factory, TestCase, user_factory from olympia.reviews.models import Review from olympia.reviews.tasks import addon_review_aggregates class TestAddonReviewAggregates(TestCase): # Prevent <Review>.refresh() from being fired when setting up test data, # since it'd ...
#!/usr/bin/env python import sys import time from progressBar import update_prog from commands import getoutput from multiprocessing import Process #tumbleweed.py is part of the Lariat tool #Author: sean.m.donnelly@navy.mil '''takes a file name as a parameter and determines if the URLs in the file are operational a...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ Main ...
""" align_funcs.py The alignment algorithm takes in TextGrid classes and extracts meaningful data. This information consists of the beginning of a phoneme's utterance, its end, and its phonemic transcription. With this information the program finds the edit distance between two given utterances, ph...
""" This defines classes that can be used to implement a series of Actions. """ from benchbuild.settings import CFG from benchbuild.utils.db import persist_experiment from benchbuild.utils.run import GuardedRunException from plumbum import local from benchbuild.utils.cmd import mkdir, rm, rmdir from plumbum import Pro...
# ABC025a import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) s = sorted(list(input()[:-1])) # print(s) n = int(input()) print(s[(n-1)//5]+s[(n-1) % 5])
from io import BytesIO from rivr.http.request import Query, Request def test_query_parse() -> None: query = Query('message=Hello+World') assert query['message'] == 'Hello World' def test_query_from_dict() -> None: query = Query( { 'message': 'Hello World', } ) asse...
import sys import augment import torch import random import numpy as np import torchaudio from torchaudio.compliance import kaldi import nlpaug.augmenter.audio as naa from espnet2.bin.enh_inference import SeparateSpeech from torchaudio_augmentations import RandomApply, Compose from vistec_ser.data.featu...
# This is print new line print("this is awesome")
import json if __name__ == '__main__': #Open 'testbench_manifest.json' with open('testbench_manifest.json', 'r') as f_in: testbench_manifest = json.load(f_in) #Add metrics print "Saving Metrics to testbench_manifest.json..." for metric in testbench_manifest["Metrics"]: if ...
# External dependencies import argparse import logging import os.path # Custom dependencies from twittersupervisor import LoggingConfig, ConfigFileParser, Database, Messaging, TwitterApi # Default values config_file_name = "config.json" # Command line parsing parser = argparse.ArgumentParser(prog="twitter-supervisor"...
#!/usr/bin/env python ''' Build a cms.PSet desribing a "Tanc transformation". The TaNC transformation f(x) transforms the neural network output x of a tau candidate such that f(x) is the probability that it is a true tau. The transformation "t" format is a cms.vdouble, where the ith entry is the value of f(x) at x ...
try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension setup( ext_modules=[ Extension( "hit", ["hit.cpp", "lex.cc", "parse.cc"], extra_compile_args=...
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker Base = declarative_base() Session = sessionmaker() class SlackTeams(Base): __tablename__ = 'slack_teams' id = Column(Integer, prim...
# stdlib import os try: from urllib.request import build_opener, install_opener except ImportError: from urllib2 import build_opener, install_opener # tool modules from tests.mock_urllib import MockHTTPHandler # third party modules import pytest @pytest.fixture def patch_PB_CONFIG(monkeypatch): """Monk...
import rita def setup_spacy(model, patterns=None, rules_path=None, rules_string=None, override_ents=True): from spacy.pipeline import EntityRuler ruler = EntityRuler(model, overwrite_ents=override_ents) if not patterns: if rules_path: patterns = rita.compile(rules_path, use_engine="spa...
import pytest from roa import read_only_attributes def test_attribute_immutable_error(): @read_only_attributes("x") class MyClass: def __init__(self, x): self.x = x mc = MyClass(1) with pytest.raises(AttributeError): mc.x = 3 def test_attribute_mutable(): @read_only_...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ...
from sqlalchemy_utils import get_class_by_table from werkzeug.routing import UnicodeConverter, ValidationError from app.models import Word class WordClassConverter(UnicodeConverter): """ Converts a word class string into a class. """ def to_python(self, value): try: word_class = get_clas...
{ "cells": [ { "metadata": { "_kg_hide-output": true, "_uuid": "82dba2dc7059a766fe05ddb328c6acb60533dd8f" }, "cell_type": "markdown", "source": "# Package Imports\nAll the necessary packages and modules are imported in the first cell of the notebook" }, { "met...
""" Implements a tabular version of maximum entropy inverse reinforcement learning (Ziebart et al, 2008). There are two key differences from the version described in the paper: - We do not make use of features, which are not needed in the tabular setting. - We use Adam rather than exponentiated gradient descent. ""...
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # TODO: (FreeBSD) add test for comparing connections with 'sockstat' cmd. """Tests specific to all BSD platforms.""" import date...
from django.views.generic import ListView, DetailView,CreateView,UpdateView,DeleteView from .models import Thing from django.urls import reverse_lazy class ThingListView(ListView): template_name = "things/thing_list.html" model = Thing class ThingDetailView(DetailView): template_name = "things/thing_deta...
import numpy as np import keras.backend.tensorflow_backend as backend from keras.models import Model, Sequential from keras.layers import Input, Dense, concatenate #, Dropout, Conv2D, MaxPooling2D, Activation, Flatten from keras.optimizers import Adam from keras.callbacks import TensorBoard import tensorflow as tf from...
# -*- coding: utf-8 -*- """Top-level package for pixell.""" __author__ = """Simons Observatory Collaboration Analysis Library Task Force""" __email__ = '' __version__ = '0.4.2'
# -*- encoding=utf-8 -*- import wechat_bot wechat = wechat_bot.wechat_bot(local=True) config = wechat.config for plugin in config['plugins']: plugin['module'].test() test = ['test', 'reloadconfig', 'updateupdate!', u'测试.'] for t in test: msg = {'Text': t, 'FromUserName': '@dajflsdkfjs', 'Type': 'Text'} ...
# proxy module from enable.savage.svg.backends.null.null_renderer import *