text
stringlengths
38
1.54M
from tkinter import * from math import * class InvestmentCalc: def __init__(self): window = Tk() window.title("Investment Calculator") frame0 = Frame(window) frame0.pack() Label(frame0, text = "Investment Amount:").grid(row = 1, column = 1, sticky = W) self.v1 = St...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
#pragma out #pragma repy try: try: raise Exception, "Exiting" finally: print "Hi" # should be printed except Exception: pass
import enum from abc import ABC, abstractmethod from model.list_pkg.entry import Entry from model.observer_pkg.observer import Observer import pymongo from pymongo import MongoClient import urllib.parse class Account(Entry, ABC): class Role(enum.Enum): AUTHOR = "Author" PCM = "PCM" PCC = ...
import re from django import forms from django.contrib.sites.models import Site from subdomains.conf import settings as subdomain_settings from subdomains.models import Subdomain class SubdomainForm(forms.ModelForm): class Meta: model = Subdomain exclude = ('site', 'user',) def cle...
import FileManager as fm; import csv import os.path import time import argparse import glob out_file ="places.txt" in_folder="places" search_pattern='/*/*INCPLACE.txt' skip_first=True# skip the first line of subsequent files directory = os.path.dirname(os.path.realpath(__file__))+"/" # files from https://www.cen...
# -*- coding:utf-8 -*- import xlwt import os """ 将数据写入excel的脚本,简单版 """ class ExcelWriteHelper: @staticmethod def write(title,data,excel_name,save_path=os.getcwd()): """ :param title: sheet中的标题 :param data: 标题对应的内容数据 :param excel_name: excel的文件名 :param save_path: exce...
import math from collections import defaultdict, namedtuple DiscreteParameters = namedtuple( 'DiscreteParameters', ['S0', 'u_n', 'd_n', 'q_n', 'R_n', 'n']) def convert_to_discrete(T, S0, r, sigma, c, n): R_n = math.exp(r * T / n) u_n = math.exp(sigma * math.sqrt(T / n)) d_n = 1 / u_n q_n = (mat...
import numpy as np import math pi = np.pi def getLogLikelihood_k(means, weights, covariances, X, K): # Log Likelihood estimation # # INPUT: # means : Mean for each Gaussian KxD # weights : Weight vector 1xK for K Gaussians # covariances : Covariance matrices for each gaussian...
import os import boto3 import datetime from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText from email import encoders from email.mime.base import MIMEBase from . import LOGGER class Mail(object): def __init__( self, s...
def f(n, m, k, p_arr, s_arr, c_arr): i_p_s_c_arr = [] for i in range(n): i_p_s_c_arr.append((i + 1, p_arr[i], s_arr[i], (i + 1) in c_arr)) i_p_s_c_arr.sort(key=lambda x: (x[2], -x[1])) count = 0 for i in range(1, n): if i_p_s_c_arr[i][3] and i_p_s_c_arr[i][2] == i_p_s_c_arr[i - 1]...
from django.contrib.auth import logout, login from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import render, redirect, get_object_or_404 from .forms import UserForm, PostForm from .models import Post # Create your views here. def signup(request): if request.method =='POST': ...
import sys sys.path.insert(0, '/var/www/html/saferouteapp') from saferouteapp_backend import app as application
"""Alibaba cloud OSS.""" from contextlib import contextmanager as _contextmanager import re as _re import oss2 as _oss # type: ignore from oss2.models import PartInfo as _PartInfo # type: ignore from oss2.exceptions import OssError as _OssError # type: ignore from airfs._core.io_base import memoizedmethod as _memo...
from django.contrib import admin from .models import * class AlunoAdmin(admin.ModelAdmin): empty_value_display = 'Nenhum' list_display = ('nome','ra','cod_energia','escola') search_fields = (['nome','ra','cod_energia', 'escola']) class AgenciaTransporteAdmin(admin.ModelAdmin): empty_value_display = 'N...
#!/usr/bin/python import os virtenv = os.environ['APPDIR'] + '/virtenv/' os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages') virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: execfile(virtualenv, dict(__file__=virtualenv)) except: pass # new codes we adding fo...
#!usr/bin/python score_C=int(input("请输入语文成绩:")) score_M=int(input("请输入数学成绩:")) score_E=int(input("请输入英语成绩:")) if score_C>score_M: if score_M>score_E: print(score_C) print(score_E) else: if score_C>score_E: print(score_C) print(score_M) else: pr...
# Generated by Django 3.1.4 on 2021-01-08 08:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myapi', '0003_auto_20210108_1359'), ] operations = [ migrations.DeleteModel( name='Category', ), ]
from django.db.models import Q, Count from utils.file.export_task import ExportExcelTask from reman.models import Batch, Repair, EcuRefBase REMAN_DICT = { 'batch': [ ('Numero de lot', 'batch_number'), ('Quantite', 'quantity'), ('Ref_REMAN', 'ecu_ref_base__reman_reference'), ('Client', 'customer'),...
from django import forms from src.bo.Enum import TimePeriod, Index, TransactionType, PositionType from src.bo.static.Calendar import Calendar import models from models import Portfolio, TCBond, Identifier, Equity, ModelPosition, TCSwap from models import InterestRateCurve, Location, UserProfile, Transaction, Batch...
#NATURAL SELECTION # # # sim15d_mono_1of2.py # # # Script to simulate a population with n subpops of i individuals, with population rebound, # natural selection and sampling. Selection occuring at different periods. Equal events spacing # 2 Initial subpopns, expanding to 6 # output as genotypes for Powermarker # ...
# -*- coding: utf-8 -*- # # Auxiliary functions for querying things/people # __all__ = [] def user_yesno(msg, default=None): """ Docstring """ # Parse optional `default` answer valid = {"yes": True, "y": True, "ye":True, "no":False, "n":False} if default is None: suffix = " [y/n] " ...
# Generated by Django 3.0.5 on 2020-06-01 08:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('holvi_orders', '0002_auto_20200331_1347'), ('fvh_courier', '0034_delete_userlocation'), ] operations = [ ...
import dash # from settings import PATH # # external css # icons = 'https://fonts.googleapis.com/icon?family=Material+Icons' # external_stylesheets = [icons, {"href": icons, "rel": "stylesheet"}] # external_scripts = [ # {"src": "https://code.jquery.com/jquery-3.4.1.min.js", # "integrity": "sha256-CSXorXvZc...
''' 파이썬의 조건문 쉬운 내용이라 대부분 스킵했음. if / elif / else 중요한건 elif는 if의 조건문에 해당 안되면서, elif의 조건문을 만족할 때 분기가 걸림. pass 키워드 아무것도 처리하고 싶지 않을 때 (디버깅 할 때 사용) 한줄일 경우에는 간략하게 표현 가능. if score >= 80: result = "Success" else: result = "Fail" if ~ else를 한줄에 작성 가능. score = 85 result = "Success" if score >= 80 else "Fail" 파이썬은 수학의 부등식을 그...
from flask import session from models.ACC_USER import AccUser from utils.db_connection import DbSession from utils.errors.parameter_errors import BadRequest def login(username, password): with DbSession() as db_session: register_user = db_session.query(AccUser).filter(AccUser.username==username).first() ...
from django.shortcuts import render,redirect from django.http import HttpResponse from CrimeReportingSystem.forms import UserRegistrationForm,MyProfileForm,ChangepassForm,ComplaintForm from CrimeReportingSystem.models import MyProfile # Create your views here. def home(request): return render(request,'html/home.html'...
__author__ = "jz-rolling" import numpy as np import tifffile import nd2reader as nd2 from .helper_image import * import pickle as pk from .segmentation import * from .optimize import * from .particle import Particle Version = '0.2.2' class Patch: def __init__(self): # make sure that the number of imag...
# Python Standard Library Imports # Third Party / PIP Imports # HTK Imports from htk.lib.yahoo.groups.message import YahooGroupsMessage def yahoo_groups_message_parser(message_html): """Extracts the main message from a Yahoo Groups message """ yahoo_groups_message = YahooGroupsMessage(message_html) ...
#!/usr/bin/env python from robolink import * # API to communicate with robodk from robodk import * # robodk robotics toolbox import sys from io import StringIO import sys #import StringIO import contextlib @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: ...
class MemoryAllocation(object): _store_name = "address" def __init__(self): self._address_map = {} def __setattr__(self, attr, value): if attr == '_address_map': return super(MemoryAllocation, self).__setattr__(attr, value) self._address_map[attr] = value def __getattr__(self, att): ...
import socket import feiQ_data import send_online_msg def deal_msg(recv_data_): """处理消息数据""" _recv_data = recv_data_.decode("gbk", errors = "ignore") message_list = _recv_data.split(":", 5) #用字典保存数据信息 msg_dict = dict() msg_dict["version"] = message_list[0] msg_dict["packet_numb"] = message...
from abc import ABC, abstractmethod class Trainer(ABC): def __init__(self, iteratinos, batch_size, num_workers, learning_rate, optimizer, split, dataloader, loss_function): ''' args: iterations: number of iterations for training batch_size: number of batch size num_workers: number of works to load dat...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: if root1 is None or root2 is None: return root2 is Non...
from bs4 import BeautifulSoup from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager import requests import pandas as pd def scrape(): executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable_path, headless=False) # Cre...
from django.contrib import admin from .models import Button from .models import Slider admin.site.register(Button) admin.site.register(Slider) # Register your models here.
from urllib.parse import quote import json def URLEncodeQuery(**kwargs): """Encodes kwarg values to URL-friendly strings Ex. query="Redmi Phone" => {'query': 'Redmi%20Phone'} Returns: dict: object containing kwargs and URL-encoded kwarg values """ for kwarg in kwargs: kwargs[kwarg]...
max_tentativas = 6 tentativas = 0 oculta = "teste" digitadas = "" acertou_tudo = False while (tentativas < max_tentativas) and not acertou_tudo: letra = raw_input("Digite uma letra: ") digitadas = digitadas + letra if letra in oculta: #acertou a letra digitada print "A palavra é: ", ...
import os import pathlib from flightsparser.cache import LocalCache, RedisCache class TestLocalCache: def test_get_cache_elements_empty(self): cache = LocalCache() cache.cache_path = f"{pathlib.Path(__file__).parent.absolute()}/local_cache.pkl" cache.remove_cache() elements = cach...
#!/usr/bin/env python # -*- coding: utf-8 -*- # !/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 # Подключаемся к базе данных con = sqlite3.connect('dbase1') curs = con.cursor() # Создаем таблицу curs.execute( ''' create table diafilms(name text, path text, type text, )''')
1# -*- coding: utf-8 -*- """ Created on Tue Jun 8 03:54:05 2021 @author: sarangbhagwat """ import thermosteam as tmo import biosteam as bst from biosteam.process_tools import SystemFactory from biorefineries.BDO import units, facilities from biorefineries.BDO.process_settings import price import numpy as np __all__ ...
#--================================================ # Loops #--================================================ #--------------------------------------- # Definite Loop for i in [5, 4, 3, 2, 1]: print(i) print('Blastoff!') # A Definite Loop with Strings friends = ['Joseph', 'Glenn', 'Sally'] for friend in frie...
from nltk import NaiveBayesClassifier from nltk.tokenize import word_tokenize from itertools import chain from textblob.classifiers import NaiveBayesClassifier from text import training_data from textblob import TextBlob import sys import pickle test = [ ('the beer was good.', 'pos'), ('I do not enjoy my jo...
import pytest from takler.core import NodeStatus from takler.core.expression_parser import parse_trigger from takler.core.expression_ast import ( AstOpEq, AstOpGt, AstOpGe, AstOpOr, AstOpAnd, AstNodePath, AstVariablePath, AstNodeStatus, AstInteger ) def test_node_path(): expr_cases = [ "/flo...
import json from pony.orm import * from email.utils import parseaddr from datetime import datetime import re from app.db import Institution, InstitutionType, Phone, InstitutionPhone, UserInstitution from app.address_controller import Address import app.user_controller class CRUDInstitution(): phone_pattern = No...
import torch import torch.nn as nn import utils.batch_norm import utils.whitening def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def conv1x1(in_planes, out_planes, stride=1): "...
"""A basic police lights effect.""" import time from logipy import logi_led logi_led.logi_led_init() time.sleep(2) while True: logi_led.logi_led_set_lighting(100, 0, 0) time.sleep(0.1) logi_led.logi_led_set_lighting(0, 0, 0) time.sleep(0.1) logi_led.logi_led_set_lighting(100, 0, 0) time.sleep(...
import pandas import matplotlib.pyplot as plt import numpy as np import time import seaborn as sns sns.set() # df = pandas.read_csv("results/latin_cube_integration_results.csv", header=0) df = pandas.read_csv("lc_2000.csv") print(df.head()) df.columns = ["iterations", "samples", "area", "computationtime"] print(df.des...
import numpy as np class MaxPoolLayer(object): def __init__(self, size=2): """ MaxPool layer Ok to assume non-overlapping regions """ self.locs = None # to store max locations self.size = size # size of the pooling def forward(self, x): """ Co...
# Equal weight portfolio in case no clear over/under wight asset allocation signal exists def equal_weight(marked_portfolio): target_value = marked_portfolio # Calculate the total value of holdings by portfolio target_value['PortfolioValue'] = target_value['Value'].groupby(target_value['Portfolio']).transf...
class Solution: def firstUniqChar(self, s: str) -> int: unique_letters = sorted(set(s), key=s.index) for letter in unique_letters: if s.count(letter) == 1: return s.index(letter) return -1
#! /usr/bin/python import sys, math import pdb_lib ### # This programs was writen by Trent E. Balius, the Shoichet Group, UCSF, 2017 # It counts how meny waters are nearby a extreme point ### #def cal_dists(atom1,atom2): # d2 = (atom1.X - atom2.X)**2 + (atom1.Y - atom2.Y)**2 + (atom1.Z - atom2.Z)**2 # return ...
# Copyright 2021 # # 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 agreed to in writing, software # distr...
import subprocess from . import constants from . import exceptions def send_command(command): """ Function to send the IR command through LIRC. Make sure that LIRC is properly configured or this could raise exceptions. :param command: string representing the raw IR command to send :return: nothin...
''' calcula as raízes de uma equação do 2o grau: ax² + bx + c=0 Para ela existir, o coeficiente 'a' deve ser diferente de zero. No caso de a ser igual a zero, envie uma mensagem de erro ao usuário. Caso o delta seja maior ou igual a zero, as raízes serão reais. Caso o delta seja negativo, exiba a mensagem: As raízes sã...
from utility import * from scipy.stats import poisson from sklearn.manifold import MDS import numpy as np from scipy.stats import multivariate_normal from numpy import argmax,log from random import randint,uniform,shuffle import math import scipy as sc def update_frag_topic(ecount_matrix,components,frag_group,frag_t...
# Generated by Django 3.0.5 on 2020-04-29 11:30 from django.db import migrations, models import django.utils.timezone import sorl.thumbnail.fields import tinymce.models class Migration(migrations.Migration): dependencies = [ ('mysite', '0005_portfolio_url'), ] operations = [ migrations....
"""Module to hold the ServicesInvoice resource.""" from fintoc.mixins import ResourceMixin class ServicesInvoice(ResourceMixin): """Represents a Fintoc Services Invoice."""
from typing import List from sklearn.svm import LinearSVC from arg.counter_arg.runner_qck.qck_datagen import load_qk from arg.qck.decl import QKUnit, KDP from cache import load_from_pickle def main(): split = "training" qk_list: List[QKUnit] = load_qk(split) svclassifier: LinearSVC = load_from_pickle("s...
''' Created on Jul 3, 2018 @author: Pravesh ''' from config import Session from tables import Issue session=Session() result=session.query(Issue).filter(Issue.id=="1").first() print(result)
import configuration import inference_utils import inference_wrapper def main(_): # Build the inference graph. g = tf.Graph() with g.as_default(): model = inference_wrapper.InferenceWrapper() restore_fn = model.build_graph_from_config(configuration.ModelConfig(), ...
''' 已知文本文件,以 \n 为行结束符, 每行包含两个字符串 key和value, 中间用 \t 分割,key和value均有可能重复出现, 输入文件内容格式举例: 2687694 18070300 2687694 18070300 2687694 18070500 2687694 18070500 2687697 15050000 2687697 15050000 2687697 15050500 2687697 15050500 请写程序统计下列信息: 1) 每个key对应多少不同的唯一value? 2) 每个不同的value出现次数是多少? 并按value次数从大到小输出结果文件 (key1:valu...
from flask import Flask,request,jsonify,Response from flask_pymongo import PyMongo,ObjectId from flask_cors import CORS app = Flask(__name__) CORS(app) app.config["MONGO_URI"] = "mongodb://localhost:27017/flask" mongo = PyMongo(app) db= mongo.db.users @app.route('/users', methods=['POST']) def create(): ...
from sklearn import tree features = [[140,1], [130,1], [150,0], [170,0]] #apple = 0 #orange = 1 labels = [0,0,1,1] clf = tree.DecisionTreeClassifier() clf = clf.fit(features,labels) print(clf.predict([[120,1]]))
#! /usr/bin/env python # -*- coding: utf-8 -*- """A lightweight Application framwork. """ from __future__ import ( division, print_function, absolute_import, unicode_literals) # Standard libraries. import argparse # ID: $Id$" __date__ = "$Date$"[6:-1] __scm_version__ = "$Revision$"[10:-1] __author__ = "`Berthold...
# -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”), # 您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时...
from django.shortcuts import render from django.http import JsonResponse from rest_framework import permissions, status from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.views import APIView from rest_f...
import PIL import cv2 import requests import zbarlight video_capture = cv2.VideoCapture(1) call_set = set() def get_webcam_image(): # Capture frame-by-frame ret, frame = video_capture.read() cv2.imshow("Webcam", frame) # Convert the CV frame to PIL image return PIL.Image.fromarray(frame) def de...
import time from math import * from sys import * from groups import * # also checks default value def check_initial_conditions(argv): if len(argv) < 2: print "Usage: python blur.py <input file> [neighbor reach]" exit() elif len(argv) == 2: return 4 else: return argv[2] def in_file(argv): try: f = open(ar...
# -*- coding: utf-8 -*- import utool as ut ut.noinject(__name__, '[wbia.gui.__init__]', DEBUG=False)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 5 20:42:24 2019 @author: nico """ import os import numpy as np from scipy import signal as sig import matplotlib.pyplot as plt from scipy.fftpack import fft import scipy.io as sio from time import time import pandas as pd os.system ("clear") # li...
from flask import Flask,g from proxy_pool.db import Reidis_client __all__=['app'] app = Flask(__name__) def get_conn(): if not hasattr(g,'redis_client'): g.redis_client = Reidis_client() return g.redis_client @app.route('/') def index(): return '<h1>欢迎进入代理池系统!</h1>' @app.route('/get') def get(): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 15:09:11 2020 @author: ns2dumon """ import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import os import re Directory=os.getcwd() + '/storage' dirnames = [name for name in os.listdir(Directory) if os.pat...
# Generated by Django 2.1.3 on 2020-07-03 11:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='companyCompare', fields=[ ...
import asyncio from logging import getLogger from typing import List, TYPE_CHECKING from pymongo.errors import DuplicateKeyError from sqlalchemy import update, delete from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncEngine from virtool_core.models.group import GroupMinimal, Group from...
from collections import defaultdict import pprint from nltk import word_tokenize import simple def get_words(text): words = word_tokenize(text) clean_words = simple.clean_words(words) return words, clean_words def get_byte_ngram(text, n=2, cs=False): if not cs: text = text.lower() ngrams...
N = 4 arr = [1,2,3,-2,5] first = arr[0] f = first for i in range(1,len(arr)): sec = f+ arr[i] first = max(first, sec) f = sec print(first)
sizes = [5, 7, 300, 90, 24, 50, 75] print("Hello, I'm Thanh and here are my sheep's sizes: ") print(sizes) print("Now my biggest sheep has size", max(sizes), "let's shear it!") index = sizes.index(max(sizes)) sizes[index] = 8 print('After shearing, here is my flock:') print(sizes) month = int(input('Number of months:...
import os import logging import shutil from openpyxl import Workbook def clear_summary_path(path_to_summary): """ Removes the summaries if it exists """ if os.path.exists(path_to_summary): logging.info("Summaries Exists. Deleting the summaries at %s" % path_to_summary) shutil.rmtree(path_to_sum...
# -*- coding: utf-8 -*- """ Created on Wed Nov 11 19:57:41 2015 @author: Feng-cong Li """ import os import sys from os.path import abspath, dirname, join import inspect import subprocess import tempfile from tkinter.filedialog import askopenfilename, asksaveasfilename from tkinter import Tk from wavesynlib.languagece...
# Load the AlchemyAPI module code. import AlchemyAPI # Create an AlchemyAPI object. alchemyObj = AlchemyAPI.AlchemyAPI() # Load the API key from disk. alchemyObj.loadAPIKey("api_key.txt") # Extract a ranked list of named entities from a text string, using the supplied parameters object. result = alchemyObj.TextG...
import re from pprint import pformat import requests from swiggy_order.constants import ( SWIGGY_URL, CSRF_PATTERN, SWIGGY_COOKIE, SWIGGY_SEND_OTP_URL, SWIGGY_VERIFY_OTP_URL, STATUS_FLAG, STATUS_MESSAGE, CART_URL, APPLY_COUPON_URL, PLACE_ORDER_URL, ) from swiggy_order.utils imp...
# -*- coding: utf-8 -*- def human_readable_int_to_machine(size): """ translates human readable integer format to integer @param str Number that may optionally end with K, M, or G at the end, to ease writting powers of ten @return int """ multiplier = 1 size = size.upper() ...
import random LETTER_POOL = { 'A': 9, 'B': 2, 'C': 2, 'D': 4, 'E': 12, 'F': 2, 'G': 3, 'H': 2, 'I': 9, 'J': 1, 'K': 1, 'L': 4, 'M': 2, 'N': 6, 'O': 8, 'P': 2, 'Q': 1, 'R': 6, 'S': 4, 'T': 6, 'U': 4, 'V': 2, ...
import requests import pymorphy2 from tkinter import * from googletrans import Translator morph = pymorphy2.MorphAnalyzer() root = Tk() def kelvin_to_celsius(temp): return round(temp - 273.15, 2) def eng_to_rus(city): translator = Translator(service_urls=['translate.googleapis.com']) result = transla...
class GameCharacter: def __init__(self,name,hp,power): self.name = name self.hp = hp self.power = power def is_alive(self): return self.hp > 0 def get_attacked(self,damage): # 게임케릭터가 살아있으면 파라미터로받은 다른 케릭의 체력을 자신의 공격력만큼 깍음 if self.is_alive(): ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return 1 left=self.isBalanced(root.left) i...
from sage.all import RealIntervalField, ComplexIntervalField, prod, vector, matrix, arccosh, Infinity from snappy.verify.upper_halfspace.finite_point import FinitePoint from snappy.raytracing.hyperboloid_utilities import complex_and_height_to_R13_time_vector, PSL2C_to_O13 class PrecisionExperiment: def __init__(s...
# -*- coding: utf-8 -*- from openerp import models, fields, api class Ddi(models.Model): '''Ddi''' _name = "pbx.ddi" _description = "DDI" _rec_name = 'number' def _search_inuse(self, operator, value): ids = set() if operator == '=' and value == True: sel...
from django.shortcuts import render from playsound import playsound from text_to_speech.TextToSpeech import TextToSpeech from duddy import forms from duddy import models # Create your views here. def index(request): context = {} # playsound('sounds/SampleAudio.mp3') app = TextToSpeech() app.get_token(...
import unittest from OdioPares import respuesta_pares class PruebaOdioPares(unittest.TestCase): def prueba(self, fun_solucion): dict_pruebas = { 1:('101001','10'), 2: ('1', '1'), 3: ('0', '0'), 4: ('', 'Helado es el vacio'), 5: ('11', 'Helado es el vacio'), 6: ('0...
from sqlalchemy import (Table, Column, Integer, String, create_engine, MetaData, ForeignKey) from sqlalchemy.orm import mapper, create_session from sqlalchemy.ext.declarative import declarative_base e = create_engine('sqlite:///sqlite.db', echo=True) Base = declarative_base(bind=e) class Employee(Base): __tab...
import unittest from Learning.TokenParser import * class TokenParserTests(unittest.TestCase): def setUp(self): self.tokenizer = TokenParser() def parse(self, token): return self.tokenizer.parse(token) def test_number_recognition(self): self.assertEqual(self.tokenizer.NUMBER_TAG,...
class Node: def __init__(self,data=None,next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert_at_beginning(self,data): node = Node(data,self.head) self.head = node def print(self): if...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import time #-------------------------------------------------------------------------------------- #_1.Data object 생성하기 #pd.Series s = pd.Series([1, 3, 5, np.nan, 6, 8]) #date_range를 통해 날짜 기간 배열 생성 dates = pd.date_range('20130101', periods =6) ...
import py from hippy.phpcompiler import compile_php, PHPLexerWrapper from hippy.objspace import ObjSpace from testing.directrunner import run_php_source, DirectInterpreter from testing.test_interpreter import BaseTestInterpreter, MockInterpreter class LiteralInterpreter(MockInterpreter): def run_source(self, sour...
# Artificial Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyp...
def Sum(lst): sum_negative=0 sum_even_positive=0 sum_odd_positive=0 for i in lst: if i <0: sum_negative+=i elif i>0 and i%2 == 0: sum_even_positive+=i elif i>0 and i%2 != 0: sum_odd_positive+=i print('Sum of Negative = {}\nSum of Positive E...
import tkinter import serial import msvcrt from tkinter import * class Application(tkinter.Frame): """ GUI """ def __init__(self, master): """ Initialize the Frame""" tkinter.Frame.__init__(self, master) self.grid() self.create_widgets() self.updater() ...
from .SwtAdapter import SwtAdapter from .VdfAdapter import VdfAdapter from .VscAdapter import VscAdapter