content
stringlengths
5
1.05M
#!/usr/bin/env python3 # switch.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC def main(): print('this is the switch.py file') # Equivalent to case/switch statements choices = dict( one = 'first...
import json, pickle, time, copy from Louis.ARC_data.objects import * from program import * def pickle_read(filename): with open(filename, 'rb') as f: ret = pickle.load(f) return ret def pickle_write(filename, data): with open(filename, 'wb') as f: pickle.dump(data, f) def json_read(filena...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from gaiatest import GaiaTestCase from gaiatest.apps.system.regions.cards_view import CardsView from gaiatest.apps.syste...
from src.cart import CartProduct from src.product.products import Product class Client(object): def __init__(self, name, wallet=None): """ Supermarket client >>> wilson = Client(name='Wilson', wallet=10.00) >>> sweet_potato = Product(name='sweet_potato', sku='001', price=1.00, cost...
import sqlite3 # form connection to 'demo_data' sqlite3 db conn = sqlite3.connect('demo_data.sqlite3') # create cursor curs = conn.cursor() # set schema for the 'demo' table create_demo_table = (""" CREATE TABLE demo ( s CHAR(1), x INT, y INT ) """) # create the table in demo_data db...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import time import sys import paddle import paddle.fluid as fluid #import reader_cv2 as reader import reader as reader import argparse import functools from utility import add_argume...
import os from http import HTTPStatus from flask import request from flask_cors import cross_origin from app.controllers.hodler import HodlerController from app.controllers.token import TokenController from app.controllers.watcher import WatcherController from app.tasks.blockchain import ( blockchain_events_sync_...
import json import logging import mongoengine as me import rmc.shared.util as util class AggregateRating(me.EmbeddedDocument): rating = me.FloatField(min_value=0.0, max_value=1.0, default=0.0) count = me.IntField(min_value=0, default=0) sorting_score_positive = me.FloatField( min_value=0.0, max_...
# pylint: disable=invalid-name,no-self-use import json import os import numpy from numpy.testing import assert_almost_equal from deep_qa.run import compute_accuracy from deep_qa.run import run_model_from_file, load_model, evaluate_model from deep_qa.run import score_dataset, score_dataset_with_ensemble from deep_qa.te...
#!/usr/bin/env python """ MySQL implementation of GetChecksum """ from WMCore.Database.DBFormatter import DBFormatter class GetChecksum(DBFormatter): sql = """SELECT cst.type AS cktype, fcs.cksum AS cksum FROM wmbs_file_checksums fcs INNER JOIN wmbs_checksum_type cst ...
from nose.tools import ( eq_, set_trace, ) from ...util.web_publication_manifest import ( JSONable, Manifest, AudiobookManifest, ) from .. import DatabaseTest class TestJSONable(object): class Mock(JSONable): @property def as_dict(self): return dict(value=1) d...
def get_type(value): try: int(value) return "int" except ValueError: try: float(value) return "float" except ValueError: return "string" if __name__ == '__main__': input_value = input("Enter value: ") print(get_type(input_value)) ...
# -*- coding: utf-8 -*- """Runs various benchmarks on the Yaklient package"""
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 # 默认实例变量 def get_describe_name(self): """ 打印车子的基本信息 :return: long_name """ long_name = f"{self.year} {self.ma...
from chainer.backends import cuda from chainerkfac.optimizers.fisher_block import compute_pi from chainerkfac.optimizers.fisher_block import FisherBlock class FisherBlockConnection(FisherBlock): def __init__(self, *args, **kwargs): self._A = None self._G = None super(FisherBlockConnectio...
from bpy_extras.io_utils import ExportHelper from bpy.props import StringProperty, BoolProperty, EnumProperty from bpy.types import Operator import bpy import os import re import uuid import mathutils import json bl_info = { "name": "Export to ARENA (to folder)", "author": "Nuno Pereira", "version": (0, 1,...
import numpy as np print('test run') a = np.asarray([1,2,3]) print(str(a))
#!usr/bin/env python3.7 #-*-coding:utf-8-*- import discord from src.discord.database.exceptions import * from src.discord.database.dataformat import * class Table: def __init__(self,db,name): self.db = db self.name = name if not Table.exists(db, name): raise TableDoesNotExist(d...
# coding=utf-8 # !/usr/bin/python3.6 ## Please use python 3.6 """ __synopsis__ : Matching Networks for Extreme Classification. __description__ : Metrics (Precision@k and NDCG@k) for Matching Networks for Extreme Classification. __project__ : MNXC __author__ : Vishwak, Samujjwal Ghosh __version__ : "0.1...
import requests from bs4 import BeautifulSoup from pprint import pprint import json response = requests.get('https://news.ycombinator.com/news') soup = BeautifulSoup(response.text, 'html.parser') links = soup.select('.storylink') subtext = soup.select('.subtext') def sort_stories_by_votes(hmlist): sorted_data = ...
from mars_profiling.report.presentation.flavours.widget.collapse import WidgetCollapse from mars_profiling.report.presentation.flavours.widget.container import ( WidgetContainer, ) from mars_profiling.report.presentation.flavours.widget.duplicate import ( WidgetDuplicate, ) from mars_profiling.report.presentati...
import bpy from bpy.types import ( Curve, ) from mathutils import (geometry, Vector) import numpy from . import grid from . import bezier import importlib grid = importlib.reload(grid) bezier = importlib.reload(bezier) def is_valid_curve(curve): if curve.dimensions != '2D' or len(curve.splines) != 1: ...
#!/user/bin/python # -*- coding: utf-8 -*- # 1. 准备 bootloader.bin # 2. 编译输出 rt-thread.bin # 3. 使用 OTA 打包工具(ota packager),设置为不加密、不压缩方式,固件分区名称为 app,填入版本号,点击开始打包,将 rt-thread.bin 打包为 rt-thread.rbl # 4. 将 bootloader.bin、rt-thread.rbl 拷贝到 AllBinPackager.py 目录下 # 5. 配置 config.json,填写文件名、分区偏移地址、分区大小(十六进制) # 6. 在 AllBinPackage...
"""concentration/settings.py Defines how the basic concentration settings get loaded. """ import os import sys from enum import Enum OS = Enum('OS', 'linux mac windows') HOSTS_FILE = "/etc/hosts" REDIRECT_TO = "127.0.0.1" START_TOKEN = "## START DISTRACTORS ##" END_TOKEN = "## END DISTRACTORS ##" SUB_DOMAINS = ('www...
""" Contains example functions for handling training """ import tensorflow as tf import tf_encrypted as tfe ### Example model_fns ### def default_model_fn(data_owner): """Runs a single training step!""" x, y = next(data_owner.dataset) with tf.name_scope("gradient_computation"): with tf.GradientTape() as...
#!/usr/bin/env python # # Searches through the whole source tree and validates all # documentation files against our own XSD in docs/xsd. # import sys,os import SConsDoc if __name__ == "__main__": if len(sys.argv)>1: if SConsDoc.validate_all_xml((sys.argv[1],)): print("OK") else: ...
"""This module contains the general information for Error ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import ImcVersion, MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class ErrorConsts(): pass class Error(ManagedObject): """This is Error class.""" consts = Erro...
# -*- coding: utf-8 -*- from __future__ import absolute_import import os from psd_tools import PSDImage from psd_tools.constants import TaggedBlock from psd_tools.decoder.actions import Descriptor from psd_tools.decoder.tagged_blocks import ArtboardData from .utils import decode_psd, DATA_PATH from PIL import Image ...
from . import audio_io from . import constants from . import files from scipy import signal import json import numpy as np import os ERROR = 'fp.getframerate() != constants.FRAME_RATE: 48000' def get_framerate_error_files(): for f in sorted(files.with_suffix(constants.METADATA_DIR, '.json')): if json.loa...
import matplotlib from matplotlib import pyplot as plt from matplotlib import gridspec import palettable #CMAP1 = palettable.cartocolors.sequential.Teal_7.mpl_colormap #CMAP2 = palettable.cartocolors.sequential.Teal_7.mpl_colormap #COLORS = palettable.cartocolors.sequential.Teal_4_r.mpl_colors TEXTWIDTH = 7.1014 # ...
import os from setuptools import setup, find_packages def read(file): return open(os.path.join(os.path.dirname(__file__), file)).read() setup( name="cdqa", version="1.1.2b", author="Félix MIKAELIAN, André FARIAS, Matyas AMROUCHE, Olivier SANS, Théo NAZON", description="An End-To-End Closed Domai...
from interface import Subject """ Notes: - Setter is used to notify that changes have occurred - Fields temperature, humidity, pressure are "private". This means that we are preventing the alteration of any of them without notification from their observers - I have doubts about the presence of getters methods in this ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by {{ cookiecutter.full_name }}
import tornado.web from handlers.base_handler import BaseHandler from models.group import Group from models.user import User from .util import check_group_permission from forms.forms import GroupForm class GroupsHandler(BaseHandler): @tornado.web.authenticated def get(self): group_name = self.get_arg...
#! /usr/bin/env python """DBF accessing helpers. FIXME: more documentation needed Examples: Create new table, setup structure, add records: dbf = Dbf(filename, new=True) dbf.addField( ("NAME", "C", 15), ("SURNAME", "C", 25), ("INITIALS", "C", 10), ...
import matplotlib.pyplot as plt class SignChangeSparseMap: def __init__(self): self.x_plus = [] self.x_minus = [] self.y_plus = [] self.y_minus = [] def add_right_change(self, x, y): self.x_plus.append([x, y]) def add_left_change(self, x, y): self.x_minus...
#!/usr/bin/python3 import requests import re import sys import subprocess import shlex from bs4 import BeautifulSoup import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {'http':'http://127.0.0.1:8080','https':'https://127.0.0.1:8080'} class Interface (): def __init__ (self):...
""" ============================================================================== Element unit tests ============================================================================== @File : testElements.py @Date : 2021/07/29 @Author : Alasdair Christison Gray @Description : """ # ==========================...
import logging class LogConfigurator(object): """Console logging that can be configured by verbosity levels.""" def __init__(self, root=None, root_level=logging.INFO): self.root = logging.getLogger() if root is None else root self.root.setLevel(root_level) self.__file_handler = None ...
#------------------------------------------------------------------------------- # Evaluate Division #------------------------------------------------------------------------------- # By Ying Peng # https://leetcode.com/problems/evaluate-division/ # Completed 11/30/20 #-----------------------------------------------...
import numpy as np import math def poisson_lambda_mle(d): """ Computes the Maximum Likelihood Estimate for a given 1D training dataset from a Poisson distribution. """ return sum(d) / len(d) def likelihood_poisson(x, lam): """ Computes the class-conditional probability for an univari...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2019 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from migrate.changeset import UniqueConstraint from sqlalchemy import MetaData, Table ENGINE = 'InnoDB' CHARSET = 'utf8' def upgrade(migrate_engine): """ This database upg...
# -*- coding: utf-8 -*- """ Created on Thu Jun 19 19:29:07 2018 @author: yiyuezhuo """ ''' A relative gerneralized framework will be employed, such as apply common distributions rather than meanfield or full-rank multivariate normal. Pytorch 0.4 new features are required. core3 move q_size from first dimention to ...
""" Copyright (C) 2020 Piek Solutions LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ...
""" :mod:`asp_cml` Alexander Street Press Classical Music Library Job """ __author__ = "Jeremy Nelson" from asp_base import AlexanderStreetPressMusicJob class AlexanderStreetPressClassicalMusicLibrary(AlexanderStreetPressMusicJob): def __init__(self,marc_file,**kwargs): """ Creates instance of `A...
from django.shortcuts import reverse from model_bakery import baker from ..models import EnvironmentProject from glitchtip.test_utils.test_case import GlitchTipTestCase class EnvironmentTestCase(GlitchTipTestCase): def setUp(self): self.create_user_and_project() self.url = reverse( "o...
import torch from torchsupport.flex.checkpointing.savable import ( savable_of, Savable, SaveStateError ) @savable_of(torch.nn.Module) class SaveModule(Savable): def __init__(self, module): if isinstance(module, torch.nn.DataParallel): module = module.module self.module = module def write(self, dat...
import io from pdfminer.converter import TextConverter from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfpage import PDFPage def extract_text_from_pdf(pdf_path): """Extract the content of a PDF file as text.""" resource_manager = PDFResourceM...
# =============================================================================== # Copyright 2013 Jake Ross # # 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...
#!/usr/bin/env python import xml.dom.ext from xml.dom.ext.reader import Sax2 from xml import xpath filename = "example.xml" print "Demo started." reader = Sax2.Reader() doc = reader.fromStream(filename) #xml.dom.ext.PrettyPrint(doc) #xml.dom.ext.Print(doc) mod_list = xpath.Evaluate('/configuration/module', doc.do...
''' cat that kitten ''' from catms import app if __name__ == '__main__': app.run()
import logging from datetime import datetime from gettext import translation from typing import Any, Callable from asciimatics.effects import Effect, Print from asciimatics.event import Event, KeyboardEvent from asciimatics.exceptions import NextScene, StopApplication from asciimatics.renderers import Box, ColourImage...
import pandas as pd import numpy as np import plotly from plotly.offline import plot from plotly.subplots import make_subplots import plotly.graph_objects as go import sys def plot_html(table): ''' function splits table (a dictionary of 3 dataframes as values) and plots them in a html report. ...
# Generated by Django 3.1.12 on 2021-06-22 08:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0010_merge_20210616_1048'), ('home', '0010_merge_20210617_1019'), ] operations = [ ]
#!/usr/bin/env python ''' Author: Saijal Shakya Development: > LMS: December 20, 2018 > HRM: Febraury 15, 2019 > CRM: March, 2020 > Inventory Sys: April, 2020 > Analytics: ... License: Credited Contact: https://saijalshakya.com.np ''' """Django's command-line utility for administrative tasks.""" i...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Post-order DFS traversal class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """...
import os import glob import subprocess import traceback token = os.environ['BINSTAR_TOKEN'] cmd = ['binstar', '-t', token, 'upload', '--force'] cmd.extend(glob.glob('*.tar.bz2')) try: subprocess.check_call(cmd) except subprocess.CalledProcessError: traceback.print_exc()
from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post') image = models.ImageField(upload_to='post_image') caption = models.CharField(max_length=264,blank=T...
a,b=map(int,input().split()) print(a-1 if a>b else a)
import sys import tensorflow as tf from keras import backend as K from keras.models import Sequential from keras.layers import Conv1D, MaxPooling1D, Activation, CuDNNGRU, Flatten, Dense, Dropout, BatchNormalization from keras.callbacks import TensorBoard, ModelCheckpoint from imblearn.over_sampling import SMOTE ...
from eth.vm.forks.berlin.headers import ( configure_header, create_header_from_parent, compute_berlin_difficulty, ) compute_daejun_difficulty = compute_berlin_difficulty create_daejun_header_from_parent = create_header_from_parent( compute_berlin_difficulty ) configure_daejun_header = configure_heade...
import pprint import math datapoints = dict( dp1=(-1.88, 2.05), dp2=(-0.71, 0.42), dp3=(2.41, -0.67), dp4=(1.85, -3.80), dp5=(-3.69, -1.33) ) clusters = dict( cluster_1=(2., 2.), cluster_2=(-2., -2.) ) def calc_distance(datapoint, cluster): return math.sqrt(sum([(c - d)**2 for c, d ...
from pythonforandroid.build import Context from pythonforandroid.graph import get_recipe_order_and_bootstrap from pythonforandroid.bootstrap import Bootstrap from itertools import product import pytest ctx = Context() name_sets = [['python2'], ['kivy']] bootstraps = [None, Bootstrap.get_...
# coding: utf-8 from fabkit import filer, sudo, env, Service from fablib.base import SimpleBase class Gluster(SimpleBase): def __init__(self): self.data_key = 'gluster' self.data = { } self.services = { 'CentOS Linux 7.*': [ 'glusterd', ] ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import get_version from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class ShopConfig(AppConfig): name = 'shop' verbose_name = _("Shop") def ready(self): from django_fsm.signals imp...
from django.test import TestCase from .factories import GalleryFactory class RequestGalleryTest(TestCase): urls = 'photologue.tests.test_urls' def setUp(self): super(RequestGalleryTest, self).setUp() self.gallery = GalleryFactory(slug='test-gallery') def test_archive_gallery_url_works(s...
from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from astrometry.net.models import UserProfile @receiver(post_save, sender=User) def add_user_profile(sender, instance, created, raw, **kwargs): print('add_user_profile() called. sender',...
import unittest from conans.search.binary_html_table import RowResult, Headers, Results class RowResultTestCase(unittest.TestCase): @classmethod def setUpClass(cls): data = {'id': '1234', 'outdated': True, 'extra': 'never used', 'settings': {'os': 'Wind...
# -*- coding: utf-8 -*- __author__ = 'zj' import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': x = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range plt.plot(x, np.sin(x)) # Plot the sine of each x point plt.show() # Displa...
import os import configparser import platform config = configparser.ConfigParser() config.read('./config.ini') location = config.get('MODE', 'LOCATION') print ("[temperature_firestore] location", location) if location == "local": platform = platform.system() print("[te...
# -*- coding: utf-8 -*- # Generated by Django 1.11.18 on 2019-03-11 11:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Activities', '0001_initial'), ] operations = [ migrations.AlterField( ...
name = 'gsodpy'
############################################################################# # # VFRAME # MIT License # Copyright (c) 2020 Adam Harvey and VFRAME # https://vframe.io # ############################################################################# import click from vframe.settings.app_cfg import VALID_PIPE_MEDIA_EXT...
import pytest @pytest.yield_fixture(scope="module") def test_domain_project(test_admin_client): domain = test_admin_client.Domain() domain.slug = "test-project" domain.name = "Test Domain" domain.description = "Test" * 10 domain.save() yield domain domain.destroy() @pytest.yield_fixtur...
# BuildFox deploy script # compiles multiple files into one python script import re from pprint import pprint re_lib_import = re.compile(r"^from (lib_\w+) import \w+((, \w+)+)?$", flags = re.MULTILINE) re_import = re.compile(r"^import (\w+)$", flags = re.MULTILINE) # return prepared text of BuildFox module def file_...
import os class LocustfileStorage: def upload(self, locustfile: os.PathLike) -> None: raise NotImplementedError() def delete(self) -> None: raise NotImplementedError()
"""Tensorflow based linear algebra backend.""" import tensorflow as tf # "Forward-import" primitives. Due to the way the 'linalg' module is exported # in TF, this does not work with 'from tensorflow.linalg import ...'. det = tf.linalg.det eigh = tf.linalg.eigh eigvalsh = tf.linalg.eigvalsh expm = tf.linalg.expm inv =...
import org.pydev.dhyaniv.stockAnalyzer.getandAnalyzeStockData as stockAnalyzer import org.pydev.dhyaniv.constants.constants as constants import time import schedule if __name__ == "__main__": print("Hello guys!") #schedule.every(20).seconds.do(stockAnalyzer.getStockData) #schedule.every(constants.CHECKFR...
from django.conf.urls import patterns, include, url from rest_framework import routers from talos import views from django.contrib import admin router = routers.DefaultRouter() router.register(r'projects', views.ProjectViewSet) router.register(r'libraries', views.LibraryFileViewSet) router.register(r'resource_files', ...
import string import math from codestat_tokenizer import Tokenizer from token_builders import ( InvalidTokenBuilder, WhitespaceTokenBuilder, NewlineTokenBuilder, EscapedStringTokenBuilder, IntegerTokenBuilder, IntegerExponentTokenBuilder, RealTokenBuilder, RealExponentTokenBuilder, PrefixedIntegerTok...
import os import clip import torch import numpy as np from sklearn.linear_model import LogisticRegression from torch.utils.data import DataLoader from torchvision.datasets import CIFAR100 from tqdm import tqdm # Load the model device = "cuda" if torch.cuda.is_available() else "cpu" model, preprocess = clip.load('ViT-...
# mAP and topk recall rate for image retrieval import numpy as np import torch from torch.autograd import Variable import pdb def main(): x_query = Variable(torch.rand(3,100)) x_gallery = Variable(torch.rand(9,100)) y_query = Variable(torch.LongTensor([0,1,2])) y_gallery = Variable(torch.LongTensor([0...
r"""Collection of quadrature methods.""" import logging from functools import wraps from .frontend import generate_quadrature from .sparse_grid import sparse_grid from .utils import combine from .chebyshev import chebyshev_1, chebyshev_2 from .clenshaw_curtis import clenshaw_curtis from .discrete import discrete from...
from abc import ABC, abstractmethod from datetime import date from listens.definitions import SunlightWindow class SunlightGateway(ABC): @abstractmethod def fetch_sunlight_window(self, iana_timezone: str, on_date: date) -> SunlightWindow: ...
# -*- coding: utf-8 -*- """ datagator.api.client._entity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2015 by `University of Denver <http://pardee.du.edu/>`_ :license: Apache 2.0, see LICENSE for more details. :author: `LIU Yu <[email protected]>`_ :date: 2015/03/24 """ from __future__ import uni...
import torch from torch import autograd, nn import torch.nn.functional as F from itertools import repeat from torch._six import container_abcs import time from prune.pruning_method_transposable_block_l1 import PruningMethodTransposableBlockL1 def _ntuple(n): def parse(x): if isinstance(x, container_abcs.I...
#!/usr/bin/env python3 import queue from typing import Callable import sounddevice as sd import vosk import sys import json import requests import random import configparser from assistant import Assistant from command import Command, CommandError API_URL = None TOKEN = None q = queue.Queue() def callback(indata,...
# Get sentence representations """ Sentences have to be in the BPE format, i.e. tokenized sentences on which you applied fastBPE. Below you can see an example for English, French, Spanish, German, Arabic and Chinese sentences. """ ######################################################## ############ Testing on simple ...
from ..suffixes import DerivationalSuffix from ..transitions import Transition from . import State class DerivationalState(State): def __init__(self, initialState, finalState, *suffixes): super(DerivationalState, self).__init__(initialState, finalState, *suffixes) def NextState(self, suffix): ...
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...
from collections import deque class Solution: def decodeString(self, s): s1, s2 = [], [] s = [c for c in s] q = deque(s) alpha = [chr(c) for c in range(ord("a"), ord("z") + 1)] open, close = ["["], ["]"] prev_digit = False while q: node = q.popl...
import numpy as np import cvxopt from cvxopt import solvers from cvxopt import matrix from numpy.linalg import eigh cvxopt.solvers.options['show_progress'] = True cvxopt.solvers.options['maxiters'] = 1000000 cvxopt.solvers.options['abstol'] = 1e-14 cvxopt.solvers.options['reltol'] = 1e-14 srng = np.random.RandomS...
import sys import urllib.request import json import re known_supported_version = { 'jira-software': '8.13.8', 'confluence': '7.12.2', 'stash': '7.12.1', } def get_lts_version(argv): product = argv[0].lower() if product == 'jira': product = 'jira-software' elif product == 'bitbucket': product = 'stash' if ...
from .glvq import GLVQ from .deeplvq import DeepLVQ from .gmlvq import GMLVQ # from .knn import KNN # from .lvq1 import LVQ1 from .lvqmln import LVQMLN from .network import Network __all__ = [ 'GLVQ', 'DeepLVQ', 'GMLVQ', # 'KNN', # 'LVQ1', 'LVQMLN', 'Network', ]
import os import random import numpy as np # import torch def seed_everything(seed=42): # noqa D103 # TODO: Remove this ignore random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) # torch.manual_seed(seed) # torch.cuda.manual_seed_all(seed) # torch.backends.cudnn....
from flask_app import app from flask import render_template, request, redirect, jsonify, session from flask import flash import requests # class for User class Author: def __init__(self, id, contents): self.id = id self.contents = contents # classmethods # =======================================...
import random from .serializers import NotionSerializer, NotionActionSerializer, NotionCreateSerializer from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.authentication import SessionAuthentication from rest_framew...
# %% import numpy as np import pandas as pd import git # Find home directory for repo repo = git.Repo("./", search_parent_directories=True) homedir = repo.working_dir # Import plotting features import matplotlib.pyplot as plt import seaborn as sns # %% # Set plot style sns.set_style("ticks") sns.set_palette("colorbl...
import os, threading class QtcFile(object): def __init__(self, path, validator): self._writer = FileWriter(path) self._validator = validator self._path = path def write(self, path): if self._validator.is_valid(path): self._writer.write(path) def remove(self, p...
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit # making life easier def l2hnorm(x, h): return np.linalg.norm(x)*np.sqrt(h) # Colelctors for convergence analysis err = [] hs = [] #Choose here if you want to see the plots for h = 0.2 plot = False #Choose here if you want t...