text
stringlengths
8
6.05M
#!/usr/bin/python3 import argparse import binascii import bitarray import collections import fcntl import json import os import re import select import signal import socket import subprocess import sys import time import uuid import urllib.request import warnings class Error(Exception): pass class CommandError(E...
import os import sys import colorama from colorama import Fore class Logging(object): """ Logging class with colored message types """ def __init__(self, name=None): colorama.init(autoreset=True) def print(self, msg): sys.stdout.write(Fore.RESET + msg + os.linesep) def _form...
class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums) == 1: return nums[0] l,r = 0,len(nums)-1 while l<r: mid = (l+r) / 2 if nums[r] > nums[mid]: ...
#!/usr/bin/env python # Funtion: # Filename: import re ip_list = [] with open("ip.txt", 'r', encoding='utf-8') as f: for line in f.readlines(): if re.search("(\d{1,3}\.){1,3}\d{1,3}", line) != None: ip_list.append(re.search("(\d{1,3}\.){1,3}\d{1,3}", line).group()) print(ip_list)
import pandas as pd import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import pycountry from mpl_toolkits.axes_grid1 import make_axes_locatable df = pd.read_csv('./MinedDataset/datasetForCovidAuthorConnectivityGraph.csv') selectedColumns = ["Country", "centrality"] df = df.dropna(axis=0, subse...
from flask import Flask, jsonify, request, url_for, json from flask_cors import CORS from flask_socketio import SocketIO # Custom imports from database.DP1Database import Database # status verkiezingen is_published = False # Start app app = Flask(__name__) CORS(app) socketio = SocketIO(app) conn = Database(app=app...
import cairocffi as cairo import ctypes import sdl2 import sdl2.ext from ulugugu import events def main(state): sdl2.ext.init() window = sdl2.ext.Window("ulugugu", (800,600)) window.show() loop(window, state) sdl2.ext.quit() def loop(window, state): sdl_event = sdl2.SDL_Event() should_redraw = True ...
premium_shipping = 125 def ground_shipping(weight): if weight <= 2: return weight * 1.5 + 20 elif weight > 2 and weight <= 6: return weight * 3 + 20 elif weight > 6 and weight <= 10: return weight * 4 + 20 else: return weight * 4.75 + 20 def drone_shipping(weight): if weight <= 2: return ...
""" Part 1: Discussion 1. What are the three main design advantages that object orientation can provide? Explain each concept. Abstraction: You can hide away the "how" of why things work, and interact easily with your classes/instances Encapsulation: You put all the data related to a "thing" o...
# -*-coding:utf-8-*- # AUTHOR:tyltr # TIME :2018/11/25 # regex import re MOBILE_PATTERN = re.compile("1[356789]\d{9}") # 手机 EMAIL_PATTERN = re.compile("\w+@\w+\.\w+") # 邮箱 USERNAME_PATTERN = re.compile("[\w\u4e00-\u9fa5]{6,16}") # 用户名 PASSWORD_PATTERN = re.compile("\w{6,16}") # 密码 # email topic EMAIL_TOPIC = { ...
# make sure you run this from the project parent directory as # data being saved to "models/arima_python/dump" def main() -> None: from cropcore.model_data_access import get_training_data from arima.clean_data import clean_data from arima.prepare_data import prepare_data from arima.arima_pipeline impo...
#!python2 import sys t = int(raw_input().strip()) for a0 in xrange(t): n,k = raw_input().strip().split(' ') n,k = [int(n),int(k)] if (k-1) | k <= n: print k-1 else: print k-2
class Employee: def name(self,name): self.name=name def ID(self,ID): self.ID=ID def time(self,worktime): self.worktime=worktime class Student(Employee): def work(self,time): self.time=time print(name,ID,time) s1=Student() s1.ID(2301)
from PIL import Image import png import sys import numpy as np import os def get_png_files(path): return [os.path.join(dp, f) for dp, dn, filenames in os.walk(path) for f in filenames if "prediction.png" in f ] def make_transparent(f): img = Image.open(f) img = img.convert("RGBA") datas = img.getdata() new...
def count_substring(string, sub_string): c=0 n=len(string) m=len(sub_string) for i in range(n-m+1): k=0 for j in range(i,m+i): try: if string[j] != sub_string[k]: break; except: pass c+=1 ...
#!/usr/bin/env python import re from google_spreadsheet.api import SpreadsheetAPI GOOGLEDOCS_USER = '' GOOGLEDOCS_PASS = '' GOOGLEDOCS_SRC = '' IOG_AMAZON_SHEET = ['', ''] IMACROS_VERSION_BUILD = '8810214' IMACROS_STAGE1 = '/home//iMacros/Macros//#stage1.iim' IMACROS_STAGE2 = '/home//iMacros/Macros//#stage2.iim' ...
from dataset_toolkit.compress_utils import get_zip_ROI_AU import_lib = True try: import pylibmc as mc except ImportError: import memcache as mc import_lib = False class PyLibmcManager(object): def __init__(self, host): self.AU_couple = get_zip_ROI_AU() if import_lib: ...
import abc class Conta(abc.ABC): def __init__(self, numero, titular, saldo, limite=1000.0): self._numero = numero self._titular = titular self._saldo = saldo self._limite = limite @property def saldo(self): return self._saldo @property def titular(self): ...
import random import copy class SingletonInstane: # Singleton 포맷의 클래스. 한번 Tester 클래스를 호출하여 작업하면 이후 Tester 클래스의 새로운 instance를 만들어도 이전의 상태를 유지. __instance = None @classmethod def __getInstance(cls): return cls.__instance @classmethod def instance(cls, *args, **kargs): cls.__instan...
import numpy as np import treecorr import twopoint import fitsio as fio import healpy as hp from numpy.lib.recfunctions import append_fields, rename_fields from .stage import PipelineStage, TWO_POINT_NAMES import os CORES_PER_TASK=64 global_measure_2_point = None def task(ijklm): i,j,k,l,m=ijklm global_measu...
from pymongo import MongoClient db = MongoClient()['iot-anyware'] def insert_db(post, collection = 'sanode'): db[collection].insert_one(post) def search_db(conditions, collection = 'sanode'): return db[collection].find(conditions)
class Node: def __init__(self,val): self.val = val self.left = None self.right = None self.height = 1 class avl: def insert(self,root,key): if not root: return Node(key) elif key < root.val: root.left = self.insert(root.left,ke...
import os BASEDIR = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = False CSRF_SESSION_KEY = os.getenv('CSRF_SESSION_KEY') SECRET_KEY = os.getenv('SECRET_KEY') # SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') SQLALCHEMY_DAT...
import secrets import sedate from copy import copy from enum import IntEnum from onegov.activity.models import Activity, Occasion, OccasionDate, Period from onegov.activity.utils import date_range_decode from onegov.activity.utils import date_range_encode from onegov.activity.utils import merge_ranges from onegov.acti...
# Generated by Django 3.0.5 on 2020-07-03 13:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csp_observer', '0002_auto_20200618_1232'), ] operations = [ migrations.AlterField( model_name='cspreport', name='dis...
import inspect from . import interfaces from notifications.interfaces import BaseMessageInterface def get_interface(class_name: str): modules = inspect.getmembers(interfaces, inspect.isclass) interface = next(filter(lambda obj: obj[0] == class_name, modules), (None, None)) return interface[1]
''' This script exports urls af decore objects in a file. Urls are formed by concatinating bucketUrl with max archive name which are taken from json file. First argument ti the script is input json file and 2nd argument is output file to export links. Usage: exportAssetsUrlsFromAppJson.py -i <input json> -o <output fi...
from guns import Weapon from pygame import Surface import cores from movable import Movable from pygame.event import Event from image_loader import ImageLoader import pygame fonte_30 = pygame.font.SysFont('arial', 30, True) class Character(Movable): def __init__(self, screen: Surface) -> None: s...
import logging import re import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable from nltk.tokenize import word_tokenize from sklearn.preprocessing import PolynomialFeatures import codecs import argparse import torch.optim as optim use_cuda = torch.cuda.is_available() de...
from E160_config import * import math import sys # Use correct package given version of python if sys.version_info[0] < 3: from Tkinter import * else: from tkinter import * from E160_robot import * from PIL import Image, ImageTk class E160_graphics: def __init__(self, environment): self.envir...
# -*- python -*- TaskModel( 'idct', ports = {'input':MwmrInput(256), 'output':MwmrOutput(64), }, impls = [ SwTask( 'idct', stack_size = 1024, sources = [ 'idct.c' ...
#!/usr/bin/env python import cv2 import numpy as np # parse input # argv[1] - images path like "./images/" # argv[2] - input image name (before processed) # argv[3} - output image name (after processed) path = '../../test/' imageName = 'test_rgb.jpg' processedImageName = 'test_rgb_out_kmeans.jpg' reshapeValue = 2 max...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy import Field as field class DoubanmovieItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() #...
import gevent import multiprocessing as mp from gevent import monkey from functools import partial import numpy as np import pandas as pd # http://www.gevent.org/intro.html#monkey-patching monkey.patch_socket() def parallel_apply(data, func, direct_apply=False, process_ct=2, parallelization_module="multiprocessing",...
# -*- coding: utf-8 -*- # @Author: IBNBlank # @Date: 2018-11-03 18:42:27 # @Last Modified by: IBNBlank # @Last Modified time: 2018-11-04 21:30:56 import tensorflow as tf import numpy as np ############### ### 创建数据 ### ############### x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1 + 0.3 #####...
def quick_sort(arr, start=None, end=None): if start is None or end is None or \ not start < end: return i = start j = end base = arr[start] while i < j: # 注意顺序,必须从右边开始 while arr[j] >= base and i < j: j -= 1 while arr[i] <= base and i < j: ...
''' Create a list with at least 10 elements in it :- print all elements perform slicing perform repetition with * operator Perform concatenation wiht other list. ''' #perform repetition with * operator list1 = [1]*7 list2 = [4,5,6] #Perform concatenation with other list list3 = list1+list2...
def GCD(a, b): if b == 0: return a else: return GCD(b, a % b) if __name__ == '__main__': a = int(input("Enter value of A:\n")) b = int(input("Enter value of B:\n")) gcd = GCD(a, b) lcm = (a * b) // gcd print("Greatest Common Divisor : ", gcd) print("Lowest Common Mult...
class Solution: def searchRange(self, nums, target): res = [-1, -1] if not nums: return res l, r = 0, len(nums) - 1 while l < r: m = l + (r - l) / 2 if nums[m] < target: l = m + 1 else: r = m if n...
# this is a float type number number = 3.25 print(type(number)) # this is an int type number anotherNumber = 4 print(type(anotherNumber)) a = 12 b = 3 print(a + b) # addition print(a - b) # subtraction print(a * b) # multiply print(a / b) # dividing print(a // b) # dividing rounding down print(a % b) # remain...
"""Tests downloading and reading of the GO annotation file from NCBI Gene. python test_NCBI_Entrez_annotations.py """ __copyright__ = "Copyright (C) 2016, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" import sys sys.path.insert(0, '..') # Use local version of goatools during t...
import json import os import time from threading import Thread, Event from typing import Optional, Any from mcdreforged.api.all import * QBM_PID = 'quick_backup_multi' PLUGIN_METADATA = { 'id': 'timed_quick_backup_multi', 'version': '1.0.0', 'name': 'Timed QBM', 'description': '一个QuickBackupM插件的扩展,用于定时触发QBM从而进行自动...
# John Harney, Centre College, 09.17.19 # this code exists thanks to Texas-Mark on the official RPi forums, # he shared the code the original (PIR sensor) iteration of this was based on at # https://www.raspberrypi.org/forums/viewtopic.php?t=176241 # button code version relied heavily on Soren at # https://raspberryp...
#!/usr/bin/env python #encoding=utf-8 import tensorflow as tf import numpy as np from multiply import ComplexMultiply import math from scipy import linalg from numpy.random import RandomState rng = np.random.RandomState(23455) from keras import initializers from keras import backend as K import math class CNN(object)...
import os import lmdb # install lmdb by "pip install lmdb" import time import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") import pickle import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image import random random.seed(9001) import torchvision.tra...
__author__ = 'barnett' #refactored factorial(n) for efficiency def factorial(n): result = 1 while n >= 1: result = result * n n -= 1 return result
from hangman import update_word_pattern def checker(): """ Test for the update_word_pattern function Prints a result for all test :return: Boolean value, if the test succeeded """ flag = True if update_word_pattern("word", "__r_", 'h') != "__r_": flag = False el...
from rv.api import m def test_delay(read_write_read_synth): mod: m.Delay = read_write_read_synth("delay").module assert mod.flags == 1105 assert mod.name == "d e l a y" assert mod.dry == 158 assert mod.wet == 273 assert mod.delay_l == 242 assert mod.delay_r == 43 assert mod.volume_l ==...
#!/usr/bin/env python # Funtion: # Filename: import configparser config = configparser.ConfigParser() config.read('new_config.ini') # # # 查询方法 # print(config.sections()) # 打印所有的section,为列表 # conf_section = config.sections()[0] # 取出section里的第一个元素 # print(config.options(conf_section)) # 打印该section下面所有的opti...
#importing necessary packages import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statistics import statsmodels.formula.api as smf import statsmodels.api as sm import pickle ## reading the dataset df=pd.read_csv("C:\\Users\\Ranna\\Documents\\excelR\\Project\\dat...
import tkinter import tkinter as tk from tkinter import Label,Entry,Button,NORMAL,END,RIGHT,Text,Y,WORD #from EXPENSESpack.Pay_Expenses.PayOperation import operation from EXPENSESpack.Pay_Expenses.Model import FormValues from tkinter import messagebox from tkinter.ttk import * class MyForm: No="" am=""...
def media_notas(nome_arquivo): arquivo = open(nome_arquivo, 'r') aluno_nota = arquivo.read() print(aluno_nota) aluno_nota = aluno_nota.split("\n") print(aluno_nota) for x in aluno_nota: print(x) if __name__ == '__main__': media_notas('notas1.txt')
import pytest def get_data(): l = [1,2,3] return l @pytest.fixture(params=get_data(),scope="module") def myfixture(request): print("参数为:{}".format(request.param)) print("执行myfixture") def pytest_collection_modifyitems(session, config, items): print(type(items)) items.reverse() for ite...
# A Simple Hello World application # Assiging String a = "HELLO" b = "World" #The + operator is used to concatinate the two String that was assigned to A and B print(a + b );
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ for n in range(len(nums)): temp = abs(nums[n])-1 if nums[temp] > 0: nums[temp] = -nums[temp] ans = [] for n ...
import os import errno import tarfile from PIL import Image from torch.utils.data import Dataset from .utils import DEFAULT_PATH class ImageNet32Dataset(Dataset): urls = [ 'http://image-net.org/small/train_32x32.tar', 'http://image-net.org/small/valid_32x32.tar' ] raw_folder = 'imagenet32...
from sklearn import linear_model, svm, preprocessing from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from sklearn.model_selection import train_test_split, cross_val_score from sklearn.pipeline import make_pipeline import matplotlib.pyplot as plt from joblib import dump import csv class M...
"""Classes to match FbxObjects and FbxProperties from one FbxScene to another. """ import fbx from brenpy.utils import io_utils from brenpy.core import bpDebug reload(io_utils) from brenfbx.core import bfCore from brenfbx.utils import bfFbxUtils from brenfbx.fbxsdk.core import bfObject DEBUG_LEVEL = bpDebug.Debu...
from . import format
import psycopg2 conn = psycopg2.connect("dbname=postgres user=postgres password=admin_post") cur = conn.cursor() cur.execute(""" CREATE TABLE QIPM.Demographic ( Deomgraphic_EntryID integer, MRN text primary key, Demographic_FirstName text, Demographic_LastName text, Demographic_DOB date, Demographic_Sex text,...
# @Title: 使字符串平衡的最少删除次数 (Minimum Deletions to Make String Balanced) # @Author: 2464512446@qq.com # @Date: 2020-11-15 00:39:59 # @Runtime: 848 ms # @Memory: 22.5 MB class Solution: def minimumDeletions(self, s: str) -> int: n = len(s) a = [0] * n b = [0] * n cur = 0 for i in...
#!/usr/bin/env python3 import os, sys, math, functools, numpy # similarity measures SIMILARITY_EUCLIDEAN = 0 SIMILARITY_MANHATTAN = 1 SIMILARITY_COSINE = 2 # reads files from a folder line by line # iterating returns (line, filename) class DirectoryCrawler: def __init__(self, path): self.path = path ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) # To update the package version number, edit fdp/__version__.py version = {} with open(os.path.join(here, 'fdp', '__version__.py')) as f: exec(f.read(), version) ...
class NoDataFoundException(BaseException): pass
import torch from matplotlib import pyplot as plt import numpy as np import random # 人工生成一个训练样本 # 样本特征数为2 # 假定真实权重为[2,-3.4]_transpose, 偏差b=4.2 # 同时加入一个随机噪声项,服从均值为0,标准差为0.01的正太分布,噪声代表数据集中无意义的干扰 # 样本特征数 num_inputs = 2 # 样本数 num_examples = 1000 # 真值权重 true_w = [2, -3.4] true_w = torch.tensor(true_w) # 转换成tensor true_...
'''Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Sample String : 'The quick Brow Fox' Expected Output : No. of Upper case characters : 3 No. of Lower case Characters : 12 ''' def case(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: ...
import tensorflow as tf import tensorflow_addons as tfa import numpy as np # TODO move p and seed to Augs # TODO add seed to some classes class Augs(object): def __init__(self, only_image): self.only_image = only_image self.p = 0.5 self.perform = True self.seed = None def ran...
from webtest import TestApp as Client def test_view_exceptions(gazette_app): client = Client(gazette_app) assert ( "Sie versuchen eine Seite zu öffnen, für die Sie nicht autorisiert " "sind" ) in client.get('/groups', status=403) assert ( "Die angeforderte Seite konnte nicht ...
#!/usr/bin/python # vim: set fileencoding=UTF-8 d = 0 n = int(input("? ")) if n > 0 : i = 2 while i <= n // 2 : if n % i == 0 : print(n, 'é divisível por', i) d = d + 1 i = i + 1 if d == 0 : print(n, 'é primo.')
import speedycloud bucket_name = "bucketName" key_name = "keyName" file_path = "/root/abc.mp4" cli = speedycloud.create_object_storage_api("access_key", "secret_key") cli.upload_big_data(bucket_name, key_name, file_path, "file", {})
#!/usr/bin/python3 tupla = ('valor1', 'valor2', 'valor3','valor4') #print(tupla1) #print(type(tupla1)) #Criar uma Tupla com valores aleatorios print(f"1º) {tupla}") #Acessar o primeiro indice print(f"2º) {tupla[0]}") #Mostrar o 3º indice em formato de titulo print(f"3º) {tupla[2].title()}") #mostrar a 3ª letra do 3...
# -*- coding: utf-8 -*- # © 2016 Alessandro Martini, Trustcode # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import datetime from odoo import api, fields, models class SaleOrder(models.Model): _inherit = 'sale.order' version = fields.Integer(u'Versão', compute='_compute...
#title :models.py #description : #author :juniorgerdet #date :04-06-2015 #version :0.1 #usage : #notes : #python_version :2.7.10 #============================================================================== from django.db import models from django.contr...
import sys import numpy as np sys.path.append("..") from mcts import MCTS from player import Player from models.dumbnet import DumbNet from neural_network import NeuralNetwork class UninformedMCTSPlayer(Player): def __init__(self, game, simulations): self.game = game self.simulations = simulations...
from ED6ScenarioHelper import * def main(): # 卢安 CreateScenaFile( FileName = 'T2700 ._SN', MapName = 'Ruan', Location = 'T2700.x', MapIndex = 1, MapDefaultBGM = "ed60016", Flags = 0, Ent...
''' Compare raster values. Output confusion matrix. Currently hard-coded for Turner age map bins. INPUTS (in parameter file): -predictionsRaster -truthRaster -outputPath OUTPUT: -confusion matrix CSV EXAMPLE: python compareRasters.py path/to/paramfile.txt ''' import sys, os, gdal import numpy as np ...
# Generated by Django 3.1.7 on 2021-03-18 13:24 import cloudinary.models from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Watch', fields=[ (...
# encoding: utf-8 # pylint: disable=invalid-name,wrong-import-position """ 本项目Invoke Task的入口 基本上是frol/flask-restplus-server-example的一个翻版, 很多都是沿用的frol的配置,然后做了优化与汉化。 出处:https://github.com/frol/flask-restplus-server-example """ import os import platform from invoke import Collection from invoke.executor import Executor...
import random import requests from django.shortcuts import render, redirect import time from .forms import LocationForm from .models import * from .forms import * from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required import os from django.urls import reverse import...
import sys from pylinac.version import __version__ # check python version if sys.version_info[0] < 3 or sys.version_info[1] < 7: raise ValueError( "Pylinac is only supported on Python 3.7+. Please update your environment." ) # import shortcuts # core first from .core import decorators, geometry, imag...
# Generated by Django 2.2.4 on 2019-08-28 15:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('base', '0066_pyproductwebcategory_parent_id'), ] operations = [ migrations.CreateModel(...
import logging import pytest import requests_mock import transaction from onegov.pay.models.payment_providers.stripe import ( StripeConnect, StripeFeePolicy, StripeCaptureManager ) from purl import URL from unittest import mock from urllib.parse import quote def test_oauth_url(): provider = StripeCon...
# -*- coding: utf-8 -*- from odoo import fields from odoo.tools import DEFAULT_SERVER_DATE_FORMAT def format_date(date, date_format=DEFAULT_SERVER_DATE_FORMAT): if isinstance(date, basestring): date = fields.Date.from_string(date) return date.strftime(date_format) def format_amount(amount, decimal_...
#!/usr/bin/python2 #Author Jeganathan Swaminathan <jegan@tektutor.org> <http://www.tektutor.org> import subprocess import json from os.path import expanduser def executeDockerCommand(*args): return subprocess.check_output(["docker"] + list(args)).strip() def docker_inspect(fmt, mcn): return executeDockerComm...
''' Function: 俄罗斯方块主程序 Author: Charles 公众号: Charles的皮卡丘 ''' import sys import random from modules.utils import * from modules.ai import TetrisAI from PyQt5.QtCore import Qt, QBasicTimer from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication, QHBoxLayout, QLabel '''定义俄罗斯方块游戏类''' class TetrisGame(QMai...
import os import zipfile import ntpath import datetime from time import time #basedir = r"C:\test\ziptest" basedir = r"X:\C" today = datetime.date.today() now = time() days = 365 * 3 """ Zips qualified files. """ def zipit(originalFile): try: print "Zipping " + originalFile ...
from redis import StrictRedis import logging class Config(object): """配置文件类""" # 配置秘钥:项目中的CSRF和session会用到 SECRET_KEY = "5I35e4Y6IUrBiEETcwO/eWrJ/Zxl5EbfBp8gHqxE9qQHgqmu" + \ "OnHr2w6zijnMGYdDPrURJSolj9GtFGFmcbg5ZdJnMhx1OqZqI0L" + \ "9AtoGnvlCWUwe0RFzWJEekoubjopmQhrgyZkCU...
''' Created on Nov 3, 2015 @author: Jonathan ''' def canMake(message, letterlist): messageLetters = "".join(message).lower() letterlistLetters = "".join(letterlist).lower() if set(messageLetters) <= set(letterlistLetters): return "yes" else: return "no" if __name__ == '__main__': ...
from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("https://www.youdao.com") driver.find_element_by_id("translateContent").send_keys("hello") sleep(1) driver.find_element_by_id("translateContent").submit() sleep(2) driver.quit()
from .test_camera import TestCamera from construct import Computed, Struct def assert_response_code_different(response, value, reason): 'Check that the code of a response is not value.' try: assert response.ResponseCode != value, reason except AttributeError: pass def assert_response_cod...
#!/usr/bin/python #\file lib1.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Dec.28, 2015 import os def Run(t, *args): a= args[0] if len(args)>0 else None b= args[1] if len(args)>1 else None print '=========' print 'a is:',a print 'b is:',b prin...
from django.db import models class YahooStock(models.Model): rowid = models.CharField(primary_key=True, max_length=40) symbol = models.CharField(max_length=10) exchange_symbol = models.CharField(max_length=10) date = models.DateField() open_price = models.FloatField(blank=True, null=True) high_price = models.F...
def kadane_algo(a): low = high = i = j = 0 s = 0 max_sum = min(a) - 1 for i in range(len(a)): s = s + a[i] print s, max_sum if s > max_sum: max_sum = s low = j high = i print "------", max_sum, low, high elif s < 0: ...
# -*- coding=utf-8 -*- # author: dongrixinyu # contact: dongrixinyu.89@163.com # blog: https://github.com/dongrixinyu/ # file: bilstm_attention_model.py # time: 2020-07-15 17:37 # -------------------------------------------------------------------------------- ''' DESCRIPTION: 1、word embedding:词向量一般是普通模型中参数量最大的部分...
""" =========================== Cross-Session Motor Imagery =========================== This example show how to perform a cross session motor imagery analysis on the very popular dataset 2a from the BCI competition IV. We will compare two pipelines : - CSP+LDA - Riemannian Geometry+Logistic Regression We will use ...
from pytimize.graphs import UndirectedGraph from pytimize.parsers import GraphParser edges = GraphParser.parse("sa:3 ab:4 bt:1 td:2 dc:2 cb:2 ac:1 sc:4") g = UndirectedGraph(edges) # Shortest path using primal dual algorithm print(f"Shortest Path: {g.shortest_path('s', 't')}\n") # Shortest path linear program formu...
"""使用列表构建二叉堆""" class binaryheap: def __init__(self): self.heaplist=[0] self.currentsize=0 def add_up(self,i): a=self.currentsize//2 while a>0: if self.heaplist[i]<self.heaplist[a]: temp=self.heaplist[i] self.heaplist[i]=self.heaplist[...
from ex11_1 import parse_cdp_neighbors from draw_network_graph import * infiles = [ "sh_cdp_n_sw1.txt", "sh_cdp_n_r1.txt", "sh_cdp_n_r2.txt", "sh_cdp_n_r3.txt", ] def create_network_map(filenames): result = {} for filename in filenames: with open(filename) as show_command: ...
""" Stuff """ import fbx from types import NoneType from brenpy.qt.bpQtImportUtils import QtCore from brenpy.qt.bpQtImportUtils import QtWidgets from brenpy.qt.bpQtImportUtils import QtGui from brenpy.qt.item import bpQtItemsModels from brenfbx.core import bfCore from brenfbx.qt.scene import bfQtSceneModels from b...
''' I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help. P.S. Each array includes only integer numbers. Output is a number too. (Developer Note: this was the Kana's description, not me asking for help) ''' def array_plus_array(arr1,arr...