content
stringlengths
5
1.05M
from PIL import Image import numpy as np import _pickle as pickle import os import glob # only using the library for confusion_matrix from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from knn import NearestNeighbour # Loads a binary patch file def load_CIFAR_batch(file): """ load single...
#!/usr/bin/env python import json from pathlib import Path def minmax_coordinates(path): minx = miny = 0x800000 maxx = maxy = -0x800000 for fn in path.glob('*.json'): with open(fn) as fp: obj = json.load(fp) hole = obj.get('hole', []) figure = obj.get('figure', {}).get(...
""" Testing the radius cutoff utility """ from particula.util.radius_cutoff import cut_rad def test_cuts(): """ testing cuts: * test if starting radius is lower than mode * test if ending radius is higher than mod * test if lower radius is smaller than end radius *...
import sys import numpy as np from daetools.pyDAE import * from time import localtime, strftime from pyUnits import m, kg, s, K, Pa, mol, J, W, kJ, hour, l class model2(daeModel): def __init__(self, Name, Parent=None, Description=''): daeModel.__init__(self, Name, Parent, Description) self.muMax ...
from numpy.random import seed seed(1) from tensorflow import set_random_seed set_random_seed(2) import os os.environ["KMP_AFFINITY"]="disabled" import csv import math import tensorflow as tf import FK2018 #import objgraph #from pympler.tracker import SummaryTracker import mrcnn.model as modellib import pandas as pd fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class InvoiceContactInfo(object): def __init__(self): self._contact_addr = None self._contact_mail = None self._contact_mobile = None self._contact_name = None @pro...
cont = 0 total = 0 soma = 0 num = int(input('Digite um número [999 para parar]: ')) while num != 999: soma += num total += 1 num = int(input('Digite um número [999 para parar]: ')) print('Você digitou {} números e a some entre eles foi {}'.format(total, soma))
# Copyright 2017-present Adtran, Inc. # # 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 writ...
import sys sys.path.append("../pyscatwave/") import numpy as np import scipy as sp import scipy.io import scipy.optimize import torch from torch.autograd import Variable from full_embedding import FullEmbedding from solver_hack_full import SolverHack, MSELoss, offset_greed_search_psnr from check_conv_criterion import ...
# importing packages from multiprocessing import pool from pprint import pprint from pytube import YouTube from youtube_dl import YoutubeDL import os from multiprocessing.pool import Pool def download(value): for count in range(0, 3): try: initial_list = YouTube(value) audio = init...
''' Function: 斐波那契数列 Author: Charles ''' class Solution: memory = {} def fib(self, n: int) -> int: if n <= 1: return n if n not in self.memory: self.memory[n] = (self.fib(n-1) + self.fib(n-2)) % 1000000007 return self.memory[n]
from flask import render_template_string import flask_featureflags from flask_caching import Cache from dmutils.flask_init import pluralize, init_manager from dmutils.forms import FakeCsrf from .helpers import BaseApplicationTest import pytest @pytest.mark.parametrize("count,singular,plural,output", [ (0, "pers...
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg class Preprocessor: thresh_sobelx_max = {'gray': 100, 'sat': 100} thresh_sobelx_min = {'gray': 50 , 'sat': 20 } def crop(self, image): #Clip the ROI xLength = image.shape[1]; ...
import contextlib import inspect import io from enum import Enum from functools import lru_cache from importlib.metadata import entry_points from typing import Type, TextIO, Optional, TypeVar, List, get_args, get_origin from uuid import UUID from pydantic import BaseModel _EDB_TYPES = { "string": "str", "bool...
__author__ = 'super3'
#!/usr/bin/env python import unittest from tempfile import mktemp, mkstemp import os from anuga.utilities.data_audit import * class Test_data_audit(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_license_file_is_not_valid1(self): """Basic test using ...
from __future__ import division from gurobipy import * from miscs import * import numpy as np #following Tests are prepared for double checking def CTbaseline(k, rest): tmpSum = 0.0 for i in rest: tmpSum +=utiliAddE(i) tmpSum = utiliAddE(k)+tmpSum #print tmpSum if tmpSum <= np.log(2): ...
#! /usr/bin/env python from __future__ import print_function from __future__ import division from manual_preds import manual_train_and_predict from info_reduc import random_error from auto_preds import auto_train_and_predict from sklearn.preprocessing import scale import pickle import math import numpy as np import pa...
# Copyright 2020 - 2021 MONAI Consortium # 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 wri...
from .http import EasydbClient from .domain import SpaceDoesNotExistException, BucketDoesNotExistException, ElementDoesNotExistException, \ TransactionDoesNotExistException, MultipleElementFields, ElementField, Element, FilterQuery, \ PaginatedElements, TransactionOperation, OperationResult, Element, UnknownOp...
# terrascript/data/stackpath.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:27:49 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.data.stackpath # # instead of # # >>> import terrascript.data.stackpath.stackpath # # This is only available for 'official' and 'partner' provi...
from ._GetBool import * from ._GetMotorsHeadingOffset import * from ._GetPOI import * from ._GetPTZ import * from ._InsertTask import * from ._QueryAlarms import * from ._ResetFromSubState import * from ._SetBuzzer import * from ._SetByte import * from ._SetElevator import * from ._SetEncoderTurns import * from ._SetLa...
# Copyright 2018 The TensorFlow Probability 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 o...
#!/usr/bin/env python import matplotlib matplotlib.use("Agg") # NOQA import matplotlib.pyplot as plt import numpy as np import os import re import sys # OpenCV import for python3.5 sys.path.remove('/opt/ros/{}/lib/python2.7/dist-packages'.format(os.getenv('ROS_DISTRO'))) # NOQA import cv2 # NOQA sys.path.append('...
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint import time class Claptrap(object): meta = { 'name': "Claptrap", 'description': "Just few funny Clap Trap's quotes", 'author': "F. Kolacek <fkolacek@redhat.com>", 'version': "1.0", 'triggers': { '^!clap': "haveSomeFu...
#!/bin/python import fileinput def bits_to_int(bits): return int("".join(str(bit) for bit in bits), 2) counts = None total = 0 for line in fileinput.input(): total += 1 bits = [int(bit) for bit in line.strip()] if counts is None: counts = [0] * len(bits) else: assert len(bits) == len(counts) for i in ra...
$ git clone git@github.com:<github_username>/bpython.git
import io import os import csv import json from pdfminer.converter import TextConverter from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfpage import PDFPage PDF_NAME_LIST = [] PDF_LIST = [] DATA_DICT = {} PATH = "your/path/here/" OUTPUT =...
#equipe: Carlos Eduardo Rodrigues de Aguiar import matplotlib.pyplot as plt games = ['God of War','GTA San Andreas','Sonic Unleashed','Super Mario World','Clash Royale','Among Us','League of Legends','Watch Dogs','Dark Souls','Shadow of Colossus'] nota = [9.3,9.2,8.9,9.6,8.0,7.6,7.9,7.8,8.9,9.3] desenvolvedor = ['San...
# coding=utf-8 # @Time : 2021/2/2 15:53 # @Auto : zzf-jeff import numpy as np import cv2 import os import random from tqdm import tqdm train_txt_path = './train_val_list.txt' num_img = 10000 # 挑选多少图片进行计算 img_h, img_w = 640, 640 imgs = np.zeros([img_w, img_h, 3, 1]) means, stdevs = [], [] w...
import boto3 exceptions = boto3.client('macie').exceptions AccessDeniedException = exceptions.AccessDeniedException InternalException = exceptions.InternalException InvalidInputException = exceptions.InvalidInputException LimitExceededException = exceptions.LimitExceededException
import os.path from functools import reduce import operator import data, cabfile, folder, header class InvalidCabinet(Exception): pass class InvalidFileAllocation(InvalidCabinet): pass class EmptyFileName(InvalidCabinet): pass class Cabinet: def __init__(self, buffer, verify_integrity=True): ...
import logging from time import sleep from fluent import handler # Example from https://github.com/fluent/fluent-logger-python custom_format = { 'host': '%(hostname)s', 'where': '%(module)s.%(funcName)s', 'type': '%(levelname)s', 'stack_trace': '%(exc_text)s' } logging.basicConfig(level=logging.INFO) #l = lo...
"""Module to test API class.""" import pytest from mailerlite import MailerLiteApi from mailerlite.constants import API_KEY_TEST @pytest.fixture def header(): headers = {'content-type': "application/json", "X-MailerLite-ApiDocs": "true", 'x-mailerlite-apikey': API_KEY_TEST ...
# -*- coding: utf-8 -*- """ Created on Sun Sep 28 14:25:41 2014 @author: victor @todo Adicionar roleta genérico aqui pois vários algoritmos vão precisar """ import copy from random import randrange #import mysql.connector
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url urlpatterns = patterns("main.views", url(r"ajax/get_signature$", "jsapi_signature"), url(r"ajax/log$", "log"),)
"""Training script, this is converted from a ipython notebook """ import os import csv import sys import numpy as np import mxnet as mx import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # In[2]: def get_lenet(): """ A lenet style net, takes difference of each frame as input. """ ...
from django.apps import AppConfig from django.db.models import signals class PlaybookJobsConfig(AppConfig): name = 'waldur_ansible.playbook_jobs' verbose_name = 'Waldur Ansible Playbooks' def ready(self): from . import handlers Playbook = self.get_model('Playbook') signals.pre_d...
# Generated by Django 3.1.2 on 2020-11-21 00:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cart', '0007_auto_20201102_1902'), ] operations = [ migrations.RemoveField( model_name='search', name='default_facets', ...
__all__ = [ 'configmapping', 'connectionchecks', 'docgen', 'readconfig' ]
"""This module defines a base class for CRDS command line scripts. MAYBE integrate rc, environment, and command line parameters. """ # ----------------------------------------------------------------------------- import sys import os import argparse import pdb import cProfile, pstats import re from collections import...
import numpy as np import dnnlib import dnnlib.tflib as tflib import PIL.Image from tqdm import tqdm import matplotlib.pyplot as plt import pretrained_networks import tensorflow.compat.v1 as tensorflow tf = tensorflow tf.disable_v2_behavior() # Get tf noise variables, for the stochastic variation def generate_zs_from...
#!/usr/bin/python import sys import os import six try: import configparser except: from six.moves import configparser ConfigParser=configparser fusePath = 'fuse' class runScript: def __init__(self): self.runSimulationScript = "cd build\n" self.Name = "unset" def AddName(self,Name...
import unittest from zoolandia import * class TestHabitat(unittest.TestCase): def test_name_empty_string_default(self): habitat = Habitat() self.assertEqual(habitat.name,'') def test_members_empty_set_default(self): habitat = Habitat() self.assertIsInstance(habitat.members, set) def test_add_...
# Generated by Django 2.0.5 on 2019-05-24 14:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import re from neuralparticles.tools.plot_helpers import write_dict_csv from neuralparticles.tools.param_helpers import getParam, checkUnusedParams log_path = getParam("log", "") csv_path = getParam("csv", "") checkUnusedParams() if csv_path == "": csv_path = log_path[:-4] + ".csv" p_loss_l = re.compile("[ ]*(...
from functools import partial from .encentry import EncEntry def EncEntryTemplate(**kwargs): return partial(EncEntry, **kwargs)
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.address import * class QtumTransactionReceiptBloomFilterTest(BitcoinTestFramework): def set_test_pa...
import itertools import os import re import requests from datetime import datetime, timedelta from bson import ObjectId from lxml import etree from constants.spider import FILE_SUFFIX_LANG_MAPPING, LangType, SUFFIX_IGNORE, SpiderType, QueryType, ExtractType from constants.task import TaskStatus from db.manager impor...
""" Copyright 2013 Rackspace 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 writing, software dist...
# from spaceone.tester.scenario import Scenario import random from spaceone.core.utils import random_string from spaceone.tester.scenario.runner.runner import ServiceRunner, print_json __all__ = ['RoleRunner'] class RoleRunner(ServiceRunner): def __init__(self, clients, update_mode=False): self.set_cl...
# 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 writing, software # distributed under t...
""" --- Aircraft Design --- sizing plot for civil-jet (Far 25) *FAR = Federal Aviation Regulation Ref. Kenichi Rinoie, "Aircraft Design method - conceptual design from single pulloperant to SST - " """ import math import time import matplotlib.pyplot as plt class LapseRate: def __init__(self): # L...
""" Component to offer a way to select a date and / or a time. For more details about this component, please refer to the documentation at https://home-assistant.io/components/input_datetime/ """ import logging import datetime import voluptuous as vol from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_N...
# Rest framework imports from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response # Serializers from users_manage_api.serializers import UserLoginSerializer, UserProfileModelSerializer, CreateUserSerializer # Internal apps imports from users_manage_api.mo...
import argparse # We can change the default message by `usage` parser = argparse.ArgumentParser(prog='myprogram', usage='%(prog)s [options]') parser.add_argument('--foo', nargs='?', help='foo help') parser.add_argument('bar', n...
# -*- coding: utf-8 -*- """ lantz.simulators.fungen ~~~~~~~~~~~~~~~~~~~~~~~ A simulated function generator. See specification in the Lantz documentation. :copyright: 2015 by The Lantz Authors :license: BSD, see LICENSE for more details. """ import time import logging import math from . impor...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
import boto3 import pytest from botocore.exceptions import ClientError from moto import mock_s3 from moto import mock_dynamodb2 from handler import call BUCKET = "some-bucket" KEY = "incoming/transaction-0001.txt" BODY = "Hello World!" TXNS_TABLE = "my-transactions-table" ## Test Setup Functions from contextlib impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'WEB编程的练习' __author__ = 'Jacklee' """ 使用flask框架 处理3个URL 1. GET / 首页 返回HOME 2. GET /signin 登录页,显示登录表单 3. POST /signin 处理登录表单,显示登录结果 对于不同的路由flask使用装饰器进行关联 案例中使用jinja2模板进行页面的渲染 需要安装jinja2 pip3 install jinja2 """ from flask import Flask from flask import request...
from poynt import API class Store(): @classmethod def get_store(cls, business_id, store_id): """ Gets a store by ID. Arguments: business_id (str): the business ID store_id (str): the store ID """ api = API.shared_instance() return api.request(...
from ethereum.utils import sha3 as keccak256, decode_hex from asynceth.test.utils import words async def test_f(jsonrpc, abiv2_contract): method_id = keccak256("f((uint256,uint256[],(uint256,uint256)[]),(uint256,uint256),uint256)")[:4].hex() data = words('80', '8', '9', 'a', '1', '60', 'c0', '2', '2', '3', '2'...
"""The Rituals Perfume Genie integration.""" import asyncio import logging from aiohttp.client_exceptions import ClientConnectorError from pyrituals import Account from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady...
import re print("Example 1 : ") pattern = 'd' sequence = 'abcdef' x = re.match(pattern,sequence) y = re.search(pattern,sequence) print(y.group()) try: print(x.group()) except: print("Using the match function will now return any value. "+ "This is because it seaches from first, and if it is false prints ...
"""test max methods""" __revision__ = None class Aaaa(object): """yo""" def __init__(self): pass def meth1(self): """hehehe""" raise NotImplementedError def meth2(self): """hehehe""" return 'Yo', self class Bbbb(Aaaa): """yeah""" def meth1(self): ...
print ( True or False ) == True print ( True or True ) == True print ( False or False ) == False print ( True and False ) == False print ( True and True ) == True print ( False and False ) == False print ( not True ) == False print ( not False ) == True print ( not True or False ) == ( (not True) or False ) print ( ...
from fastapi import APIRouter from app.core.config import settings from .endpoints import login, users, wishlist api_router = APIRouter(prefix=settings.api_v1_str) api_router.include_router(login.router) api_router.include_router(users.router) api_router.include_router(wishlist.admin_router) api_router.include_rout...
import time from concurrent import futures import grpc from eu.softfire.tub.core import CoreManagers from eu.softfire.tub.core.CoreManagers import list_resources from eu.softfire.tub.entities.entities import ManagerEndpoint, ResourceMetadata from eu.softfire.tub.entities.repositories import save, find, delete, find_b...
# Copyright 2017 Battelle Energy Alliance, LLC # # 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 t...
import requests response = requests.get('https://api.github.com') # Проверка на код if response.status_code == 200: print("Success") elif response.status_code == 404: print('Not Found') # Более общая проверка на код в промежутке от 200 до 400 if response: print('Success') else: print('An error has oc...
"""Run a simple web server which responds to requests to monitor a directory tree and identify files over a certain size threshold. The directory is scanned to pick up the current situation and then monitored for new / removed files. By default, the page auto-refreshes every 60 seconds and shows the top 50 files or...
from graphene.relay.node import Node from graphene_django.types import DjangoObjectType from cookbook.graphql.core.connection import CountableDjangoObjectType from cookbook.ingredients.models import Category, Ingredient from cookbook.ingredients.filtersets import IngredientFilterSet # Graphene will automatically map...
from django.urls import path from the_mechanic_backend.v0.service import views urlpatterns = [ path('', views.ServiceList.as_view(), name='create-service'), # # path('<int:service_id>/', views.ServiceDetailsView.as_view(), name='update-service'), path('general/', views.GeneralServiceView.as_view(), n...
from django.conf.urls.defaults import url, patterns, include registry_urlpatterns = patterns( 'varify.samples.views', url(r'^$', 'registry', name='global-registry'), url(r'^projects/(?P<pk>\d+)/$', 'project_registry', name='project-registry'), url(r'^batches/(?P<pk>\d+)/$', 'batch_registry', na...
#!/usr/bin/env python3 # Copyright (c) 2018 The Zcash developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://www.opensource.org/licenses/mit-license.php . from test_framework.authproxy import JSONRPCException from test_framework.test_framework import BitcoinTestFramewor...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): """ Config class Contains path information for the face detection cascade and the Bowie image. """ CASCADE_PATH = os.environ.get('CASCADE_PATH') or os.path.join(basedir,'data','cascade.xml') BOWIE_PATH = os.environ.get('BOWIE...
import unittest from handlers.declension_handler import DeclensionHandler from casing_manager import get_words_casing, apply_words_cases, apply_cases class DeclensionHandlerTest(unittest.TestCase): def test_inflected_text(self): text_handler = DeclensionHandler() source_text = "Иванов Ив...
for c in range(2, 51,2): print(c, end=' ') print('esses são os números pares')
__author__ = 'MBlaauw' #!/usr/bin/env python from pylearn2.datasets import DenseDesignMatrix from pylearn2.utils import serial from theano import tensor as T from theano import function import pickle import numpy as np import csv def process(mdl, ds, batch_size=100): # This batch size must be evenly divisible int...
# -*- coding: utf8 -*- """ .. module:: burpui.api.client :platform: Unix :synopsis: Burp-UI client api module. .. moduleauthor:: Ziirish <hi+burpui@ziirish.me> """ import os import re from . import api, cache_key, force_refresh from ..engines.server import BUIServer # noqa from .custom import fields, Resour...
#!/usr/bin/python # -*- coding: utf-8 -*- from include import * from timecat import locate_next_line dataset_index = 0 def judge(f, st, ed): global dataset_index dataset_index += 1 print("\ndataset[{}]".format(dataset_index)) locate_next_line(f, st, ed) print(f.readline()) if __name__ == "__m...
#coding: utf-8 from caty.core.typeinterface import dereference try: from sqlalchemy import * from sqlalchemy.orm import * from interfaces.sqlalchemy.SQLAlchemy import SQLAlchemyBase except: import traceback traceback.print_exc() print '[Warning] sqlalchemy is not installed or sqlalchemy IDL is n...
#!/usr/bin/python3 import sys import battlelib dirin = '/home/vova/stud_tanks/' dirout = '/home/vova/tanks-results/res/' prefix = 'https://senya.github.io/tanks-results/res/' prefix = 'res/' players = ['krohalev', 'patritskya', 'kozlova', 'venskaya', 'scherbakov', 'mishina', 'lomonosov', 'abdrakhimov'] #players = ['b...
#!/usr/bin/env python3 from led_system import LEDSystem system = LEDSystem() system.createConfig(249)
import os import threading import PIL.Image as IMG import numpy as np def send_to_back(func, kwargs={}): t = threading.Thread(target=func, kwargs=kwargs) t.start() def save_as_img(tensor, to_dir='tensor_img'): def f(tsr=tensor, dir=to_dir): t = tsr.clone().detach().cpu().numpy() * 255 t...
import os import themata project = 'themata' copyright = '2020, Adewale Azeez, Creative Commons Zero v1.0 Universal License' author = 'Adewale Azeez' html_theme_path = [themata.get_html_theme_path()] html_theme = 'sugar' html_favicon = 'images/themata.png' master_doc = 'index' exclude_patterns = [ 'ha...
import itertools import random import os from math import floor, ceil from functools import partial import cv2 import json import numpy as np from PIL import Image import torch.utils.data import torchvision.transforms.functional as xF from torchvision.transforms import ColorJitter from skin_lesion.default_paths impor...
#addfunctions.py def add(num1,num2): result=num1+num2 return result def addall(*nums): ttl=0 for num in nums: ttl=ttl+num return ttl
import pygame from pygame.locals import * import player import boss_toriel import boss_mario import boss_captain boss_cons = boss_captain.CaptainViridian class Game: def __init__(self): pygame.mixer.pre_init(48000, -16, 2, 1024) pygame.init() self.display = pygame.display.set_mode((400,70...
import h5py import sys # argv[1] : H5 file path # argv[2] : path to actions list with h5py.File(sys.argv[1], 'r') as fin, open(sys.argv[2], 'r') as fin2: act_names = fin2.read().splitlines() act = act_names[fin['stream0/logits'].value.argmax()] print('Detected action: {}'.format(act))
# 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) from spack import * class Bzip2(Package): """bzip2 is a freely available, patent free high-quality data compress...
import cv2 import os import sys import imutils imgpath = sys.argv[3]#Source folder namp = sys.argv[4] #Folder to write files def movdet(imx,imy,ind): imc = cv2.imread(imx,0) #copy of the image to crop without boxes im0 = cv2.imread(imx,0) #Reads frame in gray im1 =cv2.imread(imy,0) #Reads frame in gra...
#导入pymysql的包 import pymysql import threading def demo(conn): try: cur=conn.cursor()#获取一个游标 cur.execute('select id from 10 ORDER BY RAND() LIMIT 1000') data=cur.fetchall() print(len(data)) # cur.close()#关闭游标 # conn.close()#释放数据库资源 except Exception :print("查询失败")...
# Ein Palindrom ist ein Wort das in beide Richtungen gleich gelesen wird: # Bsp: Anna, Drehherd, Kukuk # # Bauen Sie eine Funktion, die ein Wort entgegennimmt und dann zurückgibt, ob es sie bei dem Wort um ein Palindrom handelt oder nicht. #wort = input("Geben sie ein Wort ein") def palindrom(wort): wort = wort....
import urlparse import urllib3 import requests import time import heapq from bs4 import BeautifulSoup import robotparser import os CRLF = '\r\n' FIELD_END = '#' ENTRY_END = '$' # It would be more natural to use a Max-Heap in this program. # Since I already had my old code for a Min-Heap, I employed that by negating t...
import json import re with open('warnings.txt', 'r') as f: w = json.loads(f.read()) for elem in w['missing-variable-declarations']: print elem[0] + ':' + elem[1] + ' ' + elem[3]
from typing import Optional from pydantic import BaseModel class JobCat(BaseModel): job_cat: str class JobDesc(BaseModel): job_desc: str
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from src.RegularShape import RegularShape class SymmetricShape(RegularShape): # def _count_points(self, num): # line = get_line(self.points[0], self.points[1]) @staticmethod def name(): return 'Symmetric Shape'
import discord from cogs.utils.settings import Settings from cogs.utils.botdata import BotData from cogs.utils.helpers import * from cogs.utils.helpformatter import MangoHelpFormatter import cogs.utils.loggingdb as loggingdb import traceback import asyncio import string from discord.ext import commands import logging ...
import hashlib import numpy as np from django.conf import settings from dicom_to_cnn.tools.pre_processing import series from dicom_to_cnn.model.reader.Nifti import Nifti from dicom_to_cnn.model.post_processing.mip.MIP_Generator import MIP_Generator class DicomToCnn: def to_nifti(self,folder_path: str): ...