text
stringlengths
38
1.54M
import boto3 from botocore.exceptions import ClientError cloudfront_c = boto3.client('cloudfront') def list_distributions(): dl = cloudfront_c.list_distributions() ret = [] if 'Items' not in dl['DistributionList']: return ret for dist in dl['DistributionList']['Items']: ret.append({ ...
"""Example script for testing / validating the linear electric grid model.""" import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go import mesmo def main(): # Settings. scenario_name = mesmo.config.config["tests"]["scenario_name"] results_path = mesmo.utils...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch import argparse import os import json import numpy as np from model import Model_Hotpot, Model_FEVER import data import logging import random import torch.nn as nn import torch.distributed as dist from tqdm import tqdm from pytorch...
five_by_five_grid = [ ['X','0','X','X','X'], ['X','X','0','0','0'], ['X','0','X','0','X'], ['0','X','X','X','X'], ['X','0','0','X','X'], ] col = 0 row = 0 a = 0 b=0 while row < len(five_by_five_grid): for items_r in five_by_five_grid[row]: if items_r == 'X': a=a+1 else: b=b...
import warnings as wn def gen_regdf(df): """Function to create the relevant dummy variables and interaction terms for the probit models. Args: dataFrame containing the categorial variables Returns: ------- A data frame containing the dummy variables a...
# k + n*log(k) # k = len(lists) | n = totalNodes(lists) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None import heapq class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: preHead = ListNode(None) ...
import django from django.db.models.functions import TruncDay, Now, TruncMonth, TruncYear, TruncHour from datetime import timedelta, date, datetime from calendar import monthrange import django from sys import argv import os from django.utils import timezone import random from time import sleep from django.db.models i...
import random print("chuong trình tìm số lớn nhất trong danh sách !") #[123, 3, 4, 3424, 4, 23, 423, 4, 23, 4] # muon co so ngau nhien danh_sach = [] for n in range(10): danh_sach.append(random.randrange(1, 1000)) print('%d,' % danh_sach[n], end='') vi_tri = 0 lasgest_number = danh_sach[vi_tri] for n in rang...
# Import the os module, for the os.walk function import os # Set the directory you want to start from rootDir = 'C:\\Users\\Rhavy\\OneDrive\\Documentos\\IFPB\\Projeto NutrIF\\Sistema\\Fotos\\temp' for dirName, subdirList, fileList in os.walk(rootDir): print('Found directory: %s' % dirName) for fname in fileLis...
class Anagram: def is_anagram(self, word1, word2): dic1 = {} dic2 = {} for c1, c2 in zip(word1, word2): try: dic1[c1] += 1 dic2[c2] += 1 except: dic1[c1] = 1 dic2[c2] = 1 for k, v in dic1.items():...
import math class Point: # all points are in the first and fourth quadrants totalPoints = 0 # class attribute # constructor def __init__(self, xx = 0, yy = 0): self.x = xx # public instance attribute self.y = yy # public instanc...
# syntactic sugar [i for i in range(10)] # list comprehension {i:i**2 for i in range(10)} # dict comprehension
from flask import json ''' Return an error message as json ''' def generateError(message, errorNumber): return json.jsonify( result="error", error=errorNumber, message=message), errorNumber
from __future__ import absolute_import, print_function from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TestCase class ManageProjectKeysTest(TestCase): @fixture def path(self): return reverse('sentry-manage-project-keys', args=[self.organization.slug...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import __author__ = "Diego Cadogan" __copyright__ = "2018" __version__ = "0.1" __license__ = "LGPL" import struct, sys, os, math, platform, time, requests, traceback import numpy as np from PyQt5 import QtCore, QtGui, QtWidgets, u...
# encoding: utf-8 # module PyQt4.QtGui # from C:\Python27\lib\site-packages\PyQt4\QtGui.pyd # by generator 1.145 # no doc # imports import PyQt4.QtCore as __PyQt4_QtCore class QTextFragment(): # skipped bases: <type 'sip.simplewrapper'> """ QTextFragment() QTextFragment(QTextFragment) "...
from collections import deque class Solution: """ @param: start: a string @param: end: a string @param: dict: a set of string @return: An integer """ def ladderLength(self, start, end, dict): if end not in dict: return 0 distance = {start:1} queue = deq...
import json from umqtt.simple import MQTTClient from server import * class ThingsboardMQTTClient(MQTTClient): """ Define un cliente especial para la conexión al servidor de Thingsboard Metodos: publish_telemetry: Utilizado para publicar parametros de telemetría subscribe_rpc: Utilizado pa...
import mysql.connector from mysql.connector import errorcode database = "db_digitaliza" def create_database(): conn = mysql.connector.connect(user='felipe', password='123', host='127.0.0.1') try: cursor = conn.cursor() cursor.execute("CREATE DATABASE {database}".format(database = database)) ...
""" Wrapper for COLOR and UTILITY sub packages. """ from COLLECTION import color from COLLECTION import utilities
# -*- coding: utf-8 -*- # encoding=utf8 from bs4 import BeautifulSoup import requests, csv def cne_object( nacionalidad, cedula ): cedula = str(cedula.upper()).strip(nacionalidad.upper()).strip() nacionalidad = str(nacionalidad).strip().upper() try: #url = 'http://www.cne.gov.ve/web/registro_electoral/ce.php?n...
import socket HOST = '127.0.0.1' # The server's hostname or IP address PORT = 65432 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) while True: a = str(input().strip()) if (a=='stop client'): break s...
import enum import random #from dlgo.agent import Agent __all__ = [ 'RandomAgent', ] # tag::random-agent[] class RandomAgent():#Agent): def select_move(self, game_state): return random.choice(game_state.legal_moves()) # end::random-agent[]
###################################################################################################### # DDPG Algorithm --- Paper: Continuous control with Deep Reinforcement Learning - Lillicrap (2015) # # Create an actor pi(s) and a critic Q(s,a) # and a copy of these two networks that evolve slowly to improve stabil...
import requests from requests.exceptions import RequestException import argparse def check_url(): try: url = "http://localhost" r=requests.get(url, verify=False) if r.status_code == requests.status_codes.codes.ok: print("%s %s ok" %(url, r.status_code)) except RequestExcepti...
length = float(input("Length of pendulum:")) period = float(input("Enter period of pendulum:")) g = (4*3.142*3.142*length)/(period**2) print("Period of pendulum:",round(g,4),"m/s^2")
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
my_list=[i for i in range(10)] even_list=list(filter(lambda x:x%2==0, my_list)) sq_even=list(map(lambda x:x**2,even_list)) print (sq_even)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time    : 2019/1/13 0013 上午 11:28 # @Author  : Aries # @Site    : # @File    : 命名空间1.py # @Software: PyCharm Community Edition def func1(): print('hehe') def func2(): func1() print('haha') func1() func2()
import sys, math from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QPolygon, QImage from PyQt5.QtCore import Qt, QRect, QPoint class DrawDemo(QMainWindow): def __init__(self): super(DrawDemo, self).__init__() self.ini...
import scrapy class ItunesSpider(scrapy.Spider): name = "applev2" handle_httpstatus_list = [404, 403] allowed_domains = ["apple.com"] start_urls = ["https://www.apple.com/itunes/charts/free-apps/"] custom_settings = {'DOWNLOAD_DELAY': 0.5} def parse(self, response): apps = respons...
#------------ # Author: Shuya Ding # Date: Sep 2020 #------------ import torch import torch.nn as nn import math import numpy as np import torch.nn.functional as F from torch.autograd import Variable import config as cfg from torch.nn.parallel import DistributedDataParallel class AttentionalClassify(nn.Module): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """wcount.py: count words from an Internet file. __author__ = "胡奕潇" __pkuid__ = "1700011716" __email__ = "1700011716@pku.edu.cn" """ import sys from urllib.request import urlopen def wcount(lines, topn=10): import string tol = {} al = [] trans = [] ...
import unittest from airlineReservationAndBooking.boarding_pass import BoardingPass from airlineReservationAndBooking.airline import Airline from airlineReservationAndBooking.aeroplane import Aeroplane from airlineReservationAndBooking.passenger import Passenger from airlineReservationAndBooking.reservation import Res...
t_number = input("Enter number: ") zz = len(t_number) def number_f(z): if z == 10: print('Your phone number is right.') else: print('Your phone number is wrong.') return z number_f(zz)
class Lightbulb: def __init__(self): self.state = "off" # create method change_state here def change_state(self): self.state = 'off' if self.state == 'on' else 'on' print(f"Turning the light {self.state}")
# .Sypnosis: this is a random password generator. saves to a text file after the passwords are generated. import random char = 'abcdefghijklmnopqrstuv1234567890ABCDEFGHIJKLMNOPQRSTUV!@#$%^&*' number = input('Number of passwords to create: ') number = int(number) length = input('Password length: ') length = int(length)...
#!/usr/bin/env python # # Author: Daniela Duricekova <daniela.duricekova@gmail.com> # """Tests for the db module.""" import unittest from teeny_weeny_link.db import Database from teeny_weeny_link.id_generator import IDGenerator class TestDatabase(unittest.TestCase): def setUp(self): self.db = Databas...
class Item(object): def __init__(self, name, bWeight): self.name = name self.bWeight = bWeight self.quantity = 1 def getItemName(self): return self.name def getItemWeight(self): return self.bWeight*self.quantity def setItemWeight(self, weight): self.bWei...
""" Parse command line arguments for Orion ====================================== Parsing and building of the command line input for using script. Simplify the parsing of a command line by storing every values inside a `dict` mapping the name of the argument to its value as a key-pair relation. Positional arguments a...
# ========================================================================= # Logging # ========================================================================= from tools import config import logging.config logging.config.dictConfig(config['logging_config']) logger_discord = logging.getLogger('discord') # import lo...
from django.urls import path from .views import SignUpView from django.contrib.auth import views as auth_views urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change_form.html'), ...
from tkinter import * import webbrowser root = Tk(screenName="Prafull Forms") root.geometry("1000x2000") def newTest(): koot = Tk() Label(koot,text="This Page is Under Construction ",bg="black",fg="cyan").pack() koot.geometry("1000x2000") url = "https://admin.typeform.com/accounts/01FD6BJYK94V21...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 14 14:36:45 2017 @author: ejreidelbach :DESCRIPTION: :REQUIRES: :TODO: :NOTES: NOTE 1: For the Selenium driver to function properly on Ubuntu, I had to download the most up-to-date geckodriver found at: h...
import yaml import time from Utils import datasets import GenericNeuron.LogisticNeuron as logisticNeuron import GenericNeuron.HiperbolicNeuron as hiperbolicNeuron from sklearn.model_selection import train_test_split def main(): stream = open('configurations/runConfigurations.yml', 'r', encoding='utf-8').read() ...
# Morse Code Dictionary morse_code_dict = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '.....
import sys import os from qa_common import * from pathlib import Path class QATestLog(object): def __init__(self,root_dir,incremental_testing): self.successful_tests = root_dir+'/successful_tests.log' self.successful_regression_tests = root_dir+'/successful_regression_tests.log' self....
from attacks import carlini, pgd, carlini_robust_precision def module_from_name(name): if name == 'pgd': return pgd elif name == 'carlini': return carlini elif name == 'carlini_robust_precision': return carlini_robust_precision else: raise ValueError('Attack "{}" not sup...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Exercise 2: Module which substract the background from the picure, corresponding to the data contained in pixels """ import sys import matplotlib.pyplot as plt import mylib def main(): """ Take datas (2D numpy.array) from the fits file specific.fits and d...
""" MENU TOOLS TKINTER """ from tkinter import * from tkinter import ttk import sys from time import sleep versao = '1.2' emais = [] email = '' pw = '' class Menu_App: #initial function def __init__(self, window_m): #window window_m.title('TOOLS BY DEUKAUS') ...
from tkinter import * from tkinter import filedialog from tkinter import messagebox import os from PyPDF2 import PdfFileReader from pdf2docx import Converter class Window(Frame): def __init__(self, master=None): self.targetPdf = "" self.is3Page = IntVar() Frame.__init__(self, master) self.master = master s...
data = list(map(int,input().split())) def baby_gen(number): counts = [0] * 12 run = 0 triplet = 0 for n in number: counts[n] += 1 for i in range(10): if counts[i] >= 3: counts[i] -= 3 triplet += 1 if counts[i] >= 3: counts[i...
import torch.utils.data from torch.nn import functional as F import numpy as np import sklearn.datasets from sklearn.metrics import roc_curve, auc from utils.plot_utils import plot_distribution, plot_save_roc, plot_save_acc_nzs_auroc from utils.data_preprocess import get_threshold, extract_ood from models import nnz...
class BillType: Water = 1 Sewerage = 2 Gas = 3 Other = 4 array = ['Water','Sewerage','Gas','Other']
# 연습문제 복습 # 리스트 초기화 Arr = [[0 for _ in range(5)] for _ in range(5) ] # 우 하 좌 상 dc = [0, 1, 0, -1] dr = [1, 0, -1, 0] # 달팽이 숫자 만들기 # 방향키 인덱스 초기화 i = 0 # 배열 인덱스 초기화 c = r = 0 # 배열에 1부터 25까지 숫자 넣기 for x in range(1, 26): Arr[c][r] = x while x < 25: # 직진했을때, 막히는 벽이 없는 경우 if 0 <= c+dc[i] < 5 and 0...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('accident_avoidance', '0002_auto_20180406_0547'), ] operations = [ migrations.AddField( model_name='coordinates',...
#!/usr/bin/env python3 import cv2 import torch import numpy as np import argparse #import tensorrt as trt from time import time import sys from libs.Loader import Dataset from libs.Criterion import LossCriterion from libs.utils import makeVideo from libs import shufflenetv2 import torch.backends.cudnn as cudnn impor...
import traceback import random import redis import ujson from grand import RandManage from gdata import direction_conf from gdata import percentage_conf r = redis.Redis("127.0.0.1", 6379) key_name = "the_game_data_key" def gen_rand(): rb = RandManage() lst = [] for i in range(200): d = rb.by_wei...
from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, weak=False, dispatch_uid="prepare_appointments_on_post_save") def prepare_appointments_on_post_save(sender, instance, raw, created, using, **kwargs): """""" if not raw: try: instance.pr...
import os #operating systeam #讀取檔案 products = [] if os.path.isfile('products.csv'): #檢查檔案在不在 print('太棒了,找到檔案了') with open('products.csv' , 'r' , encoding = 'utf-8') as f : for line in f : if '商品 , 價格 ' in line : continue name , price =line.strip().split('...
from LinkList import LinkList def Merge2(A,B): #求解算法 p=A.head.next #p指向A的首结点 q=B.head.next #q指向B的首结点 C=LinkList(); #新建立单链表C t=C.head #t为C的尾结点 while p!=None and q!=None: #两个单链表都没有遍历完 if p.data<q.data: #将较小结点p链接到C的...
import numpy as np import cv2 from scipy.spatial.distance import pdist,squareform from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from array2gif import write_gif # predefine colormap colormap= np.random.choice(range(256),size=(100,3)) #colormap=np.asarray([[255,0,0],[0,255,0],[0,0,255],[255,255...
import subprocess from os import popen import os.path import socket import re def check_user(userName): ret = subprocess.call("id "+userName+" > /dev/null 2>&1", shell=True) if ret != 0: return False return True def is_python_3(): python_version = int(str(range(3))[-2]) if python_version ...
def sum(a,b): print(__name__) return a+b def sub(a,b): print(__name__) return a-b print("importing trymof")
# Python program for implementation of Selection sort # Input = [64, 12, 25, 12, 22, 11] # Step 1. [11, 12, 25, 12, 22, 64] # Step 2. [11, 12, 25, 12, 22, 64] # Step 3. [11, 12, 12, 25, 22, 64] # Step 4. [11, 12, 12, 22, 25, 64] # Step 5. [11, 12, 12, 22, 25, 64] = Output import time def selection_sort(a)...
import cirq import utils.misc_utils as mu def test_transfer_flag(): qubit = cirq.NamedQubit("qubit") circuit = cirq.Circuit() circuit.append(cirq.ops.X.on(qubit)) circuit.append(cirq.ops.Y.on(qubit)) circuit.append(cirq.ops.Y.on(qubit)) circuit.append(cirq.ops.X.on(qubit)) mu.flag_operatio...
import torch import pickle import random import numpy as np import matplotlib.pyplot as plt from push_fold_models import Pusher, Caller from push_fold_helper_functions import * # Hand is 'AKs', '87o', etc def holdemResourcesPusher(hand, ranks): pushPerc = 0 if(hand[0] == 'A'): pushPerc = 1 elif(hand[0] == 'K'): ...
import Tkinter import ttk class ViewInventoryFrame(ttk.Frame): def __init__(self, parent): ttk.Frame.__init__(self, parent) self.parent = parent test = ttk.Label(self, text='View Inventory Frame') test.grid(row=0, column=0)
# -*- coding: utf-8 -*- """ Created on Fri Sep 21 21:11:30 2018 @author: 우람 """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import random import os os.chdir('C:\\Users\\우람\\Desktop\\kaist\\3차학기\\청강) 인공지능') #%% Neural Net... 레이어를 여러개 만들어서 합성하는 것. x_data=[[0,0],[0,1], [1,0], [1,1]] y_da...
import os import sys import time import provision from provision import instance if __name__=="__main__": profile ='default' my_key ='vijayaws' instance_name = 'vijayxmstest' owner_email ='vijay.shastry@citrix.com' vpc_filter ='XMS_vijay*' ami_filter ='XMS_Aston_Martin*' build_id ='10.3.6.124' eip_id ...
import sys from . import call_validator from . import utils def _run_test_function(func, args, kwargs, enable_validation): call_validator.CallValidator.enable_validation = enable_validation func(*args, **kwargs) def _check_validation(func): def __wrapper(*args, **kwargs): previous_value = call_...
# Copyright 2014 The Cobalt 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 applicable ...
# -*- coding: utf-8 -*- import os db = DAL('sqlite://storage.sqlite') db.define_table('wp', Field('name', requires=IS_NOT_EMPTY()), Field('json_file', 'upload')) db.define_table( 'customer', Field('doc',label='No. Documento'), Field('full_name'), Field('user_mail'), Field('phone'), for...
#!/usr/bin/env python2.7 # -*- coding: utf-8; -*- ################################################################## # Libraries import tokenizer from alt_argparse import argparser from alt_fio import AltFileInput, AltFileOutput from offsets import Offsets import os from collections import deque ####################...
#coding=utf-8 ''' Created on 2015年5月27日 ''' import time import setting from database.nosql.mongo_engine import MongoEngine from database.rdbs.tataufo import TestDB __author__ = 'chenjian' class BaseProcessor(object): ''' classdocs ''' def __init__(self, handler): ''' Constructor ...
__author__ = "Luke Liu" #encoding="utf-8" # -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os batch_size = 100 z_dim = 100 dataset = 'lfw_new_imgs' # dataset = 'celeba' def montage(images): if isinstance(images, list): images = np.array(images) ...
from __future__ import unicode_literals, print_function, division import torch from torch import optim import torch.nn as nn import util import metrics import model import math import argparse import training def main(): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f'The model wi...
# Generated by Django 2.2.6 on 2019-10-23 08:02 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('asset', '0004_auto_20191014_0953'), ('service', '0001_initial'), ] operations = [ migrations.CreateMode...
######################################################################################### # import # ######################################################################################### import numpy as np fro...
import os import time import threading import traceback import logging import math from pymavlink import mavutil from dronekit.lib import APIConnection, Vehicle, VehicleMode, Location, \ Attitude, GPSInfo, Parameters, CommandSequence, APIException, Battery, \ Rangefinder # Enable logging here (until this code ...
from picklerutil import * filename = "request_cache.pkl" class RequestCache: def __init__(self): self.request_dict = loadFromFile(filename) def saveResponse(self, url, text): self.request_dict[url] = text saveToFile(filename, self.request_dict) def getCachedResponse(self, url): ...
import socket import struct from urllib.parse import urlparse, urlencode from time import time from os import urandom import random import string import trackon import requests import bencode import pprint import subprocess my_ips = [subprocess.check_output(['curl', '-4', 'https://icanhazip.com/']).decode('utf-8').str...
from pexpect import pxssh import os import getpass username = 'cisco' password = os.getenv('ciscopass') device_ip = '192.168.1.76' try: ssh = pxssh.pxssh() ssh.login(device_ip, username, password) ssh.sendline('ls') # run a command ssh.prompt() # match the prompt print(ssh.before) # print every...
# coding=utf-8 from django.dispatch import receiver from django.db import models from datetime import date import os import re from PIL import Image from io import BytesIO from django.core.files.base import ContentFile from resizeimage import resizeimage # -----------------------------------------------------------...
# -*- coding: utf-8 -*- from app import app from app import db, models from flask import jsonify, make_response, render_template, redirect, request, session, send_from_directory, url_for import logic import requests import datetime CLIENT_ID = requests.CLIENT_ID CLIENT_SECRET = requests.CLIENT_SECRET LOGGED_URL = requ...
__author__ = 'zh' # -*- coding: utf-8 -*- from xlwt import * import pickle record_file = open("record_dump.obj",'rb') sales_record = pickle.load(record_file) record_file.close() item_sales = { # 'item_name': { # 'count': xxx # 'money': xxx # } } item_sales_1214 = {} shop_item_sales = { ...
from config.py import * import json from datetime import date from datetime import datetime import pymysql import pymysql.cursors from flask import Flask, flash, redirect, render_template, request, session, abort theatres = {'rialto':'3076','barnstormer':'7629','old-mill-playhouse':'10656'} app = Flask(__name__) def...
# -*- coding: utf-8 -*- from ralph.lib.transitions.admin import TransitionAdminMixin from ralph.lib.transitions.decorators import transition_action from ralph.lib.transitions.fields import TransitionField from ralph.lib.transitions.forms import TransitionForm from ralph.lib.transitions.models import TransitionWorkflowB...
# -*- coding: utf-8 -*- # !/usr/bin/python3 # SkillFramework 1.0.0 face detection demo # yolo v2单类检测模型的后处理 import hilens import cv2 import numpy as np import math # 网络输入尺寸 input_height = 480 input_width = 480 class_num = 1 # 类别数 box_num = 5 # 最后一层的anchor boxes数量 biases = [0.71, 0.70, 1.37, 1.31, 2.01, 2.21, 2.73,...
from django.contrib.gis.db import models from django.contrib.gis.geos import Point import datetime DEFAULT_COUNTRY_ID = 1 DEFAULT_WAVE_ID = 1 DEFAULT_POINT = Point(0, 0, srid=4326) DEFAULT_DURATION = datetime.timedelta(days=0) DEFAULT_SCENARIO_ID = 1 DEFAULT_TARGET_NAME = "Unknown Target" # Create your models here. c...
# # classify.py # # Auto feature selection and SVC training # from sklearn.svm import SVC from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import StratifiedKFold, cross_val_score from sklearn.feature_selection import RFECV, RFE from audio import LABEL_MUSIC, LABEL_SPEECH ,debug import nump...
''' Reverse a linked list. Example For linked list 1->2->3, the reversed linked list is 3->2->1 Challenge Reverse it in-place and in one-pass ''' class Solution: def reverse(self, head): prev, curr, next = None, head, None while curr: next = curr.next curr.next = prev ...
""" This a simple proof of concept script that reads in a EdgeTPU compiled TFLite model and uses CV2 based webcam capture for inference on a MNIST model. """ ################################################################################ # %% IMPORT PACKAGES ###########################################################...
import pandas as pd import random from collections import Counter # initialize custom kmodes class class k_modes: # method # initialize model def __init__(self, n_clusters=3, n_init=10, max_iter=300, random_state=2019): self.n_clusters = n_clusters self.n_init=n_init self.max_iter=m...
#board board = ["_" , "_" , "_", "_" , "_" , "_", "_" , "_" , "_"] check_winner = None game_still_going = True current_player = "X" def display(): print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " +...
# SOURCE: https://github.com/bergran/fast-api-project-template/blob/master/README.md JWT_REGEX = r"^{} [A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$"
a = 3 b = 5 c = 2 if a > b and a > c: maks = a elif b > a and b > c: maks = b else: maks = c print('Maksimum',maks)
# from factory.abstractfactory import AbstractFactory class Bike(): def __init__(self,factory_name): self.factory_name = factory_name def createWheel(self,abs_wheel): self.bike = abs_wheel() self.bike.say_hi(self.factory_name)
from django.shortcuts import render,get_object_or_404 from boutique.models import Lunette from achat.models import Achat # Create your views here. def index(request,id): context={} achat_lunette=get_object_or_404(Lunette,id=id) if request.method=="POST": nom_complet=request.POST.get('nom') a...
import socket import sys import thread def clientThread(conn): #conn.send("Connecting to the server... \n") data = conn.recv(1024) dataParseCommand = data.split('>') command = dataParseCommand[0] print('Received <' + command +'> command...\n') if(command == 'register'): print('Regist...