text
stringlengths
38
1.54M
# Python __slots__:限制类实例动态添加属性和方法 # 前面介绍了为对象动态添加方法,但是所添加的方法只是对当前对象有效,如果希望为所有实例都添加方法,则可通过为类添加方法来实现。 from types import MethodType class Cat: def __init__(self, name): self.name = name def walk_func(self): print('%s慢慢地走过一片草地' % self.name) d1 = Cat('Garfield') d2 = Cat('Kitty') # d1.walk() # Attribut...
from bs4 import BeautifulSoup import urllib3 from urllib.parse import urljoin import csv urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) http = urllib3.PoolManager() arquivo = 'ceesc.csv' conselho = 'ceesc' ##########################################################################################...
# author: weicai ye # email: yeweicai@zju.edu.cn # datetime: 2020/7/27 下午2:25 # 一个已排序好的表 A,其包含 1 和其他一些素数.  当列表中的每一个 p<q 时,我们可以构造一个分数 p/q 。 # # 那么第 k 个最小的分数是多少呢?  以整数数组的形式返回你的答案, 这里 answer[0] = p 且 answer[1] = q. # # 示例: # 输入: A = [1, 2, 3, 5], K = 3 # 输出: [2, 5] # 解释: # 已构造好的分数,排序后如下所示: # 1/5, 1/3, 2/5, 1/2, 3/5, 2/3...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ''' Created on Fri Mar 10 15:48:51 2017 @author: heitor ''' from netpyne import sim, specs import numpy as np from matplotlib import pyplot as plt from DetectPA import getSpikes numCells = 1 netParams = specs.NetParams() simConfig = specs.SimConfig() netParams.popParam...
import random lives = 9 words = ['shirt', 'human', 'fairy', 'teeth', 'otter', 'plane', 'eight', 'pizza', 'lives'] secret_word = random.choice(words) clue = list('?????') heart_symbol = u'\u2764' guessed_word_correctly = False def update_clue(guessed_letter, secret_word, clue): index = 0 for char in secret_wor...
import json from datetime import datetime from tempfile import NamedTemporaryFile from airflow.hooks.S3_hook import S3Hook from airflow.models import BaseOperator from google_analytics_plugin.hooks.google_analytics_hook import GoogleAnalyticsHook class GoogleAnalyticsReportingToS3Operator(BaseOperator): """ ...
import csv """ CONVERT DATA FROM API TO PROPHET FORMAT """ path = './Parking_Lot_Counts.csv' f = open(path) lines = f.readlines() print("Done reading file") with open('./libraryparking_everyhalfhour_today.txt','w') as fil: numberOfLines = 0 writeToFile = False #file_writer = csv.writer(fil, delimiter=',', quo...
import pygame import GraphicSprite class Wall(GraphicSprite.GraphicSprite): image = "" tilex = 0 tiley = 0 x = 0 y = 0 width = 0 height = 0 def __init__(self,image, x, y, width, height): pygame.sprite.Sprite.__init__(self) self.image = "sprites/wall/" + image ...
import math class Pewma: def __init__(self, p_d_init, p_alpha, p_beta): self.p_d_init = p_d_init self.p_alpha = p_alpha self.p_beta = p_beta self.count = 0 self.est_var = float('nan') self.est_mean = float('nan') self.s1 = 0 self.s2 = 0 ...
# -*- coding: utf-8 -*- ''' 创建一个People 类,People 的属性有name 和age,两个参数在实例化的时候传给构造器,People 类的方法有getName 和getAge,分别返回姓名和年龄。 程序输入(用一个空格分开):姓名 年龄 程序输出:同输入 ''' ins = input().split(' ') name, age = ins[0], int(ins[1]) class People: # 请在这里编写代码 # 构造方法 def __init__ (self, name, age): self.name = name ...
from django.contrib import admin # Register your models here. from .models import Service , Category , ServiceImages admin.site.register(Service) admin.site.register(Category) admin.site.register(ServiceImages)
from unittest import TestCase from ..highest_value_palindrome import HighestValuePalindrome class TestHighestValuePalindrome(TestCase): def test_solution(self): inp = '' output = '' with open('strings\\medium\\tests\\test_cases' + '\\tc10_highest_value_palindrome.txt') ...
#!/usr/bin/env python3 # HW08_ch11_ex02d.py # (1) Write a more concise version of invert_dict_old. # (2) Paste in your completed functions from HW08_ch11_ex02a.py # (3) Update print_hist_new from HW08_ch11_ex02b.py to be able to print # a sorted version of the dict (print key/value pairs from 0 through the # largest ...
""" Approach: since you cannot delete the current node, delete the next node. TC: O(1) SC: O(1) """ class Solution: #Function to delete a node without any reference to head pointer. def deleteNode(self,curr_node): #code here if curr_node.next: curr_node.data = curr_node.next.data ...
__author__ = 'Ian' import matplotlib.pyplot as plt import matplotlib.dates as mdates import os import pandas as pd import numpy as np from sklearn.metrics import accuracy_score from Data.scripts.data import data from pandas.tools.plotting import autocorrelation_plot def run_strategy(Y_pred, Returns_df): #make ne...
#! /usr/bin/env python #@author: Emre Havazli import os import sys import glob import h5py from numpy import * from operator import itemgetter import collections import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt import matplotlib.mlab as mlab def main(argv): try: directory = argv[1...
#coding=utf-8 from selenium import webdriver import time import os import progressbar from dannyTumblr.DataBase import Mysql_data class Log: def __init__(self): self.mysqldata = Mysql_data() def Login_progressbar(self,sec): bar = progressbar.ProgressBar(max_value=sec, widgets=['►►',progressb...
#!/usr/bin/env python3 red = '\033[0;31m' yellow = '\033[0;33m' orange = '\033[1;31m' magenta = '\033[0;35m' print(orange + 'hello, what is your name?') name = input(red + '> ' + magenta + ' ') print(yellow + 'hello, ' + magenta + name)
''' University of Santo Tomas Faculty of Engineering Electronics Engineering Department First Term, AY 2019-2020 Machine Problem ECE2112: Advanced Computer Programming and Algorithms Marvin Dale Wong & Aaron Vincent Zabala 2ECE-A Given a certain set of experimental points (xi, yi), regardless of how many, the progr...
import random def maxi(a,i,b,j): return (a,i) if a>b else (b,j) def mini(a,i,b,j): return (a,i) if a<b else (b,j) def maxseq(a): if len(a) <= 1: return 0 d = 0 m, M, mi, Mi, le = a[0], a[0], 0, 0, a[0] A = [] t = 1 for i,e in enumerate(a): if e == le: ...
"Intermediate AST representation used by other parts of the project." import ast class Var(ast.AST): _fields = ["id", "type"] def __init__(self, id, type=None): self.id = id self.type = type class Assign(ast.AST): _fields = ["ref", "val", "type"] def __init__(self, ref, val, type=N...
import logging import re import os from os.path import sep import matlab2cpp from . import m2cpp import matlab2cpp.pyplot from . import reference def flatten(node, ordered=False, reverse=False, inverse=False): """ Backend for the :py:func:`~matlab2cpp.Node.flatten` function. Args: node (Node): Root node to ...
import os from math import gcd from functools import reduce def f(n, p, w, d): if n * w < p: return -1 GCD = reduce(gcd, [n, p, w, d]) n //= GCD p //= GCD w //= GCD d //= GCD z_min = int(n - p / d) - 1 z_min = z_min if z_min > 0 else 0 for z in range(z_min, n + 1): ...
from tkinter import * from functools import partial # Prevent unwanted windows import csv import re import random class Start: def __init__(self, partner, ): # Start GUI self.start_frame = Frame(padx=10, pady=10, bg="#D4E1F5") self.start_frame.grid() # background backgrou...
from unittest import TestCase from src.socketserve import deserialise class test_deseraliser(TestCase): def setUp(self) -> None: pass def test_valid_string(self): expected_string = """ { "throttle":5.2321, "yaw":44.44332, "pitch":44.321, ...
# -*- coding: utf-8 -*- """ Created on Sun Apr 14 11:24:17 2019 将轨迹数据填充到轨迹网格中,但是每个用户的网格规模是(512*401*4),将一天划分为4个时间段,所以每个人的channel为4 @author: Administrator """ import pandas as pd import numpy as np from tqdm import tqdm from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten fr...
from jira import JIRA import os from os.path import join, dirname from dotenv import load_dotenv class JiraConnector(object): """SendGrid GitHub Issues & Pull Requests""" def __init__(self, **opts): dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) self._userna...
import pamqp from pamqp.specification import Basic from pamqp.specification import Exchange from pamqp.specification import Queue from aiormq.types import ConfirmationFrameType class EmitACK: '''The producer frame confirmation class. ''' def __init__(self, confirmation: ConfirmationFrameType): s...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import UpdateVi...
from typing import List class Solution: def partition(self, s: str) -> List[List[str]]: self.Palindrome = lambda s: s == s[::-1] res = [] self.helper(s, res, []) return res def helper(self, s, res, path): if not s: res.append(path) return ...
#! /usr/bin/env python import cv2 import time import cv_bridge import rospy import numpy as np from matplotlib import pyplot as plt from scipy import signal, ndimage from sensor_msgs.msg import Image global imL global imR ### Vecorized implementation using Numpy Library ### class DisparityMap(): def __in...
from django.urls import path from . import views app_name = 'newsletter' urlpatterns = [ path('new/', views.new, name='new'), path('confirm/', views.confirm, name='confirm'), path('delete/', views.delete, name='delete'), ]
import numpy as np import math from newtonPoly import * xData = np.array([0.15,2.3,3.15,4.85,6.25,7.95]) yData = np.array([4.79867,4.49013,4.2243,3.47313,2.66674,1.51909]) a = coeffts(xData,yData) print(" x yInterp yExact") print("-----------------------") for x in np.arange(0.0,8.1,0.5): y = evalPoly(a, xData, x)...
import numpy as np import pandas as pd from sklearn.neural_network import MLPClassifier from sklearn.cross_validation import train_test_split from sklearn import svm import string targetNums = list(range(1,27)) * 1000 letter2NumMap = dict(zip(string.ascii_lowercase,targetNums)) num2LetterMap = dict(zip(targetNums,str...
"""Forecast Controller Module""" __docformat__ = "numpy" # pylint: disable=C0302,too-many-branches,too-many-arguments,R0904,R0902,W0707 # flake8: noqa # IMPORT STANDARD import argparse import logging from typing import Any, Dict, List, Optional # IMPORT THIRDPARTY import pandas as pd import psutil try: import d...
import sys import json import time import Game import pprint def makeData(fname): """ Input should be a json file """ with open(fname, 'r') as jFile: data = json.load(jFile) roles = [] players = {} strategies = {} for item in data['roles']: roles.append(item['name']) players[item['name']] = item['cou...
import pickle import statistics import math import routine_mlm as helper import os import sys, getopt #get seed arg from command line here seed = helper.command_line_seed(sys.argv[1:]) result_objs = [] for i in range(5): with open(f"out/out_mlm_results/results_{seed}_{i}.pkl", "rb") as file: resu...
import argparse import csv import os import pymongo import sys def feature_id_extract(feature): feature_parts = feature.split(":") source = feature_parts[1].lower() if "chr" in feature_parts[3]: start = feature_parts[4] end = feature_parts[5] if not start: ...
# Generated by Django 2.1.4 on 2019-01-31 08:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='bar', fields=[ ...
# Stanley H.I. Lio # hlio@hawaii.edu # All Rights Reserved. 2018 # University of Hawaii import re, logging logger = logging.getLogger(__name__) def parse_4319a(line): msgfield = ['SN', 'Conductivity', 'Temperature', 'Salinity', 'Density', 'Soundspeed'] convf = [int, float, float, float, float, float] co...
# send.py from kombu import Connection from kombu.messaging import Producer from entity import task_exchange from kombu.transport.base import Message connection = Connection('amqp://guest:guest@10.120.120.11:5672//') channel = connection.channel() message=Message(channel,body='Hello Kombu') # produce producer = Pro...
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey from .. import diffie_hellman_ratchet __all__ = [ # pylint: disable=unused-variable "DiffieHellmanRatchet" ] class DiffieHellmanRatchet(diffie_hellman_ratchet...
import pandas as pd from constants.dataset import TARGETVAR from sklearn.decomposition import PCA import seaborn as sns import matplotlib.pyplot as plt def pca_plot_train_test(train: pd.DataFrame, test: pd.DataFrame, **lmplot_args): assert len(train.columns) == len(test.columns) train_test = pd.concat([train,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/8 11:36 # @Author : liuhuiling import requests r = requests.get("https://api.github.com/user",auth = ("user","pass")) print(r.status_code) print(r.headers['content-type']) print(r.encoding) print(r.text)
print("""\ Program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,...,n. Created By Keyvin Duque <thkeyduq@gmail.com> """) n = int(input('Ingrese un numero: ')) choice = input('Desea usted realizar la suma o la multiplicacion de sus el...
import memory import numpy as np import torch from torch.autograd import Variable import lp BUFFER_SIZE = 100 MAX_CARS = 3 MAX_REQUEST = 3 class Env(): def __init__(self, locations, actor): self.locations = locations self.grid_size = (locations, locations) self.buffer = memory.Replay(b...
from flask import Blueprint, g, redirect, url_for, render_template, session from backend.models import User user_bp = Blueprint("user", __name__, url_prefix="/user") @user_bp.before_request def check_login(): user = session.get("userId") if user: user = User.query.filter_by(account=user).fi...
import sys from PIL import Image def encode(visible_image,hidden_image,output_file): # create an output image of the same size as the visible image output_image = Image.new('RGB',(visible_image.width,visible_image.height)) # this array will store the rgb values of the encoded file pixels = [] w = hidden_image.wi...
import torch def mre(pred, gt): ''' gt : ground truth depth pred: predicted depth shape: (N, H, W) ''' N = pred.shape[0] loss = 0 for i in range(N): loss += torch.sum(torch.div(torch.abs(gt[i] - pred[i]), torch.sum(gt[i]))) return loss /...
from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect, HttpResponse from .models import Product, Order, Locality, Client, Backup_copy, User from .forms import FormProduct, FormOrder, FormUser, FormClient, FormBackup_copy, FormLocality def logout(request): r...
# -------------abstract base class------------------------ from abc import ABC, abstractmethod class A(ABC): # This is abstract base class @abstractmethod def imp_fun(self): # this is abstract method return 0 class B(A): # this class is inheriting A so it should override abs_method ...
# 修改,添加和删除元素 motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) # ['honda', 'yamaha', 'suzuki', 'ducati'] too_expensive = 'ducati' motorcycles.remove(too_expensive) print(motorcycles) # ['honda', 'yamaha', 'suzuki'] print("\nA " + too_expensive.title() + " is too expensive for me.") # A Ducati i...
from sklearn import metrics import matplotlib.pyplot as plt import numpy as np import ipywidgets from sklearn.metrics import roc_curve, auc, roc_auc_score from sklearn.metrics import confusion_matrix, precision_score, recall_score import pandas as pd # This is a function which prints selected metrics for a pre...
from allennlp.predictors import SentenceTaggerPredictor, SimpleSeq2SeqPredictor from languages_predictors import universal_eng_pos_predictor key_to_predictors = { 'debug': SentenceTaggerPredictor, 'ud-eng': universal_eng_pos_predictor.UniversalEngPosPredictor, 'nc_zhen': SimpleSeq2SeqPredictor } predict_logits...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class ZhimaCustomerBehaviorSyncResponse(AlipayResponse): def __init__(self): super(ZhimaCustomerBehaviorSyncResponse, self).__init__() self._contract_no = None self...
__author__ = 'smileya' import requests import urllib import HTMLParser import cgi from xml.etree import ElementTree from xml.etree.ElementTree import Element from xml.etree.ElementTree import SubElement def fetch_translation(english_text): # key=trnsl.1.1.20150911T175348Z.9da4e8f8a4e6a6b4.c6451ebd664034a0ae11e170a...
import argparse import datetime import boto3 from botocore.stub import Stubber import unittest from unittest import mock from aws_dms_task_status_exporter.aws import get_status_replication_tasks class TestAwsModule(unittest.TestCase): _mocked_conf_file = { "region": "us-east-1", "replication-task-...
''' for 문 돌면서 X찾고 주면에 .이 3개 이상이면 후보에 추가 후보들을 돌면서 .으로 바꿔줌. ''' R, C = map(int, input().split()) Map = [] for _ in range(R): Map.append(list(input())) dx = [0, 0, 1, -1] dy = [-1, 1, 0, 0] cd = [] for i in range(R): for j in range(C): if Map[i][j] == 'X': cnt = 0 for k in range...
__author__ = 'Alexey Bright' from parsing.iced_token import IcedToken from pyced.locator import Locator class LocatorToken(IcedToken): """ Represents a locator token """ def __init__(self, number): self.__locants = [number] #TODO replace create methods by recursive constructor # -------...
from __future__ import annotations # Really? from typing import Dict, List, Optional from interface import Action, Assignment1Domain, State class Policy: ''' This class implements a policy, i.e., a mapping from states to actions. Given a policy pol, the value of state s can be accessed and modified vi...
from bs4 import BeautifulSoup import math import json #from dynaconf import settings as Config from spider.config.settings import Config from spider.tools.logtools import Logger from spider.tools.commontools import getUUID, Timer from spider.tools.webtools import myGetRequest from spider.tools.mqtools import rabbitmqCo...
""" Solution for 7. Reverse Integer https://leetcode.com/problems/reverse-integer/ """ class Solution: """ Runtime: 40 ms, faster than 99.91% of Python3 online submissions for Reverse Integer. Memory Usage: 13.2 MB, less than 5.71% of Python3 online submissions for Reverse Integer. """ def reverse(...
from __future__ import print_function import os from setuptools import setup, find_packages import punctuator CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) try: with open(os.path.join(CURRENT_DIR, 'README.md'), encoding='utf-8') as f: long_description = f.read() except TypeError: with ope...
import os from unittest.mock import MagicMock import pytest os.environ["LOG_LEVEL"] = "DEBUG" @pytest.fixture(scope='function') def mocked_shows_db(): import shows_db shows_db.table = MagicMock() shows_db.client = MagicMock() return shows_db @pytest.fixture(scope='function') def mocked_episodes_d...
# This code is mostly based on Matthieu Courbariaux's # Binary Neural Network code, accessable from: # https://github.com/MatthieuCourbariaux/BinaryNet # Jintao has modify the code so it is able to implemented on-chip. from __future__ import print_function import sys import os import time import numpy as np np.rand...
import pytest from project.servers.database import curd, db_models from project.servers.database.database import SessionLocal, engine db_models.Base.metadata.create_all(bind=engine) def get_db(): db = SessionLocal() try: yield db finally: db.close() def test_user(): with SessionLoc...
import time from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.webdriver.common.by import By from utils import get_element, input_text, execute_swipe, element_is_exsit, get_toast des_cap = { "platformName" : "android" , #表示的是android 或者ios "platformVersion" : "5...
def test_provisionPackage(): from data_provisioning.src.core.core import processRequest resources = setup() parameters = {} parameters['msisdn'] = '254734091540' parameters['transactionId'] = '11' parameters['packageId'] = '12' resources['parameters'] = parameters resources = processRequ...
from PyQt5.QtWidgets import QDockWidget, QLabel, QListWidget, QListWidgetItem, QWidget from PyQt5.QtCore import pyqtSignal, pyqtSlot from widgets import DownloadProgress class ProgressDock(QDockWidget): """ Progress dock widget which holds a list of progress items """ _placeholder = 'No download in pr...
from notifier.provider import Provider class PrintNotify(Provider): def notify(self): if self.subject is not None: print('[{}]'.format(self.subject), end='') print() print() print(self.text, end='')
class ArticleDBRouter(object): def db_for_read(self, model, **hints): if getattr(model, 'is_articleDB', False): return 'articledb' else: return None def db_for_write(self, model, **hints): if getattr(model, 'is_articleDB', False): return 'articledb' ...
n = int(input()) while n>1: print(n, end = ' ') if n%2: n*=3 n+=1 else: n//=2 print(n)
# # @lc app=leetcode id=207 lang=python3 # # [207] Course Schedule # # @lc code=start class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = [[] for _ in range(numCourses)] visit = [0 for _ in range(numCourses)] #1 visisted, -1 visiting ...
import json import os from datahub.ingestion.source.usage.bigquery_usage import BigQueryUsageConfig def test_bigquery_uri_with_credential(): expected_credential_json = { "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "auth_uri": "https://accounts.google.com/o/oauth2...
from eclcli.common import command from eclcli.common import utils from ..networkclient.common import utils as to_obj class ListPort(command.Lister): def get_parser(self, prog_name): parser = super(ListPort, self).get_parser(prog_name) return parser def take_action(self, parsed_args): ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^register$', views.register), url(r'^register_form$', views.register_form), url(r'^login$', views.login), url(r'^logout$', views.logout), url(r'^logged$', views.logged), url(r'^create_course...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 13 13:27:31 2018 @author: olli """ ika = int(input('Kuinka vanha olet? ')) if ika >= 0 and ika <= 120: print('OK') else: print('Mahdotonta!')
#------------------------------------------------------------------------------- # Name: 126 # Purpose: # # Author: uwi http://wonderfl.net/c/cC40 # from time import clock def solve(M): ct = [0]*(M // 2) dsup = int(((M - 1) / 2)**.5) for d in range(dsup+1): p = 2 * d * ...
class Solution: def reverse(self, x: int) -> int: new=str(x) if x<0: new[0]=="-" new=new.replace("-",'') new="-"+new[::-1] a=int(new) if a >= -2147483648 and a<= 2147483647: return a else: ...
import pandas as pd import matplotlib.pyplot as plt import pytemperature #import wget #wget.download("https://raw.githubusercontent.com/pesikj/python-012021/master/zadani/5/temperature.csv") teploty = pd.read_csv("temperature.csv", index_col="Day") teploty = teploty.rename(columns={"Unnamed: 0": "id", "AvgTemperature"...
from numpy import * matriz = array([ [0,0,0,0,0], [0,0,1,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0] ]) coordenadas={ "x" : [], "y" : [] } area_mapa = len(matriz)-1 def GameOfLife(numero): """Funcion que Recibe un numero y modifica la matriz cada turno Arguments: numero int...
year = int(input("Enter Year :")) if (year%400==0): print("Leap Year") elif (year%100==0): print("not Leap Year") elif (year%4 ==0): print("Leap Year") else: print("Not Leap Year")
"""To use this script, install the provided requirements.txt file and supply a secrets.py file with the required parameters listed below. JSON records will be written into the specified file and HTML reports will be written into an outputs filter under the provided directory. """ from datetime import datetime, timed...
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 16:07:46 2020 @author: tjcombs https://projecteuler.net/problem=119 """ import pandas as pd import numpy as np def sum_up_digits(ser): sum_digits = 0 while((ser > 0).any()): digit = ser % 10 sum_digits = sum_digits + digit ser = ...
if __name__ == "__main__": pandigital = [] for p in range(1,10**6): digits = list(str(p)) i = 2 while len(digits) < 10: if '0' in digits: break if len(digits) == 9 and len(digits) == len(set(digits)): pandigital.append(int(''.join(d...
from tkinter import * import os framevar = '' id_meta = 0 id_parcela = 0 def nova_meta(): def salvar_entradas(): global id_meta try: with open('metas.txt', 'r') as arquivo_meta: linhas = arquivo_meta.readlines() ids_meta = len(linhas) ...
# Uses Euclidean Algorithm to calculated the GCD of 2 numbers def gcd(x, y): a = max(x,y) b = min(x,y) rem = a % b if rem == 0: return b else: gcd(b, rem)
# -*- coding: utf-8 -*- import string import random import datetime import requests def random_string(size=32): chars = string.ascii_uppercase + string.digits return ''.join(random.choice(chars) for __ in range(size)) def localized_date(datetime): year = datetime.year month = datetime.month day ...
import pandas as pd import numpy as np import sys from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.linear_model import SGDRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn.gaussian_process import GaussianPro...
import pymongo from datetime import datetime import json import time myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["youtube"] mycol = mydb["videos"] mylist = [] with open('a.json') as f: json_from_file = json.load(f) cnt = 1 data_cnt = 0 s = time.time() for i in json_from_file['v...
# Generated by Django 3.0.5 on 2020-04-12 13:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='user_form', fields=[ ('id', models.AutoFiel...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012 Leopold Schabel # This file is part of MetaWatch Simulator. # # This software is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, eith...
import time import h5py import tensorflow as tf from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import Conv2D from tensorflow.keras.models import Model try: from tqdm import tqdm except ImportError: tqdm = lambda x, **kwargs: x from tf_fastmri_data.datasets.cartesian import Car...
#!/usr/bin/env python from rpc_client import TestingRpcClient from os import listdir test_rpc = TestingRpcClient() def compile_verilog_test(): response = test_rpc.call('compile_verilog.compile_to_vvp("batee5.v", "batee5_tb.v")') print response assert eval(response) == []
#----------------------------------------------------------------------------- # This file is part of 'SLAC Firmware Standard Library'. # It is subject to the license terms in the LICENSE.txt file found in the # top-level directory of this distribution and at: # https://confluence.slac.stanford.edu/display/ppareg/LI...
#!usr/bin/python # -*- coding: utf-8 -*- from collections import defaultdict class DirectedGraph: """ DirectedGraph class: Define a Directed Graph, containing a list with all unique node in the graph and all Node (object). Argument: --------- - node_id (str): id of the first (top) node """...
import os from pymongo import MongoClient MONGO_DATABASE_URL: str = os.getenv("MONGO_DATABASE_URL") mongoclient = MongoClient( MONGO_DATABASE_URL, uuidRepresentation='standard' )
a={"message": [ { 'id':1, 'Rfid':'asdasdas', 'name':'ming', 'state':'1', 'time':'time' }, { 'id':2, 'Rfid': 'asdasdas', 'name':'wang', 'state':'1', 'time':'time' } ]} print(type(a))
import sqlite3 import wptools def conv(num): try: if num[1]=="trillion": return float(num[0])*1000000000000 elif num[1]=="billon": return float(num[0])*1000000000 elif num[1]=="million": return float(num[0])*1000000 elif num[1]=="thousand": return float(num[0])*1000 ...
import openpyxl for i in range(1, 13): filePath = f"2019年{i}月销售订单.xlsx" wb = openpyxl.load_workbook(filePath, data_only=True) orderSheet = wb["销售订单数据"] for rowData in orderSheet.rows: productName = rowData[2].value if productName == "商品名": continue rowValue = [] ...