content
stringlengths
5
1.05M
import struct from .Water import Water def compile_water(data: list, bom='little_endian') -> bytes: bom = '<' if bom == 'little_endian' else '>' if len(data) != 4096: if len(data) < 4096: print("Error 2001: Data list is not long enough. Expected 4096 but saw {}".format(len(data))) ...
from pwn import * #r = process(["strace", "./BaseX"]) #r = process(["./BaseX"]) #libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") libc = ELF("./libc.so.6") fread = libc.symbols["fread"] system = libc.symbols["system"] rop = "" place = 517 def num_to_31(num): s = "" while num: s += chr(ord('0') + num % 3...
from decimal import Decimal from babel.dates import format_date from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator from django.db import models from django.utils.translation import gettext_lazy as _ from helsinki_gdpr.models import S...
#!/usr/bin/env python3 ############################## # rsync via ssh backup script # Anthony Vaughn # # v0.1.0 ############################## import argparse from email.message import EmailMessage import json import os import re import smtplib import socket import subprocess import sys import time ...
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated from thrift.transport import TTransport, TSocket from thrift.transport.TTransport import TTransportException from jiffy.directory import directory_service class Perms: def __init__(self): pass none = 0 owner_read = 0o400 ...
from django.db import models from django.db.models import QuerySet, Prefetch, Value, Min, Max from django_filters import rest_framework as filters from rest_framework.exceptions import ValidationError from smart_meter.models import Measurement, GroupParticipant, SmartMeter, PowerMeasurement, GasMeasurement, \ Sola...
from sklearn import datasets from NoiseFiltersPy.AENN import AENN dataset = datasets.load_iris() data = dataset.data classes = dataset.target aenn = AENN() filter = aenn(data, classes) print(filter.clean_data)
""" Update album data by searching with Discogs Python client. """ import pymongo import discogs_client client = pymongo.MongoClient("localhost", 27017) db = client.discogs_masters current_albums = db.current_albums d = discogs_client.Client('discogs-spotify/0.1', user_token="VhFxDZnEzFcBLdTCSnsGfAmxgHmCOYxXMSdbOH...
from hypereditor.blocks.base import Block from hypereditor.blocks import get_block_class_for, register @register('column') class ColumnBlock(Block): external = True def _build_col_class(self, colSettings): col_class = [] if colSettings: for sz in ['XS', 'SM', 'MD', 'LG']: ...
################################################################################ # Copyright (C) 2016 Advanced Micro Devices, Inc. All rights reserved. # # 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 th...
import cupy as cp from grid import Grid from phase import Phase class Wavefunction: """Generates the Wavefunction object. Contains information about the BEC such as interaction strength and atom number. Attributes ---------- psi : ndarray(complex) 2D :obj:`ndarray` containing wavefunction...
from typing import Optional, Union from numbers import Number import os import logging import json import random import datetime import collections from functools import wraps import asyncio import aiohttp import signal from aiohttp import web import aiohttp_session import pandas as pd import pymysql import plotly.expr...
import numpy as np from autoencoder_tf.encoder import Network test_data = np.load('test.npy') train_data = np.load('train.npy') mlp = Network(100) batch_size = 1000 learning_rate = 0.1 epochs = 10 l2 = 0 mlp.train(train_data, learning_rate, epochs, batch_size, l2)
""" Plot XU (to investigate age reliability) for the CUT components. """ import numpy as np from astropy.table import Table import matplotlib.pyplot as plt plt.ion() #~ import sys #~ sys.path.insert(0, '/Users/marusa/chronostar/chronostar/') from chronostar.component import SphereComponent from chronostar import tabl...
from dbt.adapters.mysql5.connections import MySQLConnectionManager # noqa from dbt.adapters.mysql5.connections import MySQLCredentials from dbt.adapters.mysql5.relation import MySQLRelation # noqa from dbt.adapters.mysql5.column import MySQLColumn # noqa from dbt.adapters.mysql5.impl import MySQLAdapter from dbt.ad...
#!/usr/bin/env python3 import sys from os import path from tempfile import gettempdir from unittest import ( TestLoader, TextTestRunner ) EXIT_SUCCESS = 0 EXIT_FAILURE = 1 PATH_REPORT = path.join(gettempdir(), 'vimtools_test_report.txt') TEST_FILENAMES_PATTERN = 'test_*' def write_report(failures): with o...
''' Implements Tcp Socket to communicate to the server ''' from test_server import Client def run_client(): ''' Function to run the Tcp client socket ''' tcp_client = Client(host="localhost", port=9000) count = 0 while count != 15: data = str(count) + "tcp" # data = input("Ente...
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2019-12-10 09:21 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('maintenance', '0007_auto_20191209_1315'), ] opera...
import json from models.postgres_db import Postgres_DB from models.base import Base class ActiveRecord(Base): table_name = None primary_key = None allow_fields = {} def __init__(self, record_id): self.is_loaded = False self.id = record_id self.init_data() def init_data(self): ...
# Copyright (c) 2021 Vlad Balmos <vladbalmos@yahoo.com> # Author: Vlad Balmos <vladbalmos@yahoo.com> # See LICENSE file import urwid from ...history import History from ...db.schema_cache import schema_cache_instance class CommandError(Exception): pass class Autocomplete: def __init__(self, suggestions, wor...
import pandas as pd df = pd.read_csv('https://github.com/ProjectPythia/pythia-datasets/raw/main/data/enso_data.csv',index_col=0) df.head()
from PIL import Image from pylab import * fname = "C:\\skunkworx\\Area52\\home\\6008895\dev\\bitbucket\\me-ml\\computervision\\jesolem-PCV-790b64d\\data\\empire.jpg" im = array(Image.open(fname)) imshow(im) x = [100,100,400,400] y = [200,500,200,500] plot(x, y, "ks:") plot(x[:2], y[:2]) title("empire...
from glance import client as glance_client from pprint import pprint def glance_upload(image_filename, creds = {'auth_url': None, 'password': None, 'strategy': 'noauth', 'tenant': None, 'username': None}, host = "0.0.0.0", port = "9292", token = None): image_meta = {'container_format': 'bare', ...
import unittest from main import get_API_data class FlaskClientTestCase(unittest.TestCase): def test_api_calls_region_good(self): response = get_API_data('region', 'kanto') self.assertEqual(response['id'], 1) self.assertEqual(len(response['locations']), 85) self.assertEqual(respons...
# # i want to have a consitent-on-all-systems # pseudo random generator. # this implements a Wichmann-Hill generator # class Random(object): # https://en.wikipedia.org/wiki/Wichmann%E2%80%93Hill __slots__ = ('_seed') def __init__(self, a: int = None) -> None: if a is None: import time a = int(t...
# Lint as: python3 # Copyright 2020 The TensorFlow 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 ...
#encoding:utf-8 subreddit = 'CozyPlaces' t_channel = '@r_CozyPlaces' def send_post(submission, r2t): return r2t.send_simple(submission)
import asyncio import logging.config from pathlib import Path from symphony.bdk.core.activity.command import CommandContext from symphony.bdk.core.config.loader import BdkConfigLoader from symphony.bdk.core.symphony_bdk import SymphonyBdk import time from symphony.bdk.gen.agent_model.v4_message import V4Message asy...
# -*- coding: utf-8 -*- """ Created on Fri Feb 7 16:51:12 2020 @author: dconly """ import os import sys import site import imp import getpass import arcpy version = sys.version ex = sys.executable user = getpass.getuser() module_to_find = 'xlwings' try: conda_env = os.environ['CONDA_PREFIX'] except: con...
from django import forms from django.utils.translation import ugettext as _ from django.contrib.auth.models import User from django.db.models import Q from ecs.core.forms.fields import AutocompleteModelChoiceField from ecs.pki.models import Certificate class CertForm(forms.Form): user = AutocompleteModelChoiceFi...
# ============================================================= # This script is written to generate structured multi-block # grid with different TE waviness over the DU97-flatback profile # according to grid guideline. #============================================================== # written by Pay Dehpanah # last up...
import unittest from nxtools import * class TestGetFiles(unittest.TestCase): def test_colors(self): print () logging.debug("This is a debug message") logging.info("This is an info message") logging.warning("This is a warning message") logging.error("This is a error message...
from tkinter import * root=Tk() name=Label(root, text="name") password=Label(root,text="password") entry1=Entry(root) entry2=Entry(root) name.grid(row=0, sticky=E) entry1.grid(row=0,column=1) password.grid(row=1,column=0) entry2.grid(row=1,column=1) c=Checkbutton(root,text="Keep me login ") c.grid(columnspan=2) ...
import os import pandas as pd import re CACHE_DIR = os.path.expanduser("~/.annotations") def cache_data_table(get_table_func): """Decorator that caches the pandas DataFrame returned by the decorated function. It's intended for functions that take a relatively long time to retrieve some table over the network...
""" Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B. The graph is given in the following form: graph[i] is a list of in...
import warnings from functools import partial from itertools import product import matplotlib.animation as mplanim import matplotlib.axes as maxes import matplotlib.backend_bases as mback import matplotlib.pyplot as plt import numpy as np import pytest import astropy.units as u import astropy.wcs import sunpy.data.t...
import os import docx import logging from lib.utils import * class Parser: def __init__(self, file_path): """ File path must be absolute """ try: self.document = docx.Document(file_path) except FileNotFoundError: logging.error(f"Missing file at {file...
from .DataReader import DataReader from .DataSetGenerator import DataSetGenerator from .Preprocessor import Preprocessor
import stack """ This script implements MinStack which allows one to retrieve the min of the stack in O(1) and uses less space. """ class MinStack(stack.MyStack): def __init__(self): super().__init__() self.__min_top = None def push(self, item): super().push(item) if self.__m...
from cv2 import * from .core import * from .imgcodecs import * from .imgproc import * from .flag import *
"""Advantage Air parent entity class.""" from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN class AdvantageAirEntity(CoordinatorEntity): """Parent class for Advantage Air Entities.""" def __init__(self, instance, ac_key, zone_key=None): """Initialize co...
GET_IMG_BASE64 = ( "const img = document.getElementById(arguments[0]);" "const canvas = document.createElement('canvas');" "const ctx = canvas.getContext('2d');" "ctx.drawImage(img, 0, 0);" "return canvas.toDataURL().replace(/data.*base64,/i, '');" ) def get_image_b64_by_id(driver, img_id): re...
#!/usr/bin/env python3 from setuptools import setup, find_packages import hostblock setup( name = 'hostblock', description = hostblock.__doc__.strip(), url = 'https://github.com/nul-one/hostblock', download_url = 'https://github.com/nul-one/hostblock/archive/'+hostblock.__version__+'.tar.gz', vers...
import collections class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: count = list(collections.Counter(nums).values()) quantity.sort(reverse=True) def dfs(start): if start == len(quantity): return True itemSize = qua...
""" Unit tests for the docker state """ import pytest import salt.modules.dockermod as docker_mod import salt.states.docker_volume as docker_state from tests.support.mock import Mock, patch @pytest.fixture def configure_loader_modules(): return { docker_mod: {"__context__": {"docker.docker_version": ""}}...
def assertIsOperation(op): assert op is not None assert hasattr(op, 'description') assert hasattr(op, 'runner') def assertIsResponse(res): assert res is not None assert callable(res.retries) assert callable(res.success) assert callable(res.item) assert callable(res.items) assert c...
# -*- coding: utf-8 -*- __all__ = ["Base_curv", "Elev_curv", "Orig_curv", "Slope_curv", "Tpi_curv"] from .base_curv import Base_curv from .elev_curv import Elev_curv from .orig_curv import Orig_curv from .slope_curv import Slope_curv from .tpi_curv import Tpi_curv
from skimage.exposure import rescale_intensity from skimage.measure import compare_ssim from skimage.measure import compare_mse from skimage.measure import label from skimage.filters import gaussian from skimage.color import rgb2gray from skimage.io import imread from skimage.io import imsave import numpy as np def l...
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: jianzhi_offer_25.py @time: 2019/5/1 16:01 @desc: ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class...
from model.Product import Product def _getRightmost(categories): """ Get rightmost toplevel category. categories -- list of Category, all category from database. """ rightmost = None for cat in categories: if not rightmost or cat.getRight() > rightmost.getRight(): rightmost...
# 我们有一个班级类,创建班级对象的时候,需要按序号指定班级名称, # 我们就需要知道当前已经创建了多少个班级对象,这个数量可以设计成类属性 class EduClass: class_num = 0 price = "11111111111" def __init__(self): self.class_name = f'Python{EduClass.class_num+1}班' EduClass.class_num += 1 self.price = "222222222" classList = [EduClass() for i in range...
from typing import List # A new type of variable Vector = List[str]
#get the path of directory in which project directories are there. Assume dirsPath #rootdir ='C:\Users\Yagnik\PycharmProjects\Top_Project' import os import sys import ghProc from logChunk import logChunk #print os.listdir(rootdir) # for subdir, dirs, files in os.walk(rootdir): # print dirs def main(): prin...
from scrounger.core.module import BaseModule # helper functions from scrounger.utils.config import Log from scrounger.utils.android import class_names, method_names, app_strings from scrounger.utils.android import app_used_resources from scrounger.modules.misc.android.app.manifest import Module as ManifestModule fro...
import sqlite3, uuid, sys, logging, time, os, json, zlib, hashlib, tempfile from util import mbtiles_connect, execute_commands_on_tile, flip_y, prettify_connect_string logger = logging.getLogger(__name__) def mbtiles_to_disk(mbtiles_file, directory_path, **kwargs): delete_after_export = kwargs.get('delete_afte...
""" CREATE TABLE fire_skitser ( refnr NUMBER, versnr NUMBER, png_path VARCHAR2(200), png_md5 VARCHAR2(200), master_path VARCHAR2(200), master_md5 VARCHAR2(200) ); """ import json from pathlib import Path import click import cx_Oracle from db_connect import (usr, pwd, server, service, port) ba...
import unittest import warnings from unittest import mock from qupulse.expressions import ExpressionScalar from qupulse.pulses.abstract_pulse_template import AbstractPulseTemplate, NotSpecifiedError, UnlinkWarning from tests.pulses.sequencing_dummies import DummyPulseTemplate class AbstractPulseTemplateTests(unitte...
from __future__ import annotations from Core.Actions.Actions import Actions from Core.Actions.Config import Config from pathlib import Path from Core.Actions.Read import Read from Core.Actions.Branch import Branch from Core.ConfigHandler import ConfigHandler from FlexioFlow.Options import Options class Core: CON...
# assembler.py import logging from abc import ABC from datetime import datetime from .config import BaseConfig from .run_modes import RunMode from .stage import Stage, Estimator LOGGER = logging.getLogger(__name__) class Assembler(ABC): """ Class responsible for assembling and executing a Surround pipeline...
import unittest from py_sb_image_to_text import py_sb_capture_screen from pathlib import Path class TestPySbImageToText(unittest.TestCase): project_dir = Path(__file__).parents[1] package_dir = project_dir.joinpath('tests') resource_dir = package_dir.joinpath('resources') arena_tokens_path = resource...
"""Exceptions for ``cubi-tk``.""" class CubiSakWarning(Warning): """Base ``Warning`` class.""" class IrodsIcommandsUnavailableWarning(CubiSakWarning): """Raised when iRODS icommands are not available.""" class CubiSakException(Exception): """Base ``Exception`` class.""" class IrodsIcommandsUnavailab...
#!/usr/bin/env python # Copyright(c) 2015, Shihira Fung <fengzhiping@hotmail.com> import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__))) sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../core")) from context import context from policy import policy sample1 = """ load!: policy_test a...
# -*- coding: utf-8 -*- """ Created on Tue Oct 20 11:53:22 2020 @author: fuchsca """ # -*- coding: utf-8 -*- #!/usr/bin/en python import pika import os import config import argparse """ Created on Tue Oct 13 13:47:56 2020 @author: fuchsca """ parser = argparse.ArgumentParser(description = 'Currency') parser.add_ar...
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy import os vlfeatdir = '../' files = ['vlfeat.pyx'] setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension( 'vlfeat', files, language = 'c++', include_di...
from flask import Flask, request from flask_restful import Resource, Api from json import dumps app = Flask(__name__) api = Api(app) class Apples(Resource): def get(self): result = {'data': 33} return result class Bananas(Resource): def get(self): result = {'data': 99} return ...
import matplotlib.pyplot as plt from pylab import * def Imp(extra_baoji, baoji, baojia, duoshan): if duoshan + baoji < 1: return extra_baoji*baojia / (1+baoji*baojia-duoshan*0.3) return extra_baoji*(baojia+0.3) / (baoji+duoshan+baoji*baojia-duoshan*0.3) def ImpOrig(extra_baoji, baoji, baojia, duoshan)...
# Copyright (c) 2018 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 app...
from __future__ import print_function, absolute_import from six import iteritems, itervalues from six.moves import range from pyNastran.bdf.bdf import BDF import tables import numpy as np from .input import Input from .result import Result from .pynastran_interface import get_bdf_cards from .punch ...
#!/usr/bin/env python3 import re import sys import glob import json if len(sys.argv) > 1: dir = sys.argv[1] else: dir = "pois/" ficheros = glob.glob(dir+"/*.md") ficheros.append( "intro.md" ) all_links = [] for f in ficheros: file_content = open(f,"r").read() links = re.findall('\[([^\]]+)\]\((http...
# 1. Load Data.. dataset= pd.read_csv("Give file's directory") print(dataset) # Should read data.. # 2. Set inpıt-output data X = dataset.values[:, 0:23] y = dataset.values[:, 25:26] print("X-Shape :",X.shape) print("Y-Shape :",y.shape # 3. Splitting data into Train and Test X_train, X_val_and_test, y_train, y_val_...
import os import numpy as np import tensorflow as tf from common.network import NetworkBuilder from common.network import build_conv3d, build_conv2d, build_dense, concat_actions class EMBuilder(NetworkBuilder): def __init__(self, sess, build, ob_space, ac_space): self.sess = sess ...
import time from hydro_engine.proto import youtubedl_pb2 from hydro_engine.proto import youtubedl_pb2_grpc from hydro_engine.download_manager import DownloadInfo class YoutubedlService(youtubedl_pb2_grpc.YoutubeDLServicer): """Implements YoutubeDLServicer functionalities""" def __init__(self, downloader): ...
S.noise_vs_bias(band,bias_group=1,analyze=True,make_timestream_plot=True,bias=[9,8,7,6,5,4,3,0],overbias_voltage=8,high_current_mode=False)
import os as os from lib import ReadCsv from lib import ReadConfig from lib import ReadData from lib import NetworkModel from lib import ModelMetrics from lib import SeriesPlot import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from lib import modwt import keras from datetime import date,datetime...
# -*- coding: utf-8 -*- import re from sqlalchemy.sql import or_ from david.lib.store import redis_store as rs from david.core.article import Article from david.modules.news.model import News DB_HOMEPAGE_ARTICLES = 'homepage_articles' RE_SPLITTER = re.compile(r'\s+') def get_homepage_articles(): data = rs.get(D...
# encoding: utf-8 """ Sphinx configuration and libraries for Safari Books Online documentation Created by Jeremy Bowman on Fri Jan 18 18:51:44 2013 -0500 Copyright (c) 2013-2014 Safari Books Online. All rights reserved. """
from models.base_model import SQLModel class Test(SQLModel): sql_create = ''' CREATE TABLE `test` ( `id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) )'''
def prune(argv): import argparse from .shared import get_shared_argparse shared_parser = get_shared_argparse() parser = argparse.ArgumentParser('cortexpy prune', parents=[shared_parser]) parser.add_argument('-t', '--remove-tips', required=True, type=int, help='Remove tips sho...
from ..policy import Policy class Greedy(Policy): def __init__(self, action_space, vfunction=None, qfunction=None, selfplay=False): if vfunction is None and qfunction is None: raise ValueError('Requires either a V-function or Q-function') self.action_space = action_space self....
import os from jinja2 import Template SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) OUTPUT_DIRECTORY_BASE = os.path.join(SCRIPT_DIR, "..") def get_dependency_folder(maven_dependency): folder = os.path.join( OUTPUT_DIRECTORY_BASE, "bazelrio", "dependencies", maven_depen...
from app.models.question import Question, QuestionMessage from ferris import Controller, route_with from ferris.core import messages class Questions(Controller): class Meta: prefixes = ('api', ) components = (messages.Messaging, ) Message = QuestionMessage messaging_transform_func...
import sys import logging from logging.handlers import MemoryHandler from argparse import ArgumentParser from typing import Tuple, Sequence from twisted.internet.protocol import ServerFactory from twisted.internet import defer from twisted.python.log import PythonLoggingObserver from dnsagent import logger from dnsag...
def cifar_resnet_flop(layer=110, prune_rate=1): ''' :param layer: the layer of Resnet for Cifar, including 110, 56, 32, 20 :param prune_rate: 1 means baseline :return: flop of the network ''' flop = 0 channel = [16, 32, 64] width = [32, 16, 8] stage = int(layer / 3) for index in...
import asyncio # list get insert update delete import sys import os import motor.motor_asyncio from pymongo_inmemory import Mongod sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/fastapi_restify") from fastapi_r...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Tencent is pleased to support the open source community by making Metis available. Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with th...
import os if 'DJANGO_ENV' in os.environ: if os.environ['DJANGO_ENV'] == 'prod': from .prod import * elif os.environ['DJANGO_ENV'] == 'dev': from .dev import * elif os.environ['DJANGO_ENV'] == 'local': from .local import * else: from .local import * else: from .local ...
import speg from .ast import * def _transpose(m): return dict((m[k], k) for k in m) _basic_type_map = { '@': t_none, 'X': t_void, '_N': t_bool, 'D': t_char, 'C': t_schar, 'E': t_uchar, 'F': t_sshort, 'G': t_ushort, 'H': t_sint, 'I': t_uint, 'J': t_slong, 'K': t_ulon...
import os import time def test_simple_client_server(systest): osmose_server = None test_server = None try: osmose_server = systest.run_binary( "osmose-server", "--rules", os.path.normpath(os.path.abspath(__file__) + "/../rules.json"), ) time.sl...
#-*- coding: utf-8 -*- # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control from dj...
class Flyweight: """ Flyweight parent class to implement Gang of Four flyweight design pattern. The flyweight will only create one instance of a given child class based on the return of :py:meth:`_key()`. :py:meth:`_key()` must be implemented by children. The return of :py:meth:`_key()` must be...
import asyncio class Broker: def __init__(self, dispatcher, component): self.dispatcher = dispatcher self.component = component def send(self, recipient, topic, payload=None): return self.dispatcher.send(self.component, recipient, topic, payload=payload) def subscribe(self, callb...
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations # ------------------------------------------------------------------------- # This is a sample controller # - index is the default action of any application # - user is required for authentication and authorization ...
from api import app, db from ariadne import load_schema_from_path, make_executable_schema, graphql_sync from ariadne.constants import PLAYGROUND_HTML from flask import request, jsonify from api.resolvers.subscriptions import subscription from api.resolvers.mutations import mutation from api.resolvers.queries import qu...
# Copyright (c) 2018 Ultimaker B.V. # Charon is released under the terms of the LGPLv3 or higher. import os from Charon.VirtualFile import VirtualFile def test_GCodeReader(): f = VirtualFile() f.open(os.path.join(os.path.dirname(__file__), "resources", "um3.gcode")) assert f.getData("/metadata")["/metada...
from iwlearn.models.based_on_sklearn import ScikitLearnModel #from based_on_keras import BaseKerasModel, BaseKerasClassifierModel, BaseKerasRegressorModel
""" ZFS Backup Consistency Agent """ import os import subprocess import hashlib import socket import pickle from datetime import datetime class Snapshot(): """ Snapshot representation """ def __init__(self, name, used, avail, refer, mountpoint): self.name = name self.used = used ...
# params.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue Sep 7 21:35:52 UTC 2021 # pylint: disable=missing-class-docstring """Parameter definitions for GoPro BLE and WiFi commands for Open GoPro version 2.0 Note these have to be IntE...
from datetime import datetime import decimal import numpy as np import re from decimal import Decimal import urllib3 from django.http import HttpResponse from django.shortcuts import render_to_response from django.utils.cache import patch_response_headers from django.db import connection from core.libs.cache import ...
from maze.zeolite import Zeolite from ase.visualize import view def main(): cha = Zeolite.make('CHA') cluster, od = cha.get_cluster(10) # print(cluster.additions) # cluster = cluster.remove_caps('h_caps', 'h_caps_6_') # print(cluster.name) # print(cluster.index_mapper.main_index) # open_fr...
from mongoengine import DynamicDocument from mongoengine.fields import ( StringField, IntField, DictField, DateTimeField, ObjectId, FloatField, BooleanField ) class BadgeTypeModel(DynamicDocument): host = StringField() ownid = IntField() blockchain = StringField() caption = StringField() ...