content
stringlengths
5
1.05M
import ipaddress IPV4_NETMASKS = [int(ipaddress.ip_network(f"0.0.0.0/{i}").netmask) for i in range(32, -1, -1)] IPV6_NETMASKS = [int(ipaddress.ip_network(f"::/{i}").netmask) for i in range(128, -1, -1)] NETMASKS_BY_KEY_TYPE = {"ipv4": IPV4_NETMASKS, "ipv6": IPV6_NETMASKS} def item_to_string(item): try: ...
from random import randint if __name__ == '__main__': upper = 100 lower = 1 ans = randint(1, upper) cont = 0 print('_____________________終極密碼_____________________') print('從0 ~ 100中猜一個數字,看你要猜幾次才能猜中。') while True: cont += 1 print('_____________________Round ' + str(cont) + '...
# # Pyserini: Python interface to the Anserini IR toolkit built on Lucene # # 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...
from __future__ import print_function, absolute_import import sys import os # Set a default for HSAILBIN if it is not defined. # This is only used for cmdline HLC os.environ['HSAILBIN'] = os.environ.get('HSAILBIN', '/opt/amd/bin') # The default location of the HSAIL builtins library DEFAULT_BUILTIN_PATH = os.path.jo...
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib import admin ATTRIBUTE_CHOICES = ( ('name','name'), ('http-equiv','http-equiv'), ) class MetatagType(models.Model): #metatag attribute list attribute = models.CharField(_('attribute'),max_length=...
from __future__ import absolute_import from __future__ import with_statement import sys import types from contextlib import contextmanager from mock import Mock, patch from celery import states from celery.backends.cache import CacheBackend, DummyClient from celery.exceptions import ImproperlyConfigured from celery...
# # PySNMP MIB module FLOW-METER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FLOW-METER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:00:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
"""Utility entry point for analyzing one or more samples storing results on disk or printing to terminal""" import argparse import json import os import tqdm from editops import Alignment # TODO: support saliency weights from a file/string # TODO: support m to n order gram checking if __name__ == '__main__': desc...
import unittest from .solver import solve_simple_wires class TestSimpleWireSolver(unittest.TestCase): def test_ThreeWires(self): input=['yellow', 'yellow', 'black'] self.assertEqual(solve_simple_wires(input, True), 'Cut the second wire') input=['yellow','red','white'] self.assertEqu...
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 11:31:59 2020 @author: Liam Cornu """ # Import des progiciels nécessaires import spotipy import random import redis import os import pytz import datetime import time from creds import username, client_id, client_secret, uri, playlistid # Pseudo du co...
# file: runme.py # Throw a lot of exceptions import example t = example.Test() try: t.unknown() except RuntimeError,e: print "incomplete type", e.args[0] try: t.simple() except RuntimeError,e: print e.args[0] try: t.message() except RuntimeError,e: print e.args[0] try: t....
import torch import numpy as np from clean_reverse import ReversibleModel from audio_midi_dataset import get_dataset_individually, Spec2MidiDataset, SqueezingDataset from torch.utils.data.dataloader import DataLoader from torch.utils.data.sampler import SequentialSampler def get_data_loaders(direction, ...
from __future__ import unicode_literals from unittest import TestCase from wtforms.ext.i18n.utils import get_translations class I18NTest(TestCase): def test_failure(self): self.assertRaises(IOError, get_translations, []) def test_us_translation(self): translations = get_translations(['en_US']...
#desafio 55: maior e menor da sequência usando lista [] pessoas = [] #lista vazia for c in range(1, 6): peso = float(input(f'Peso da {c}ª pessoa: ')) pessoas = pessoas + [peso] #lista += [peso] #add os valores de peso na lista print('><'*15) print(f'\33[33m O Maior peso lido foi: {max(pessoas)}') #máximo va...
from aiohttp import web app = web.Application() async def index(request): res = {"key": "value", "my": "data"} return web.json_response(res) app.router.add_get('/', index) if __name__ == '__main__': web.run_app(app, host='0.0.0.0', port=8888)
# ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # # # Redistribution and use in ...
#!/usr/bin/env python3 import sys import dateutil.parser from rofi import Rofi from taskw import TaskWarrior class RofiWarrior: def __init__(self): self.rofi = Rofi() self.taskw = TaskWarrior() self.keybinds = { "key1": ('Alt+t','list todo'), "key2": ('Al...
import commonVar as common import os import configparser # reading configuratiion file(s) def readConfigFile(): config=configparser.ConfigParser() # to chose an INI file in the current folder filesHere=os.listdir(common.project+"/") selected=[] for i in range(len(filesHere)): if filesHere[...
#!/scratch_net/nudel/esandstroem/venvs/tsdf_fusion_env/bin/python import os app_path = '/scratch_net/nudel/esandstroem/venvs/tsdf_fusion_env/bin' os.environ["PATH"] = app_path + os.pathsep + os.environ["PATH"] from TSDFHandle import * import numpy as np import cv2 from utils import extract_mesh_marching_cubes from vis...
# -*- coding: utf-8 -*- from contextlib import contextmanager from collections import namedtuple from threading import Thread import datetime import time import csv import io import json from .. import ext from .. import compat from ..logging import get_logger from ..errors import * from ..query import Drilldown __a...
#-*- coding: utf-8 -*- import os, struct, numpy dB_MIN = -80. PWI_THS = 60. PW_MIN = PWI_THS * (10.** (dB_MIN / 20.)) class SpectrumBase(object): '''Base type of spectrums''' def __init__(self, audio): self.audio = audio def walk(self, win, step, start, end, join_channels): '''Generato...
from __future__ import print_function import torch from torch.utils import data DEBUG = False import numpy as np import sys import random import torchvision.transforms as transforms from PIL import Image import torchvision.transforms.functional as TF import cv2 import os # this script is the dataloader for Carla class...
"""Simulation box utilities """ import numpy as np import math def pbc_place_inside(box: np.ndarray, r_out: np.ndarray) -> np.ndarray: """Places point inside simulation box applying periodic boundary condition. :param box Simulation box. :param r_out Point possibly outside box. :return r_in Point ins...
""" Simple PERT model in cpmpy. From Pascal van Hentenryck 'Scheduling and Packing In the Constraint Language cc(FD)', page 7f http://citeseer.ist.psu.edu/300151.html Model created by Hakan Kjellerstrand, hakank@hakank.com See also my cpmpy page: http://www.hakank.org/cpmpy/ """ import sys import numpy as np from c...
""" A simple example of NAT performance testing. It will generate multiple short TCP sessions for a configured duration. """ from __future__ import print_function from byteblower.byteblowerll import byteblower from byteblower.byteblowerll.byteblower import HTTPMultiClientStatus_Finished import time # Minim...
import time import datetime import pytz import argparse import numpy as np import torch import matplotlib.pyplot as plt import torch.nn as nn import torch.nn.functional as F import os from PIL import Image import torchvision.utils as vutils from model.net import MonocularDepthModel from model.loss import LossNetwo...
from __future__ import division, absolute_import try: from stsci.image import * except ImportError: try: from scipy.stsci.image import * except ImportError: msg = \ """The image package is not installed It can be downloaded by checking out the latest source from http://svn.scipy.org/svn/sc...
import numpy as np import pandas as pd import theano import theano.tensor as T import gc import time from theano_utils import floatX from ops import euclidean, cosine from sklearn import metrics from sklearn.linear_model import LogisticRegression as LR def cv_reg_lr(trX, trY, vaX, vaY, Cs=[0.01, 0.05, 0.1, 0.5, 1., ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import sys from pathlib import Path import qlib import pandas as pd from qlib.config import REG_CN from qlib.contrib.model.gbdt import LGBModel from qlib.contrib.estimator.handler import QLibDataHandlerClose from qlib.contrib.strategy.strategy...
from twilio.rest.resources.base import InstanceResource, ListResource class Key(InstanceResource): """ A key resource. See https://www.twilio.com/docs/api/rest-keys .. attribute:: sid The unique ID for this key. .. attribute:: friendly_name A human-readable description of this ...
from __future__ import annotations import cv2 as cv import numpy as np class ImageProcessing: def __init__(self, img: np.ndarray): self.img = img self.gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) th, self.threshed = cv.threshold(self.gray, 127, 255, cv.THRESH_BINARY_INV | cv.THRES...
import sys import os import numpy as np import time import datetime import feature_extraction_scripts.organize_speech_data as orgdata import feature_extraction_scripts.feature_extraction_functions as featfun from feature_extraction_scripts.errors import FeatureExtractionFail #to keep saved files unique #include their...
import os from unittest import TestCase from hypergol.base_data import BaseData from hypergol.dataset import RepoData from hypergol.dataset_factory import DatasetFactory class DataClass1(BaseData): def __init__(self, id_: int, value1: int): self.id_ = id_ self.value1 = value1 def get_id(sel...
from events.EventType import EventType from sprite.Tile import Tile, TileState class TileCoveredByObstacle: type = EventType.TILE_COVERED_BY_OBSTACLE def __init__(self, tile: Tile): self.tile = tile self.tile.set_state(TileState.COVERED_BY_OBSTACLE)
# lookup_test.py # Author: Thomas MINIER - MIT License 2017-2018 from http_server.server import sage_app from rdflib import Graph app = sage_app('tests/data/test_config.yaml') client = app.test_client() def test_entity_lookup(): ref_graph = Graph() ref_graph.parse("tests/entity/data/city0.ttl", format="ttl")...
import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from ccarl.glycan_graph_methods import generate_digraph_from_glycan_string from ccarl.glycan_plotting import draw_glycan_diagram def render_features_pdf(model, pdfname): '''Renders features in a PDF document, with one feature p...
# While using this program you need to " TURN ON " the less secure app access setting in the sender mail. # Manage your account -> Security -> Less sure app acces -> TURN ON import smtplib import stdiomask def mail(): sender='Example_mail' # Sender mail receivers = 'Example_mail' # Receiver ma...
def write(filename, content): with open(filename, 'w') as file_object: file_object.write(content) def appendWrite(filename, content): with open(filename, 'a') as file_object: file_object.write(content)
import torch import torch.nn.functional as F import torch.nn as nn from .. import conv3x3x3 from ..classification.myronenko import MyronenkoEncoder, MyronenkoLayer, MyronenkoResidualBlock from ..classification.decoder import MirroredDecoder from ..autoencoder.variational import ConvolutionalAutoEncoder class UNetEnc...
import asyncio from asyncua import Client URL = 'opc.tcp://localhost:4840/freeopcua/server/' async def print_node(node, parent_node=None, path=''): children = await node.get_children() if not children: val = None try: val = await node.read_value() except Exception: ...
#!/usr/bin/python3 """Lists total passenger capacities by type of transport and count of transport type distinct models given a path to a txt file with data.""" import ijson import os from typing import Generator, List, Tuple def main(data_file_path: str) -> None: """Requires the full path of the file with JSON...
import pygame from .constants import ROWS, COLS, BLUE, WHITE, GREEN, RED, RADIUS from .drawing_transition_matrix import x_cord, y_cord from .pegs import Peg from .start_board import start_board class BoardClass: def __init__(self): self.board = [] self.red_ingoal = self.green_ingoal = 0 se...
import os # isort: skip from time import time import cv2 import numpy as np import torch import matplotlib.pyplot as plt from tqdm import tqdm from torch.utils.data import DataLoader import segmentation_models_pytorch as smp from utils import configuration from utils.dataset import SegmDataset from utils.build_mo...
from asyncio import futures from concurrent.futures import ThreadPoolExecutor from slim.utils import get_ioloop thread_executor = ThreadPoolExecutor(max_workers=4) def run_in_thread(fn, *args, **kwargs): return futures.wrap_future( thread_executor.submit(fn, *args, **kwargs), loop=get_ioloop() )
from .StructBlockWithStyle import StructBlockWithStyle from wagtail.wagtailcore import blocks from common.blocks import LANGUAGE_CHOICES class CodeBlock(StructBlockWithStyle): language = blocks.ChoiceBlock(choices=LANGUAGE_CHOICES, default="python") codes = blocks.TextBlock() class Meta: # form_...
from django.contrib.auth.models import User from .models import Question, Answer from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email"] class AnswerSerializer(serializers.ModelSerializer)...
#coding:utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='csdncommenter', version='0.0.6', description='CSDN 已下载资源自动批量评论脚本', long_description=open('README.md').read(), url='https://github.com/mzlogin/csdncommenter', author='Zhuang ...
import numpy as np def get_worldcoord_from_imagecoord(image_coord, intrinsic_mat, extrinsic_mat): project_mat = intrinsic_mat @ extrinsic_mat project_mat = np.linalg.inv(np.delete(project_mat, 2, 1)) image_coord = np.concatenate([image_coord, np.ones([1, image_coord.shape[1]])], axis=0) world_coord = ...
class Car(): def needsFule(): pass def getEngineTemperature(): pass def driveTo(dest): pass
__author__ = 'Ben, Ryan' # -*- coding: utf-8 -*- import numpy as np import time import math from scipy import stats from matplotlib import pylab as plt import stockrollover def time_stamp(t): """Prints the difference between the parameter and current time. This is useful for timing program execution if times...
"""Functions that help us work with files and folders. """ import logging import os from qmk.errors import NoSuchKeyboardError def keymap(keyboard): """Locate the correct directory for storing a keymap. Args: keyboard The name of the keyboard. Example: clueboard/66/rev3 """ for d...
import pandas as pd chunk_size = 10 ** 4 dimension_vectors = [50, 100, 200, 300] d = dimension_vectors[3] csv_reader = pd.read_csv("../../txt/glove.6B."+str(d)+"d.txt", \ sep=" ", \ engine="python", \ chunksize=chunk_size, \ ...
# import the necessary packages #from skimage.measure import structural_similarity as ssim import matplotlib.pyplot as plt import numpy as np import cv2 def mse(imageA, imageB): # the 'Mean Squared Error' between the two images is the # sum of the squared difference between the two images; # NOTE: the two ...
# 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/. import pytest from pages.desktop.knowledge_base_new_article import KnowledgeBaseNewArticle from pages.desktop.questions...
from builtins import object import factory from bluebottle.statistics.models import Statistic class StatisticFactory(factory.DjangoModelFactory): class Meta(object): model = Statistic type = 'manual' title = factory.Sequence(lambda n: 'Metric {0}'.format(n)) value = None sequence = facto...
from __future__ import absolute_import import theano import theano.tensor as T import types def softmax(x): return T.nnet.softmax(x) def time_distributed_softmax(x): xshape = x.shape X = x.reshape((xshape[0] * xshape[1], xshape[2])) return T.nnet.softmax(X).reshape(xshape) def softplus(x): return...
#!/usr/bin/env python # # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """Maintainer review action. This action checks which packages have changed in a PR, and adds the...
from inspect import signature from collections import namedtuple import time import torch from torch import nn import numpy as np import torchvision import torch import torch.cuda import torch.nn as nn import torch.distributed as dist import torch.optim from torch.utils.data import DataLoader from utils import * # N...
import numpy as np import scipy.signal as sp def filter_boundary_normal(hrfparam, X): """ This function attempts to optimize costly operations in the original code. 'Normal' version. :param hrfparam: HRF filter parameters :param X: Matrix of time series :return: filtered time series """ ...
# Generated by Django 2.2.6 on 2019-12-05 13:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0023_auto_20191203_0029'), ('Clubsite', '0001_initial'), ] operations = [ migrations.Al...
# -*- coding: utf-8 -*- from .binary_cross_entropy import BinaryCrossEntropyCriterion from .cross_entropy import CrossEntropyCriterion from .kd_label_smoothed_cross_entropy_loss import KDLabelSmoothedCrossEntropyCriterion from .label_smoothed_cross_entropy import LabelSmoothedCrossEntropyCriterion
from pywire import * def increment(x): return x+1 clock_counter = Signal(26) clock_counter.drive(increment, clock_counter) def get_top_bit(x): if x > (2**25): return True else: return False flipping_bit = Signal(1, signed=None) flipping_bit.drive(get_top_bit, clock_counter) def ide...
# PuLP : Python LP Modeler # Version 1.4.2 # Copyright (c) 2002-2005, Jean-Sebastien Roy (js@jeannot.org) # Modifications Copyright (c) 2007- Stuart Anthony Mitchell (s.mitchell@auckland.ac.nz) # $Id:solvers.py 1791 2008-04-23 22:54:34Z smit023 $ # Permission is hereby granted, free of charge, to any person obtaining...
""" The PyTorch-based MistNet algorithm, used by both the client and the server. Reference: P. Wang, et al. "MistNet: Towards Private Neural Network Training with Local Differential Privacy," found in docs/papers. """ import logging import time import numpy as np import torch from plato.config import Config from pl...
from django.shortcuts import render from .models import PhoneBook from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.views.generic import ListView, DetailView, CreateView , UpdateView, DeleteView from bootstrap_modal_forms.generic import BSModalReadView, BSModalCreateView, ...
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # 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...
# -*- coding: utf-8 -*- import sys, random from collections import defaultdict, deque CACHE_DELIM = '\v' TERMINATOR = '\f' class Markovator: """ Data is a list (corpus) of lists (sentences) of strings (words) example = [ [ "Lorem", "ipsum", "dolor", "sit", "amet.", ], [ "Consectetur...
# Generated by Django 3.1.2 on 2021-01-01 22:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('volunteers', '0015_volunteerapplication_organizer_teams'), ] operations = [ migrations.AddField( model_name='volunteer', ...
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
from __future__ import absolute_import from lxml import etree from sciencebeam_utils.beam_utils.io import ( save_file_content ) from sciencebeam_gym.utils.pages_zip import ( save_pages ) from sciencebeam_gym.structured_document.lxml import ( LxmlStructuredDocument ) from sciencebeam_gym.structured_docu...
name = "text2digits" __version__ = "0.0.9"
from django.conf.urls import url from . import views app_name = 'longfellow' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^post/(?P<pk>[0-9]+)/$', views.detail, name='detail'), url(r'^about.html$', views.about, name='about'), url(r'^category.html$', views.category, name='category') ]
""" iniciar com letra, pode conter nuemros, separar _ , letras minusculas """ nome = 'Lincoln' # print(nome, type(nome)) idade = 38 altura = 1.74 e_maior = idade >= 18 peso = 88 imc = peso / (altura ** 2) print('Nome:', nome) print('Idade:', idade) print('Altura', altura) print('É maior de idade: ', e_maior) print('P...
import os import os.path as path import sys import progReader import glob from typing import List rootDir = path.join(os.path.dirname(__file__), "../") longSnippetsFileGlob = path.join(rootDir, "[A-Z]*/**/*.hpp") shortSnippetsFileGlob = path.join(rootDir, "short-snip/*.[ch]pp") def genSnippet(srcFiles: List[str], us...
from bot import botNet import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) if __name__ == '__main__': bot = botNet.botNet() bot.main()
# Switch between four states (INT PHASE, MW DET B) # INT PHASE can be 0 (TRUE) or pi/2 (FALSE) # MW DET B can be on (TRUE) or off (FALSE) from DAQ.Environment import * def prompt(text): sys.stdout.write(text) return sys.stdin.readline().strip() def go(intPhaseZeroVoltage, intPhasePiBy2Voltage): # prompt to enter...
from gutfit.experimentalneutrinomassmatrix import ExperimentalNeutrinoMassMatrix from gutfit.type1and2seesaw import Type1And2SeeSaw from gutfit import parameterlist def sample(E,PL,m1): p=PL() p["data_neutrino_m1"] = m1 return E(p) #https://stackoverflow.com/questions/13377046/scipy-fill-a-histogram-readi...
''' @description 2019/09/03 23:34 ''' # 1.使用单引号或者双引号括起来的。(在python中,双引号和单引号都可以用来生成字符串) # 2.但是如果你开头使用的是单引号,那么结尾必须使用单引号。就是前后要一致。 text = 'hello world' print(text) print(type(text)) # str # 3.如果想要存储多行的字符串,那么可以使用六个单引号或者六个双引号。 # 4.如果想要在写代码的时候将一行字符串放到多行中显示,但是真正生成字符串的时候,不需要换行,那么可以在每一行的末尾加上\。 # break_text = '''hello # worl...
"""Authoritative project's version-info""" __version__ = "1.0.0.dev12" ## Semantic-version: Update identifiers also in README.rst. __updated__ = "2019-08-30 14:55:39"
import os import numpy as np from PIL import Image class Augmentation(object): def __init__(self, data_dir, flip=True): super(Augmentation, self).__init__() self.data_dir = data_dir self.flip = flip self.array_data = [] self.flip_data = [] self.augment_data = [] self.shifting_rate = 1e-1 def get_data(...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright © 2013 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this d...
from flask import Blueprint debug = Blueprint('debug', __name__, template_folder='templates') from . import views
import redis as pyredis from ebedke import settings redis = pyredis.StrictRedis(host=settings.redis_host, port=settings.redis_port, decode_responses=False) RedisConnectionError = pyredis.exceptions.ConnectionError
# -*- coding: utf-8 -*- from ogs5py import OGS model = OGS( task_root='1d_1_root', task_id='1d_1', output_dir='out', ) model.msh.read_file('1d_1.msh') model.gli.read_file('1d_1.gli') model.pcs.add_block( main_key='PROCESS', PCS_TYPE='GROUNDWATER_FLOW', NUM_TYPE='NEW', ) model.pcs.add_block( ...
# Stats Functions
import torch import time import numpy as np from spikee.utils import evaluate import os def train(optimizer, batcher, model, delta, steps, data = None): ''' Training the model. To monitor the training, mean scores for train, valid and negative triples can be shown. optimizer: torch optimizer batcher: ...
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
import os import time from datetime import timedelta import discord import psutil as psutil from discord.ext import commands class Stats(commands.Cog, name="Stats"): def __init__(self, client): self.client = client @commands.command(name="stats") async def view_stats(self, ctx): """ ...
import urequests from simp_py import mon import re import time,sys r_tm = r'(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)' re_tm = re.compile(r_tm) pv_update='' v_min=999999999 v_max=0 ts='' btc=0 def get_btc_info(): global urequests,time,re_tm,pv_update,v_min,v_max,mon,ts,btc try: response = urequests.get('htt...
# coding=utf-8 from __future__ import absolute_import, division, print_function, \ unicode_literals import filters as f from iota import Bundle, TransactionHash from iota.commands import FilterCommand, RequestFilter from iota.commands.extended.get_bundles import GetBundlesCommand from iota.commands.extended.send_...
import os, sys sys.path.append(os.path.join(os.path.dirname(__file__))) import random from decimal import Decimal from sinaps import Sinaps from neuron import Neuron, InputNeuron, HiddenNeuron, OutputNeuron, BiasNeuron class NeuroNet: @classmethod def createNet(cls, neuronList, E, A, isBiasNeuronEnabled = F...
import itertools x = 0 d = {} for i in itertools.product(".#", repeat=9): binnum = int("".join(i).replace(".","0").replace("#","1"),2) na = sum([i[j]=="#" for j in range(len(i)) if j != 4]) if i[4] == "#": if na < 2: d[binnum] = "." elif na > 3: d[binnum] = "." ...
# -*- coding: utf-8 -*- from model.group import Group import pytest import random import string def random_string(prefix, maxlen): # string will be chosen from letters, digits and 10 spaces -- ' '*10 symbols = string.ascii_letters + string.digits + string.punctuation + ' '*5 return prefix + ''.join([rando...
import numpy as np from scipy.optimize import minimize_scalar #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # original MATLAB code from Wanxiang: # # # 1> syms x_sym latt_sym vol_sym % use symbolic computation # 2> latt_sym = [ 2*x_sym 0 z; # 3> ...
from utils import ( setup_fs, load_dbc_files, list_log_files, ProcessData, MultiFrameDecoder, ) from utils_db import SetupInflux import inputs as inp # initialize connection to InfluxDB + get latest data entries per device influx = SetupInflux(inp.influx_url, inp.token, inp.org_id, inp.influx_bucke...
class Solution: def sortByBits(self, arr: list[int]) -> list[int]: arr.sort() key = lambda x: bin(x).count("1") return sorted(arr, key=key)
version = "1.5.2" __version__ = version project_name = "datarobot-drum"
# -*- coding:utf-8 -*- # Create by 27 # @Time : 2020/3/1 02:23 __author__ = '27' class NoneLocal: def __init__(self, v): self.v = v n = NoneLocal(1)
from ansiblelint import AnsibleLintRule class ShellAltService(AnsibleLintRule): id = 'E507' shortdesc = 'Use service module' description = '' tags = ['shell'] def matchtask(self, file, task): if task['action']['__ansible_module__'] not in ['shell', 'command']: return False ...
import numpy as np import tifffile as tiff import os from tensorflow.keras import backend as K class Data_Generator: def __init__(self, C): """ C is the config from config.py """ self.fov_size = C.field_of_view_scales self.cropped_size = C.cropped_size # we should apply SAME padding self....