text
stringlengths
8
6.05M
""" 剑指 Offer 66. 构建乘积数组 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B 中的元素 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。 """ """ 这个不能用除法还真的是神仙操作呢,可以稍微研究一下,其实首先完全可以暴力破解,就根据这个公式来写,但是这样时间复杂度很高,不是最优解法. 得通过观察,假如A = [1,2,3,4,5],那么: B1 = 1 * 2 * 3 * 4 * 5 B2 = 1 * 1 * 3 * 4 * 5 B3 = 1 * 2 * 1 * 4 * 5 B4 = 1 * 2 * 3 * 1 * 5...
import pytest from heap import build_heap, heap from copy import copy @pytest.fixture def hp(): keys = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] return build_heap(keys) def _test_e2i(hp): for i in range(hp.size): assert hp.e2i[hp.es[i]] == i def _test_heap_property(hp): for i in range(1, hp.size):...
import math import csv import numpy as np import random as rand import spectral import matplotlib.pyplot as plt print 'Fast Planted Vector' def test_file(): Y = np.loadtxt(open("Y.csv","rb"),delimiter=",",skiprows=0) q = np.loadtxt(open("q.csv","rb"),delimiter=",",skiprows=0) YSY = get_YSY(Y) spa...
# -*- coding: utf-8 -*- def compute(): num=int(input()) if num == 1: print("Not Prime") elif num == 2: print("Prime") elif num < 0: print("Not Prime") elif (num-1)%2==0: print("Prime") else: print("Not Prime") co...
import time from logging import log import functools from elasticsearch import Elasticsearch from elasticsearch.exceptions import ConnectionError as ElasticConnectionError, ConnectionTimeout as ElasticTimeOutError, TransportError, \ ConnectionError def timeout_fallback(result, enable=False, last_time=5 * 60): def...
from customers.Aurora.medication_admin.medication_admin_mappings import ( DISCONT_REASON, DOSE, MAR_ACTION, MAR_DURATION, REASON, SITE, UNIT) from lib.master_fake_data_generator import FakeDataGenerator class AURORAMedicationAdminFakeDataGenerator(FakeDataGenerator): def generate_pipeline_row(self, row: str,...
# import the necessary packages from report_handler import handle_report from datetime import datetime from pyimagesearch.utils import Conf class TrackableObject: def __init__(self, objectID, centroid, licenseNumber=str()): # store the object ID, then initialize a list of centroids # using the curr...
from leetcode.tree import printtree class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def reverseTree(self, root): """ :type root: TreeNode :rtype: List[int] """ if __name__ == "_...
from django.core.exceptions import ValidationError from django.db import models from borg_utils.publish_status import EnabledStatus class PublishAction(object): """ Represent all the pending actions after last publish """ publish_all_action = 1 publish_data_action = 4 publish_feature_action = ...
#!/usr/bin/env python3 # NeoPixel library strandtest example # Author: Tony DiCola (tony@tonydicola.com) # # Direct port of the Arduino NeoPixel library strandtest example. Showcases # various animations on a strip of NeoPixels. import argparse import base64 import hashlib import json import logging import os import r...
from requests_ import groups_get, friends_get, groups_list_info, check_user from functions import json_to_file, print_json_file, sort_groups import datetime """ Ввод данных (идентификатор пользователя) осуществляется через консоль. Аргументом может быть как id так и screen_name. Идентификаторы, которые я использовал д...
import pygame import json from ship import Ship # TO-DO: reset frame-timer to 0 everytime the scoreboard transition thing is called. class Scoreboard: """Display level, ship_left, high-score, and current score""" def __init__(self, main_game): self.main_game = main_game self.settings = self.ma...
from distutils.core import setup setup( name='vent', version='0.2.1', packages=['vent', 'vent.core', 'vent.core.file-drop', 'vent.core.rq-worker', 'vent.core.rq-dashboard', 'vent.core.template-change', 'vent.core.rmq-es-connector', 'vent.helpers', 'tests', 'scripts', 'scripts.info_tools', 'scripts.service...
#this will work # Melih Özşeker islem=input("islemi giriniz:") sayi1=int(input("Sayi1:")) sayi2=int(input("Sayi2:")) if islem=="+": sonuc=int(sayi1)+int(sayi2) print("Sonuc:",str(sonuc)) elif islem=="-": sonuc=int(sayi1)-int(sayi2) print("Sonuc:",str(sonuc)) elif islem=="*": sonuc=int(sayi1)-int(...
import sys import cv2 import numpy as np from PyQt5.QtWidgets import * from PyQt5 import uic video_list = [None, "real_drive.mp4", "car_driving.mp4", "highway.mp4"] class MyWindow(QMainWindow): def __init__(self): super().__init__() self.ui = uic.loadUi("line_detect.ui", self) self.horisl...
# -*- coding: utf-8 -*- #money=int(input()) #Amount=eval(input()) #Month=int(input()) #a=[] #b=[] #for i in range(1,6): # a.append(i) #print("{:5s}{:>11s}".format("Month","Amount")) #for i in range(5): # money=money+money*Amount/1200 # b.append(money) # print("{:^5d}{:12.2f}".format(a[i],b[i])) m=int(input...
import EoN import numpy as np def simulation(G, tau, gamma, rho, max_time, number_infected_before_release, release_number, background_inmate_turnover, stop_inflow_at_intervention, p, death_rate, percent_infected, percent_recovered, social_distance, social_distance_tau, initial_infected_l...
import numpy as np from collections import defaultdict, OrderedDict from . import uff_pb2 as uff_pb from .data import FieldType, create_data from .exceptions import UffException from .node import Node from .utils import extend_with_original_traceback, int_types def _create_fields(default_fields, fields=None): de...
import numpy as np import matplotlib.pyplot as plt import numba from pprint import pprint import time @numba.njit(fastmath=True) def vdd(y, x0, alpha, noise): x = x0 xs = np.empty_like(y) for i in range(len(xs)): x = alpha*x + y[i] + noise[i] xs[i] = x return xs @numba.njit(fastmath=Tr...
from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session, sessionmaker, scoped_session from sqlalchemy import create_engine from sqlalchemy import inspect Base = automap_base() database_username = 'root' database_password = 'root' database_ip = 'localhost' database_name = 'mmr' eng...
from urllib import request url = 'https://www.flickr.com/search/?text=aurora%20polaris' c = request.urlopen(url) http = c.read().decode('utf-8') imurls = [] start = 0 while True: index = http.find('img.src', start) if index == -1: break imurls.append('http:' + http[index+9 : http.find(';', index)...
from django.conf import settings as const from api.models import Collection, Category, Make, \ Model, Artifact, CollectionArtifact, Image, Transfer, Notification from api.serializers import CollectionSerializer, CategorySerializer, \ MakeSerializer, ModelSerializer, ArtifactSerializer, CollectionArtifactSeriali...
#WAP TO INPUT THREE NUMBERS AND CHECK WHETHER THEY FORM A TRIANGLE a=input("Enter first side : ") b=input("Enter second side : ") c=input("Enter third side : ") if a<b+c and b<a+c and c<a+b: print "It's a triangle!" if a==b==c: print "It's an equilateral triangle.." elif a==b or b==c or a=...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys import os.path from PyQt4 import QtCore, QtGui QtCore.Signal = QtCore.pyqtSignal import vtk from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor class VTKFrame(QtGui.QFrame): def __init__(self, parent = None): super(VTKFrame,...
import sys import pandas as pd import numpy as np def loadmsoaData(dirName='../Loneliness'): msoaData = pd.read_excel('%s/msoa_loneliness.xlsx'%(dirName), 'msoa_loneliness', index_col=None) msoaDataDict = pd.read_excel('%s/msoa_loneliness.xlsx'%(dirName), 'Data Dictionary', index_col=None) return msoaData, msoaDat...
# Copyright 2010-2012 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 """Provides an easy-to-use python interface to Gentoo's metadata.xml file. Example usage: >>> from portage.xml.metadata import MetaDataXML >>> pkg_md = MetaDataXML('/usr/portage/app-misc/gourmet/metadata.xm...
#!python3 from numpy import random from time import perf_counter def selection_sort(array): "a is a list like iterable. returns sorted version of a" for i in range(len(array)): j = 1 k=i while i+j<len(array): if array[i+j] < array[k]: k = i+j ...
import os import uuid from datetime import datetime, timezone, timedelta from io import BytesIO from threading import Lock import pytest import pytz from wacryptolib._crypto_backend import get_random_bytes from wacryptolib.utilities import ( split_as_chunks, recombine_chunks, dump_to_json_bytes, dump_...
from scipy.signal import butter, lfilter, resample from tqdm import tqdm from pylab import genfromtxt import scipy.io as io import numpy as np import pandas as pd import lib.utils as utils import random import os import sys sys.path.append('..') from methods import pulse_noise def bandpass(sig, band, ...
import os project_folder = './Sklearn' os.makedirs(project_folder, exist_ok=True) # copy the training script into project directory import shutil shutil.copy('train_iris.py', project_folder)
#!/usr/bin/env python # -*- coding: UTF-8 -*- import pandas as pd import pickle import random from scipy import misc import sklearn.preprocessing from src.util.BaseProcess import BaseProcess from conf import FeatureCNNConf from conf import DataType from src.util.filter.InfoFilter import InfoFilter from src.util.filter...
# def in_box(): # customer_name = str('Jasmine') # current_date = str('Novemeber 27, 2020') # # def inputes(): # default_survey = '''{customer_name}, your feedback is realy important. Please give a positive feedback. # Have a great day ahead. Happy shopping. Today's date is {current_date}.''' # # def co...
class Solution: def isPowerOfFour(self, n: int) -> bool: while n > 4 and n % 4 == 0: n //= 4 if n == 1 or (n > 0 and n % 4 == 0): return True else: return False
import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 4.5] statistics.mean(data) statistics.median(data) statistics.variance(data)
import pygame import sys import random import math from OpenGL.GL import * from OpenGL.GLU import * # general OpenGL initialization def init_opengl(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90.0, float(width)/height, 0.1, 100.0) glMa...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.helm.check.kubeconform import chart from pants.backend.helm.check.kubeconform.chart impor...
# coding=utf-8 BOT_NAME = 'myspider' SPIDER_MODULES = ['myspider.spiders'] NEWSPIDER_MODULE = 'myspider.spiders' ROBOTSTXT_OBEY = False # 遵守robots协议 LOG_LEVEL = 'DEBUG' # 日志级别 CONCURRENT_REQUESTS = 20 # 线程数 DOWNLOAD_DELAY = 0.01 # 间隔时间 REDIRECT_ENABLED = True # 不允许重定向 #HTTPERROR_ALLOWED_CODES = [302, 405, 303,...
# -*- coding: utf-8 -*- """ Created on Mon May 27 22:12:22 2019 @author: HP """ import math import heapq n,k=input().split() n=int(n) k=int(k) A = [int(x) for x in input().split()] C=[] for i in range(1,n): small=math.inf for j in range(i-k,i): if j>=0: if C[j]<small: ...
from command_interface import Command from receivers import * class SandwichCommand(Command): """ A concrete / specific Command class, implementing exectue() which calls a specific or an appropriate action of a method from a Receiver class. Args: lunch (Lunch): Receiver class to be attache...
# -*- coding: ms949 -*- from sklearn.datasets.samples_generator import make_blobs import matplotlib.pylab as plt from sklearn.cluster import KMeans X, Y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0) kmeans = KMeans(n_clusters=4) # n_clusters: 군집의 개수 kmeans.fit(X) y_kmeans = kmean...
n = int(input()) arr = list(map(int,input().strip().split()))[:n-1] sum1 = sum(arr) sum2 = (n*(n+1))//2 ans = sum2 - sum1 print(ans)
# -*- encoding: utf-8 -*- """ Topic:定义数据库模型 """ from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime from settings import DATABASE def db_connect(): """ 连接数据库 :return: "...
# -*- coding: utf-8 -*- # @Time : 2019/5/16 1:12 PM # @Author : Shande # @Email : seventhedog@163.com # @File : __init__.py.py # @Software: PyCharm from flask import Blueprint pcadmin = Blueprint('pcadmin', __name__) import app.Tvzhijian.pcadmin.pc_admin
#!/usr/bin/python class Heap(object): def build(self, elements, typ): i = len(elements)/2 - 1 while i >= 0: self.heapify(elements, i, typ) i -= 1 def heapify(self, elements, index, typ): mIndex = self.getMIndex(elements, index, typ) if mIndex != index: temp = elements[index] elements[index...
from django.views.generic import View from django.shortcuts import render from django.contrib.admin.models import LogEntry, ADDITION from django.contrib.contenttypes.models import ContentType from blog.models import Post from events.models import Event from songs.models import Song def get_or_none(model, **kwargs): ...
class simple: def __init__(self): print("constructor called,".format(id(self))) a = simple()
# Generated by Django 3.0.6 on 2020-05-16 20:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('todos', '0002_auto_20200516_2046'), ] operations = [ migrations.RemoveField( model_name='todo', name='done', ), ...
#!/usr/bin/env python3 import io import csv import xlrd import utils def download(): utils.download_file('https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3534468/bin/' + 'supp_amiajnl-2012-000935_amiajnl-2012-000935supp_table2.xls', '../data/pmid_22647690/supp_amiajnl...
from django.urls import path from .views import index_view,account_of_user,profile_change,details_update,user_todo,change_details,history,view,completed, about urlpatterns = [ path('', index_view, name = 'Home'), path('account/', account_of_user, name = 'Account'), path('updateprofile/', profile_change, na...
Pn = n! – «число перестановок» из n различных знаков (т.е. знаки нельзя повторять) m^n – число наборов по n из m знаков, если знаки можно повторять Обобщение: Сколькими способами из n элементов можно выбрать m, учитывая, что сначала выбираем первую фигуру, потом – вторую и т.д.: n!/(n-m)! - («Число размещений из n по...
'''Compiles the NumPy ufuncs in `c/`. To use from the command line, run the following script: `python setup.py build_ext --inplace` and make sure you are in the `model` directory. ''' import numpy from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from os.path import join as pat...
from roboclaw import * def counterClockwise(speed): M1Forward(speed, 128) M2Forward(speed, 128) M1Forward(speed, 129) def clockwise(speed): M1Backward(speed, 128) M2Backward(speed, 128) M1Backward(speed, 129) def right(): M1Backward(35, 128) M2Backward(35, 128) M1Forward(70, 129) ...
# -*- coding: utf-8 -*- from django.contrib import admin from app.rentacar.models import RentACar class RentACarAdmin(admin.ModelAdmin): model = RentACar list_display = ['id', 'vehicle', 'customer', 'is_back'] admin.site.register(RentACar, RentACarAdmin)
__title__ = 'names' __version__ = '0.0.1' __licence__ = '????' # Losely based on code developed by Trey Hunner at https://github.com/treyhunner/names import os from random import random from bisect import bisect class SingletonMetaClass(type): def __init__(cls, name, bases, dict): super(SingletonMetaClas...
import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt from scipy import ndimage, signal import hylite from hylite import HyHeader import hylite.reference.features as ref from hylite.hyfeature import HyFeature, MultiFeature, MixedFeature from matplotlib.ticker import AutoMinorLocator class HyData(ob...
# coding: utf-8 # In[1]: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) import numpy as np import matplotlib.pyplot as plt # In[2]: """def make_batch(input_data, noise_data, batch_size): index = np.arange(0, len...
chars = open('store.txt',).read(); print(chars) # display the file contents
""" Write a python program to guess the number in the user's mind. randrange function of random module can be used to guess the number in user’s mind. Note: User should think of a number which is in between 1 and 10 (both inclusive). +---------------------+------------------------------+----------------+------------...
'''balancing an inverted double pendulum''' from math import * # specs mass_pen1=131 # pendulum 1 mass [g] len1=213 # link 1 length [mm] mass_pen2=145 # 110g bearing +35 pendulum 2 mass [g] len2=11.35 # link 2 length [mm] x=0.0 # x position of the end effector y=0.0 # y position of the end effector # let theta3 be t...
import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages setup( name = "Wicked Jukebox Database", version = "1.0", license = "BSD 3-Clause", packages = find_packages(), long_description=open("README.rst").read(), install_requires = [ 'sqlalc...
from django.conf.urls import patterns, include, url from django.contrib import admin import login.urls import exercise.url import collection.urls import resources.urls import activity.urls import fortune.urls import bbs.urls import jobs.urls import complaint.url admin.autodiscover() urlpatterns = patterns('', # u...
from typing import ( Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Type, TypeVar, Union, ) from typing_extensions import Protocol from ._pydantic import BaseModel BaseModelSubclassType = TypeVar("BaseModelSubclassType", bound=BaseModel) ModelType = Type...
from django.template import RequestContext from corcho import settings def app_settings(request): return { "settings": settings, }
from objects import glyphs class RogueGlyphs(glyphs.Glyphs): # Should put all of them in at some point, just added the ones that matter # for the initial set of calculations. allowed_glyphs = frozenset([ 'backstab', 'mutilate', 'rupture', 'slice_and_dice', 'vendetta', 'tricks_of_the_tr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 6 15:00:01 2019 @author: andr """ import os import numpy as np import matplotlib.pyplot as plt from copy import copy from tqdm import tqdm name_pulsar = input('Enter name pulsar: ') with open(name_pulsar + '_start.par', 'r') as file: lines...
import tkinter as tk import speech_recognition as sr import os from gtts import gTTS def voice_output(mytext): # Language in which you want to convert language = 'en' # Passing the text and language to the engine, # here we have marked slow=False. Which tells ...
# Generated by Django 2.2.4 on 2019-12-05 09:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('visitors', '0017_auto_20191202_1244'), ] operations = [ migrations.AddField( model_name='track_entry', name='send_ou...
''' 创建一个类 类名:首字母大写,驼峰原则,见名知意 类属性:驼峰原则 类行为:方法或函数 ''' ''' 类本身不占内存空间,实例化的对象占内存空间 格式: class 类名(父类列表): 属性 行为 ''' class People(object): # 定义属性 name = "" age = 0 height = 0 weight = 0 # 定义行为(函数) # 方法的参数必须以self当第一个参数,不传参的话只写self # self代表类的实例(某个对象) def run(self): ...
import sys, io, os, random, logging from jacks.io_preprocess import subsample_and_preprocess from jacks.jacks import infer_JACKS_gene, LOG import numpy as np def read_essentiality(): ess = [l.strip().split("\t")[0] for l in file("../../data/Hart_training_essentials.txt",'r').readlines()[1:]] noness = [l.strip(...
import networkx as nx import matplotlib.pyplot as plt import pandas as pd import scipy.sparse as sp import numpy as np from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, precision_recall_curve from sklearn.manifold import spectral_embedding import node2vec from gensim.models import...
import matplotlib.pyplot as plp, numpy xValue = numpy.random.randn(50) yValue = numpy.random.randn(50) plp.scatter(xValue, yValue) plp.title("Scatter Plot") plp.suptitle("Scatter Title") plp.grid(True) plp.xlabel("xLabel") plp.ylabel("yLabel") plp.show()
#Bubble Sort def bubble_sort(items): '''Return array of items, sorted in ascending order''' swapFlag = True while swapFlag: swapFlag= False for i in range(len(items)-1): if items[i] > items[i+1]: items[i], items[i+1] = items[i+1], items[i] swapFl...
from django.db import models # Create your models here. class Entry (models.Model): creation_date = models.DateField(('creation_date'), auto_now=False, auto_now_add=False, blank=False) updated_date = models.DateTimeField(('updated_date'), auto_now=True, blank = True) class FeelingOptions(models.TextChoic...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
from django.db import models from django.urls import reverse class Catalog(models.Model): name = models.CharField(db_index=True, max_length=200, primary_key=True, verbose_name='Имя') slug = models.SlugField(max_length=200, db_index=True) seo_descr = models.TextField(blank=True, verbose_name='Описание', ma...
preProduto = float(input('Digite o preço do produto:')) desconto = (preProduto * 6)/100 print('O produto descontado 6% ficará com esse preço {:.2f}'.format(preProduto - desconto))
import sys from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QVBoxLayout, QLineEdit, QPlainTextEdit, QStyleFactory, QTableWidget, QAbstractItemView, QTableWidgetItem, QGridLayout, QPushButton, QCheckBox, QComboBox, QHeaderView, QGridLayout...
# Generated by Django 2.2.4 on 2019-09-06 14:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('webapp', '0002_auto_20190906_1959'), ] operations = [ migrations.AlterField( model_name='bsc_chem', name='name', ...
#!/usr/bin/env python ''' encoding: utf-8 Copyright 2011 Red Hat, 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 requi...
from PIL import Image from skimage import color from skimage.feature import hog import collections import datetime import numpy as np import pytest from itertools import product from pelops.features.hog import HOGFeatureProducer def hog_features(img): img = color.rgb2gray(np.array(img)) features = hog(img, or...
def longestCommonPrefix(strs): """ Takes in a list of strings and returns the longest string all of them have in common """ first_character = strs[0][0] output, compare_to = "", "" for string in strs: compare_to = string[0] if compare_to == first_character: return first_character + longestCommonPrefix([x[1:]...
import os import sys ip = sys.argv[1] username = sys.argv[2] passwd = sys.argv[3] remote_dir = sys.argv[4] acct_id = sys.argv[5] os.system('sshpass -p '+passwd + ' scp -o StrictHostKeyChecking=no ' +'/root/accounts/account_'+acct_id+'/data_extracted/retraining_data.csv '+ username+'@'+ip+':'+remote_dir)
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import pytest from pants.backend.python.subsystems.debugpy import DebugPy @pytest.fixture(autouse=True) def debugpy_dont_wait_for_client(monkeypatch): old_debugpy_get_args = DebugPy...
def noonerize(numbers): output = '{}{}'.format if any(not isinstance(a, int) for a in numbers): return 'invalid array' b, c = (str(d) for d in numbers) return abs(int(output(c[0], b[1:])) - int(output(b[0], c[1:])))
import torch import torch.nn as nn from distance.chamfer_distance import ChamferDistanceFunction from distance.emd_module import emdFunction class ChamferDistance(nn.Module): def __init__(self): super(ChamferDistance, self).__init__() def forward(self, pcs1, pcs2): """ Args: ...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from PIL import Image import numpy as np import os import sys import cv2 import time import torch import torchvision.transforms as transforms import torchvision from modeling.deeplab import DeepLab sys.path.append('/opt/ros/melodic/lib/python2.7/dist-packages') import ...
# coding: utf-8 from NaoCreator.setting import Setting Setting(nao_connected=True, debug=True, ip="192.168.0.1") from NaoCreator.Tool.stop import normal_stop from NaoQuest.wait_for import wait_for from PlayerManager.player_manager import Player Setting.naoFaceDetectionRecognition.enableRecognition(True) Setting.naoF...
""" Django settings for vestblog project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) i...
""" 4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2....
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import folium #Import CSV file into DataFrame world_rankings = pd.read_csv('World_University_Ranks_2020.csv') print(world_rankings.head()) #change column data type world_rankings['Percentage_Female'] = pd.to_numeric(world_ran...
import numpy as np def np2pcd(x, y, z, filename, rgb=False): rgb_value=0.05 f=open(filename,'w') f.write("# .PCD v0.7 - Point Cloud Data file format\n") f.write("VERSION 0.7\n") if (rgb==False): f.write("FIELDS x y z\n") f.write("SIZE 4 4 4\n") f.write("TYPE F F F\n") ...
import numpy as np import matplotlib.pyplot as plt import random leafyFactor = .15 herbFactor = .5 predFactor = .7 leafyMat = np.full((10,10), 100) herbMat = np.full((10,10), 50) turn = 0 #max leafyPop = 100 leafyPop = 80 herbPop = 5 predPop = .5 def leafyGrowth(): leafyConc = leafyPop / 100 leafyInv = 1...
#!/usr/bin/env python # tau.yelo.at - views # -*- coding: utf-8 -*- import psutil from flask import render_template from . import app @app.route("/") def index(): divide_mb = 1000000 divide_gb = 1000000000 mem = psutil.virtual_memory() disk = psutil.disk_usage('/') cpu_percent_us...
#!/usr/bin/env python from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np #import pylab as pl import numpy as np import os import struct import argparse import glob import sys import math import Diffusion2D.unit_vec as uv class Iter_Data: def __in...
from panda3d.core import NodePath, CardMaker, Vec4, Quat, Vec3, SamplerState, OmniBoundingVolume, BillboardEffect from panda3d.core import CollisionBox, CollisionNode, CollisionTraverser, CollisionHandlerQueue, BitMask32, Point3 from panda3d.core import LPlane, LineSegs, AntialiasAttrib from bsp.leveleditor import LEG...
# -*- coding: utf-8 -*- import re from itertools import groupby, izip_longest from operator import itemgetter from collections import Counter def find_middle_x(x1, x2): cut_x1_i = x1.index('.')+11 cut_x2_i = x2.index('.')+11 cut_x1, prec_x1 = float(x1[:cut_x1_i]), x1[cut_x1_i:] cut_x2, prec_x2 = float...
from django.shortcuts import render from django.http import HttpResponse from .models import Destination def index(request): des1= Destination() des1.desc= 'The city that never sleep' des1.city='Marrakech' des1.price=800 return render (request, 'index.html',{'des1':des1}) # Create your views ...
import requests from datetime import datetime #Default - shows for Moscow api_key = "3e61296365ff0da7ca77775d7fd89edb" """ test_url = 'http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=' + api_key resp = requests.get(test_url) if resp.status_code in [200, 201]: weather_data = resp.json() print(...
import abc class FileDriverBase(abc.ABC): def onLoad(self): pass @abc.abstractmethod def read(self, filename, **kwargs): pass