text
stringlengths
38
1.54M
import pandas as pd import datetime import seaborn as sns import matplotlib.pyplot as plt from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup ...
#------------------------------------randomgrass.py------------------------------ # # Based on the Pixar course on Khan academy # # Using the basics of parabola construction N blades of grass are # initialised with random positions and sway with a random frequency and # phase # # Tkinter...
# Run with: # rllib train file cartpole_a2c.py \ # --stop={'timesteps_total': 50000, 'episode_reward_mean': 200}" from ray.rllib.algorithms.a2c import A2CConfig config = ( A2CConfig() .environment("CartPole-v1") .training(lr=0.001, train_batch_size=20) .framework("tf") .rollouts(num_rollout_wo...
import xml.parsers.expat, os configs = {} def getConfValue(confName, variable): global configs try: info = os.stat(confName) except OSError as e: raise AssertionError('Missing Config file: %s' % (e,)) modTime = info.st_mtime config = None if confName in configs: config = configs[confName] if config and ...
import random import math import copy import matplotlib.pyplot as plt import xlrd import time import numpy as np #---------------------------- workbook=xlrd.open_workbook("TSP38.xlsx") #文件路径 worksheet=workbook.sheet_by_index(0) city_position=np.zeros((worksheet.nrows,2)) #city= np.chararray(14) city=list() for i ...
import os from wtforms import * from flask import Flask, request, render_template, session, redirect, url_for, flash from flask_bootstrap import Bootstrap from flask_moment import Moment from datetime import datetime from flask_wtf import FlaskForm from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail, Me...
from django.db.models import CASCADE, CharField, ForeignKey, DecimalField, BooleanField, TextField from django.db.models import Model from .owners import Owner from .people import People from decimal import Decimal from django.core.validators import MinValueValidator STATUS = ( ('sold', 'SOLD'), ('unsold', 'UN...
from assignment1.cs231n.classifiers.k_nearest_neighbor.script import * from assignment1.cs231n.classifiers.linear_classifier import *
from ctypes import * from list import GF_List class GF_HEVCParamArray(Structure): _fields_=[ ("type", c_char), ("array_completeness", c_char), ("nalus", POINTER(GF_List)) ]
def look_and_say(s): result = '' digit = s[0] count = 0 for c in s: if c == digit: count += 1 else: result += str(count) + digit digit = c count = 1 result += str(count) + digit return result result = '3113322113' # input from adv...
#!/usr/bin/env python from math import sqrt import os, time import optparse from xml.etree import ElementTree from ROOT import * hpath="passed_boosted_ejets_1fj0b/cutflow_mc_pu_zvtx" #################################################### def ReadFromFile(histoname1): thisname = histoname1[:-1] print('fi...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @time : 18-10-9 下午8:53 # @author : Feng_Hui # @email : capricorn1203@126.com # The value of d_proxy will be changed when you update the original dict(d). # the value of d_pxoxy is dynamic from types import MappingProxyType d = {1: 'A'} d_proxy = MappingProxyType(d) print...
import unittest import model.units.api as uapi from model.board_state import BoardState from model.resources import ResType class TestUnits(unittest.TestCase): def setUp(self) -> None: self.board = BoardState(['Aaron', 'Sandra', 'Ezra', 'Dave', 'Jeff']) self.aaron = self.board.players[0] s...
#!/usr/bin/python import subprocess import numpy as np import micro_module from micro_module import * def make_stars(): #arguments to subprocess must be strings; they are converted to doubles in the c program #compile simu.c script from Sebastiano (makefile must be in the same folder as simu.c) subprocess.call('mak...
from . import modules from ..FLAGS import PARAM def get_model_class_and_var(): model_class, g, d = { 'DISCRIMINATOR_AD_MODEL': (modules.Module, modules.Generator, modules.Discriminator), }[PARAM.model_name] return model_class, g, d
import tkinter root = None canvas = None cell_side = 25 background_color = '#f7f2ff' lines_color = '#c4bfcc' draw_color = '#3d0084' field1_left_x = cell_side * 10 field2_left_x = 22 * cell_side field1_left_y = field2_left_y = cell_side * 2 def change_rectangle_color(tag, color): elem = canvas.find_withtag(tag)[...
#!/usr/bin/env python import time from ur_driver.io_interface import * if __name__ == "__main__": print "testing io-interface" get_states() print "listener has been activated" set_states() print "service-server has been started" #~ i=0 #~ while(i<10): #~ set_tool_voltage(12) ...
import urllib.request, urllib.error, urllib.parse import json url = input("Enter - ") fhandle = urllib.request.urlopen(url).read() data = json.loads(fhandle) #load the json data into python data lst = list() comments = data["comments"] #retrieve the 'comments' in the json data for item in comments: count = item[...
import binascii from decimal import Decimal from typing import Optional, Union from .. import xdr as stellar_xdr from ..muxed_account import MuxedAccount from ..type_checked import type_checked from ..utils import raise_if_not_valid_amount, raise_if_not_valid_hash from .operation import Operation __all__ = ["Liquidit...
""" Задание 5: Реализовать структуру «Рейтинг», представляющую собой набор натуральных чисел, который не возрастает. У пользователя нужно запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них. Подсказка. Наприм...
#!/bin/env python import os def GetResource(): res = os.path.abspath('./res/otdn.txt') with open(res, 'rb') as f: content = f.readlines() return content[0].strip() def GetLargest(listofints): s = 0 for i in listofints: if i > s: s = i return s def GetProduct(seq...
while True: option = input("Type scale name.\nmajor,minor,etc. or q(quit):\n\n") if option == 'major': print("2,2,1,2,2,2,1\n") elif option == 'minor': print("2,1,2,2,1,2,2\n") elif option == 'harmonic minor': print("2,1,2,2,1,3,1\n") elif option == 'q': exit() el...
import pandas as pd import numpy as np import re import spacy nlp = spacy.load('en_core_web_md') scripts_df = pd.read_csv('Data/Raw/simpsons_script_lines.csv', dtype = 'unicode') episods_df = pd.read_csv('Data/Raw/simpsons_episodes.csv', dtype = 'unicode') scripts_df.head() # episods_df episods_df.drop(columns = ...
#!/usr/bin/python # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def removeNthFromEnd(self, head, n): ans = ListNode(0) ans.next = head node = ans #两个指针,一个记录走的过程,...
from unittest.mock import patch, MagicMock import pytest import os import json from typing import Dict, List, Tuple, Optional import sqlparse from sqlparse.tokens import Keyword, DML, Whitespace, Newline, Punctuation from sql_translate import utils PATH_SAMPLES = os.path.join(os.path.dirname(__file__), "samples") d...
from flask import render_template, Flask,request from flask_mail import Mail, Message app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'amanikashema000@gmail.com' app.config['MAIL_PASSWORD'] = "Amani@1998" app.config['MAIL_USE_TLS'] = False ...
def multiplication(one, two): """Returns one * two Options: one and two """ return int(one) * int(two)
''' Given a BST and a number X. The task is to check if any pair exists in BST or not whose sum is equal to X. Example 1: Input: 8 / \ 5 9 / \ 1 3 X = 4 Output: 1 Explanation: For the given input, there exist a pair whose sum is, i.e, (3,1). https://www.youtube.com/watch?v=ouuGHu9Sjhg Meth...
""" Django settings for itmemory project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) i...
import json import requests import time as tt from tkinter import * from tkinter import ttk api_url = "https://inshortsv2.vercel.app/news?type=" def check_api(): response = requests.get((api_url + "trending")) return response.status_code def request_data(): response = requests.get(api_ur...
# -*- coding: utf-8 -*- import logging from pathlib import Path import ruamel.yaml from cg.apps import hk, gt, tb from cg.store import models, Store LOG = logging.getLogger(__name__) class UploadGenotypesAPI(object): def __init__(self, status_api: Store, hk_api: hk.HousekeeperAPI, tb_api: tb.TrailblazerAPI, ...
import tkinter from tkinter import* x=tkinter.Tk() x.geometry("300x300") label=Label(x,text="This is Times Now",font="Times",fg="red") label.pack() label1=Label(x,text="This is Helvetica",font="Helvetica",fg="white",bg="green") label1.pack(fill=X) label2=Label(x,text="This is Verdana Bold",font=("Verdana",13,"bold"),fg...
# coding: utf-8 import sys from django.utils.translation import ugettext as _, ugettext_lazy from django.core.urlresolvers import reverse from modoboa.lib import events, parameters from modoboa.core.extensions import ModoExtension, exts_pool class Webmail(ModoExtension): name = "webmail" label = "Webmail" ...
## Reference: https://stackoverflow.com/questions/39219705/how-to-download-images-using-google-earth-engines-python-api ## Reference: https://developers.google.com/earth-engine/exporting import ee ee.Initialize() landsat = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_123032_20140515') c1 = [84.28586591, 27.42846051] c2 ...
from django.db import models class City(models.Model): city = models.CharField(max_length=140) def __str__(self): return u'%s' % (self.city) class Country(models.Model): country = models.CharField(max_length=140) def __str__(self): return u'%s' % (self.country) class Course(models...
from django.shortcuts import render from django.shortcuts import HttpResponse def index(request): return HttpResponse('我是app01的index页面...')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: yyg @Create: 2016MMDD @LastUpdate: 2016-12-15 HH:MM:SS @Version: 0.0 # """ import inspect from logging import getLogger from multiprocessing import (Manager, Pool, TimeoutError, cpu_count, ...
import numpy as np import particlesim import hardboundary def newDirection(angle, rng): theta = angle + np.random.uniform(rng[0], rng[1]) x = np.sin(theta) y = np.cos(theta) return np.array((x,y)) def calculateNoise(m, s, gamma, t, n): T = 2 * m * pow(s, 2) / np.pi var = 2 * gamma * T * t cov = [[var, 0], [0,...
print('Loading libraries') from sklearn.feature_extraction import text import pandas as pd dfs = [] stop = text.ENGLISH_STOP_WORDS def remove_stopwords(st): return ' '.join([x.lower().strip('.?!()" ,;-_”') for x in st.split() if x.lower() not in stop]) for i in range(3): print('Reading file', i+1) df = p...
from brian2 import * from brian2.utils.logger import catch_logs from numpy.testing import assert_raises, assert_equal, assert_array_equal from nose import with_setup from nose.plugins.attrib import attr @attr('codegen-independent') @with_setup(teardown=restore_initial_state) def test_clock_attributes(): clock = C...
#!/usr/bin/env python # kc_query.py - module for sopel to query knifecenter.com for pricing data # # Copyright (c) 2016 Casey Bartlett <caseytb@bu.edu> # # See LICENSE for terms of usage, modification and redistribution. from sopel import * from ddg import ddg from extract_blade_info import query_kc_knife, query_bhq_...
class Rational: def __init__(self, numer, denom): self.numer = None self.denom = None def __eq__(self, other): return self.numer == other.numer and self.denom == other.denom def __repr__(self): return f'{self.numer}/{self.denom}' def __add__(self, other): pass ...
r""" --- Day 7: Recursive Circus --- Wandering further through the circuits of the computer, you come upon a tower of programs that have gotten themselves into a bit of trouble. A recursive algorithm has gotten out of hand, and now they're balanced precariously in a large tower. One program at the bottom supports the...
def restaurant(l, b): global gcd n=min([l,b]) for i in range(n,0,-1): if l%i==0 and b%i==0: gcd=i break print(int((l*b)/(gcd**2))) t = int(input()) for t_itr in range(t): lb = input().split() l = int(lb[0]) b = int(lb[1]) result = restaurant(l, b)
for x in range(20): if x**2 > 280: print("Znalazłam element: ", x) break print("Pierwsza instrukcja po pętli.")
import hashlib def md5hash (*args): s = ",".join(args) return(hashlib.md5(s.encode('utf-8')).hexdigest())
def is_prime(x): if x >= 0 and x < 2: return False elif x == 2 or x == 3: return True for num in range(2,(x-1)): if x % num == 0: #num += 1 print("False") return False num += 1 #elif x % num != 0: # num += 1 ...
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Co-Author Network fro...
import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication from view.MainView import MainView if __name__ == "__main__": app = QApplication(sys.argv) app.setAttribute(Qt.AA_EnableHighDpiScaling,True) form = MainView() form.show() sys.exit(app.exec_())
# coding: utf-8 import sys import csv def read_csv(): return csv.reader(sys.stdin) def add_id(items, id_fieldname): items = iter(items) def header(): header = items.next() return [id_fieldname] + header yield header() for id, item in enumerate(items, 1): yield [id] +...
class1, class2, class3 = 32, 45, 51 def grouped(students1, students2, students3): each_group1 = students1 // 5 each_group2 = students2 // 7 each_group3 = students3 // 6 each_group = [each_group1, each_group2, each_group3] leftover1 = students1 % 5 leftover2 = students2 % 7 leftover3 = stude...
def createfibonacci(first,second,no_of_terms): list=[first,second] for k in range (no_of_terms-2): next=first+second first=second second=next list.append(second) return tuple(list) no=int(input('no. of terms to be founded in Fibonacci Series')) first=int(input('fir...
# coding=utf-8 for i in range(4): print("this is the first level, i: %s" % i) for j in range(2): if i > 1: print("i > 1, break, i: %s" % i) print("i: %s, j: %s" % (i, j))
T = int(input()) def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller elemen...
from flask_sqlalchemy import SQLAlchemy from modelserializer import ModelSerializer db = SQLAlchemy() class NEO(db.Model, ModelSerializer): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), unique=True, nullable=False) nasa_jpl_url = db.Column(db.String(4096), unique=True, nu...
import os import time import shlex import argparse import subprocess class Parser(argparse.ArgumentParser): def __int__(self): super(Parser, self).__init__() @staticmethod def optparse(): parser = argparse.ArgumentParser() parser.add_argument( "-a", "--all", action="s...
from google.appengine.api.users import User from google.appengine.ext import db class UserData(db.Model): email = db.EmailProperty(required = True) secret = db.StringProperty( required = True) class Image(db.Model): hash = db.StringProperty() tags = db.StringListProperty() clas...
import pandas as pd import os #recibe un directorio #retorna todos los documentos de ese directorio def getDocsinDir(directory): return list(map(lambda x: directory+x,os.listdir(directory))) #recibe una lista de nombres de documentos #retorna un lista de dataFrames def getCSVs(docs): data=[] for x in docs:...
#!/usr/bin/env # Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/ # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in ...
from django.db import models # Estos modelos sirven para relacionar los datos en la base de datos class Todo(models.Model): # Se crean los modelos y patrones para los datos de los que constara cada To Do todo_title = models.CharField(max_length=30) todo_text = models.CharField(max_length=200) todo_date...
%pyspark from pyspark.sql import SparkSession from pyspark.sql.functions import (col, concat, count, countDistinct, current_timestamp, date_format, desc, floor, lag, lit, monotonically_increasing_id, sum, udf, unix_...
#!/usr/bin/env python # VERSON 1.5 from sys import flags from typing import Text import telebot import requests from bs4 import BeautifulSoup import re from telebot import types import time # Версия 1.5 #+ Написан парсер м/с #+ Регулярными выражениями удалены лишнии символы #+ Добавлены переносы строк #+ Сделан вывод в...
from peewee import * from chalicelib import config database = MySQLDatabase(config.DB_NAME, host=config.DB_HOST, port=3306, user=config.DB_USERNAME, passwd=config.DB_PASSWORD) class UnknownField(object): def __init__(self, *_, **__): pass class BaseModel(Model...
# Day 3 - Challenge 5 # 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 firstname = name1.lower() secondname = name2.lower() tcount = firstna...
from __future__ import division import math import numpy as np import sys import time import matplotlib.pyplot as plt one_class = int(sys.argv[1]) alpha = 0.0001 EPSILON = 10**-10 lmbda = 1 # # theta = np.random.rand(d) # # labels = np.array([0,0,1,1]) X = None; labels = None def initialize(perc): global X, lab...
 # these fuctions are loaded automatically and are available # from the python automation tool or python table buttons # if running from a table button, the argument will be the # current element in the current table as a ModelArrayElement
from django.db import models from django.conf import settings from django.utils.translation import ugettext as _ from .settings import wishlist_settings from .managers import UserManager AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') class WishlistItem(models.Model): """ Item in wishlist....
import heapq def solution(scoville, K): answer = 0 heapq.heapify(scoville) while len(scoville) > 0: low_food = heapq.heappop(scoville) if low_food >= K: return answer # if ~ else 말고 try ~ except로 예외처리 try: second_food = heapq.heappop...
from builtins import str from builtins import object import uuid from zope.interface import providedBy from zope.interface import alsoProvides from zope.interface import noLongerProvides from w20e.hitman.views.base import ContentView as Base from w20e.hitman.views.base import DelView as DelBase from w20e.hitman.views....
# -*- coding: utf-8 -*- """Agent Search Viewlet""" #zope imports from Acquisition import aq_inner from plone.app.layout.viewlets.common import ViewletBase from Products.CMFCore.utils import getToolByName from zope.interface import Interface, alsoProvides, noLongerProvides #local imports from customer.krainrealestate...
import networkx as nx with open("input_6-1.txt") as file: data = file.readlines() graph = nx.Graph(x.strip().split(")") for x in data) print(sum(nx.shortest_path_length(graph, x, "COM") for x in graph.nodes)) print(nx.shortest_path_length(graph, "YOU", "SAN") - 2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 12 18:32:39 2020 @author: pmchozas """ import requests import json import re def enrich_term_thesoz(myterm): get_uri(myterm) get_definition(myterm) get_relations(myterm) get_synonyms(myterm) get_translations(myterm) create_i...
from django.db import models from datetime import datetime, date, time class StatManager(models.Manager): def today(self): today_min = datetime.combine(date.today(), time.min) today_max = datetime.combine(date.today(), time.max) return self.filter(created__range=(today_min, today_max)) c...
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN(nn.Module): def __init__(self, embed_size: int): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): param.requires_grad_(False) ...
# # -*- coding: utf-8 -*- # # Copyright (c) 2017 Vantiv eCommerce # # # # Permission is hereby granted, free of charge, to any person # # obtaining a copy of this software and associated documentation # # files (the 'Software'), to deal in the Software without # # restriction, including without limitation the rights to...
import os from django.contrib.auth.models import User def populate(): add_user('abc1234', 'CG9hFLBa', email='abc1234@gmail.com', website='abc1234.com') # Print out what we have added to the user. for u in User.objects.all(): print("{}".format(str(u))) def add_user(username, password, email,...
#!/usr/bin/env python import sys zip_code = sys.argv[1] url = "http://forecast.weather.gov/MapClick.php?lat=%s&lon=%s&FcstType=dwml" lat = "" lon = "" import MySQLdb con = MySQLdb.connect(host="localhost", user="root", passwd="HXtmmPyuWI1l6pDE3l6V", db="Home_db") cur = con.cursor() try: cur.execute("SELECT latit...
#!/usr/bin/env python2 from num2verilog import nums2verilog1d as n2v import numpy as np from weights2bytes import np2hex destfile = 'cifarbytes' datadir = '/home/ricson/data/cifar_data/out/' testdata = np.load(datadir+'traindata.npy') testlabels = np.load(datadir+'trainlabels.npy') N = 10 S = [] for i in range(N):...
import torch import torch.nn as nn class Discriminator_Loss(): @staticmethod def get_D_loss(input_result, is_real): batch_size = input_result.shape[0] if is_real: return nn.BCELoss()(input_result, torch.zeros(batch_size, 1).cuda()) else: return nn.B...
import FWCore.ParameterSet.Config as cms pfAllMuons = cms.EDFilter("PFCandidateFwdPtrCollectionPdgIdFilter", src = cms.InputTag("pfNoPileUp"), pdgId = cms.vint32( -13, 13), makeClones = cms.bool(True) ) pfAllMuonsClones = cms.EDProducer("PFCandidateProductFromFwdPtrProducer", ...
# Borrowed from pset7 import csv import os import urllib.request import requests, json from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker #from time import strftime, localtime from flask import redirect, render_template, request, session from functools import wraps # Set up d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2019 Yann J.K. BERTRAND: yjk_bertrand@ybertrand.org # All rights reserved. # # Class IntervalST that create a interval search tree used to find the limits of # an alignment __version__ = "1.3" # ===============================================...
# Tui Popenoe # Challenge63E.py - Reverse(N, A) """ Take an input list A and reverse the first N indices of the array in place """ import ast import sys def reverse_na(n, a): rev = a[:n] end = a[n:] output = rev[::-1] + end return output def main(): if len(sys.argv) == 3: print(reverse...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- DB_HOST = 'localhost' DB_PORT = 3306 DB_USER = 'root' DB_PASSWORD = '' DB_DATABASE = 'diamond' DB_CHARSET = 'utf8' # 钻石接口 URL BASE_API_URL = 'http://www.zbird.com/apidiamond/ajaxdiamondNative/' # 单页显示条数 PAGE_SIZE = '20' # 全球搜索 GLOBAL_SEARCH = '2' # 国内搜索 DOMESTIC_SEARCH = ...
from flask import Blueprint, render_template, request, redirect, abort import json from flask_login import login_required from rvd.forms.Source import SourceForm from flask_admin import helpers from collections import defaultdict from rvd.models import session, Source from rvd.forms import organisation_factory from cop...
from PySide.QtGui import * from QIPythonWidget import QIPythonWidget class Main(QWidget): def __init__(self, parent=None): super(Main, self).__init__(parent) layout = QVBoxLayout(self) self.button = QPushButton('Another widget') # Just like any other widget self.iPython ...
from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse, HttpResponse from django.views.generic.base import TemplateView, View from django.views.generic import ListView, DetailView from .models import Category, Element, Food, ElementAddress, Food # -------------------- Functional ...
#hw4.py, author: Matthew Siebert import numpy as np import density_model as dm import shoot_routines as sr #Running this script answers all problems in the 4th problem set T6_1 = 10. T6_2 = 15. T6_3 = 25. T7_1 = T6_1/10. T7_2 = T6_2/10. T7_3 = T6_3/10. def W(Zj, Zk, Aj, Ak): return Zj*Zj*Zk*Zk*(Aj*Ak/(Aj +Ak)) def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 17 23:38:22 2021 @author: khazi """ import nltk def Gebaude_NonGebaude_Split(df): gebaude_rows = [] non_gebaude_rows = [] GebaudeNames = ['Gebäude', 'Geb', 'Geb.', 'Bau', 'BAU'] gebäudeDict = {} sentArray = [] xtense ...
import psycopg2 as db from abc import ABC, abstractmethod class Postgres(ABC): def __init__(self): self.table = "" self.cursor = None self.connection = None super(Postgres, self).__init__() def connect(self): try: user, password, host, port, database = self...
from flask import Flask,redirect,render_template,url_for app = Flask(__name__) @app.route('/') def index(): render_template('home.html') for _ in range(100000000): continue return redirect(url_for('another_page')) @app.route("/another_page") def another_page(): return '<h1> Hello th...
import methods.binance as binance import io def print_menu(): print("\n****************************") print("* Menu: *") print("* *") print("* 1. Retrieve Balance *") print("* 2. Sell All Coins *") print("* 3. Buyback All Coins *") ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields from odoo.tests.common import Form from odoo.addons.stock_account.tests.test_stockvaluationlayer import TestStockValuationCommon class TestSaleStockMargin(TestStockValuationCommon): @class...
from numpy import select class optical_flow_ROI: cv2 = __import__("cv2") np = __import__("numpy") tracking_area = (100,100) # Quantidade de pixeis rastreados ao redor do pixel central max_level = 2 # Nível de pirâmide usado epsilon = 0.05 # Valores menores d...
from numpy import* ma = array(eval(input("Media do Aluno: "))) p = array(eval(input("Precenca em Horas: "))) ch = int(input("Carga Horaria: ")) lol = zeros(3,dtype=int) for i in range(size(ma)): dd = (75 / 100) * ch if ma[i] >= 5 and p[i] >= dd: lol[0]= lol[0] + 1 elif ma[i] < 5: lol[1]= lol[1] + 1 else: ...
l = ["Zimmer", "Newman", "Kilar", "Newman", "", "", "Sherlock", "Sherlock"] # l = ['', ""] cos = {} selected = [0, "whoever"] for x in l: if x == "": continue if x not in cos: cos[x] = 0 cos[x] += 1 if selected[0] < cos[x]: selected = [cos[x], x] elif selected[0] == cos[x]:...
import click @click.command("sample") @click.argument("name") @click.option("--times", default=1, type=click.INT) # @pass_context is optional def cli(name, times): for _ in range(times): print("Hello " + name)
""" Client wrapper for Google App Engine NDB https://cloud.google.com/appengine/docs/standard/python/ndb/ """ from vishnu.backend.client import Base from google.appengine.ext import ndb class VishnuSession(ndb.Model): # pylint: disable=R0903, W0232 """NDB model for storing session""" expires = ndb.DateTimeP...
#-*-coding:utf-8-*- from TestModel.models import ProductCurrentState,ManageRequest,SwitchJoinDevice,ProductBelongTo,Product#,ProductDescription def Product_isExist_inNum2(First_type,Second_type,Product_num): try: if len(ProductCurrentState.objects.filter(first_type=First_type,second_type=Second_type,prod...
# -*- coding: utf-8 -*- import copy dict ={"a":"apple","o":"orange"} dict2 ={"b":"banana","p":"pear"} #copy.deepcopy等价于dict.deepcopy dict2 = copy.deepcopy(dict) #copy.copy 等价于dict.copy dict3 = copy.copy(dict) dict2["a"]="watermelon" dict3["a"]="juice" print dict,dict2,dict3