text
stringlengths
38
1.54M
#!/usr/bin/env python import unittest import nagios from component_health import parse_response class TestParseResponse(unittest.TestCase): def runTest(self): self.assertEqual( parse_response("{\"status\": \"ok\", \"summary\": \"Test Summary\", \"details\": []}"), (nagios.OK, ...
from unittest import TestCase from eemeter.uploader import api import pandas as pd from datetime import datetime import pytz class APITestCase(TestCase): def setUp(self): self.minimal_project_df = self._minimal_project_df_fixture() self.minimal_consumption_df = self._minimal_consumption_df_fixtu...
class FuelConsumption: def __init__(self, konnection): self.lf_stream = konnection.conn.add_stream(konnection.vessel.resources.amount, 'LiquidFuel') self.ox_stream = konnection.conn.add_stream(konnection.vessel.resources.amount, 'Oxidizer') self.met_stream = konnection.met_stream sel...
# -*- coding: utf-8 -*- """WebSocket Address ======================= The :mod:`darc.sites.ws` module is customised to handle WebSocket addresses. """ import darc.typing as typing from darc.error import LinkNoReturn from darc.link import Link from darc.proxy.ws import save_ws from darc.sites._abc import BaseSite cl...
# -*- coding: utf-8 -*- """ Created on Mon Mar 19 13:36:31 2018 @author: Han """ import pandas as pd import numpy as np import os '''return model''' def CorrelationTest(factordataset,factorlist,stock,time,M): if type(factordataset) == str: df = pd.read_csv(factordataset,parse_dates=[str(time)]) del...
import io import math import time import sys import random import signal import subprocess import pprint import socket import threading import os from errno import ESRCH from os import kill, path, unlink, path, listdir, remove from rpc_commands_lib import Commands_Rpc from time import sleep from uuid import uuid4 ME...
from pathlib import * from filetools import * def getTumorType(projectPath): return projectPath.strip("/").split("/")[-4] def getLabName(projectPath): return projectPath.strip("/").split("/")[-2] def getInstitutionName(projectPath): return projectPath.strip("/").split("/")[-3] def getProjectNumber(projectPath): ...
from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm from django.contrib.auth import authenticate, login from django.contrib.auth import get_user_model import views from django.http import HttpResponseRedirect def gotobooks(request): return H...
""" Alexander Eriksson Windows 10 """ def Palindrom(User_Input): not_valid = "!\"#€%&/()=? :,'" # En sträng med ogiltiga tecken som skall tas bort User_Input = User_Input.lower() #Gör om samtliga karaktärer till små bokstäver i=0 #Ger "i" värdet 0 while i < len( not_valid ): #O...
import os from cryptography.fernet import Fernet import clipboard import random import getpass import string import hashlib appdata = os.environ.get('AppData') pw_path = appdata + '/pwmanager/pw.txt' key_path = appdata + '/pwmanager/key.key' master_path = appdata + '/pwmanager/master.file' counter = 0 counter2 = 0 ...
import importlib.util blender_loader = importlib.util.find_spec('bpy') # Include the bl_info at the top level always bl_info = { "name": "Yakuza GMD File Import/Export", "author": "Samuel Stark (TheTurboTurnip)", "version": (0, 2, 2), "blender": (2, 80, 0), "location": "File > Import-Export", "...
import numpy as np R = 10 EXP = 6 N = 10**EXP np.random.seed(1) pt_x = np.random.uniform(-R, R, N) pt_y = np.random.uniform(-R, R, N) pts = zip(pt_x, pt_y) ctr = 0 for i, pt in enumerate(pts): dist = np.linalg.norm(pt) if dist<=R: ctr+=1 PI = 4*ctr/(i+1) if i%(N//100)==0: print(PI) p...
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""), ...
from ScenarioHelper import * def main(): CreateScenaFile( "m9082.bin", # FileName "m9082", # MapName "m9082", # Location 0x00C3, # MapIndex "ed7356", 0x00000000, # Flags ...
selling_price=float(input("Enter thr selling price:")) cost_price=float(input("Enter thr cost price:")) if(selling_price>cost_price): print("profit") else: print("loss")
#!/usr/bin/env python3 from flask import Blueprint, render_template trymez = Blueprint('trymez', __name__, url_prefix='/try') @trymez.route('/', methods=['GET']) def show_try(): return render_template('trymez.html')
from django.db import models import datetime from django.utils import timezone from decimal import Decimal from allauth.socialaccount.models import SocialAccount from django.contrib.auth.models import User import hashlib DAYS_OF_WEEK = ( (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'),...
# -*- coding: utf-8 -*- import inject import logging import psycopg2 import sys import crypt if __name__ == '__main__': if len(sys.argv) < 5: sys.exit(1) host = sys.argv[1] port = sys.argv[2] user = sys.argv[3] dbpassword = sys.argv[4] db = sys.argv[5] con = psycopg2.connect(host=...
from pigtest import PigTestCase, main class TestExcite(PigTestCase): PigScript = 'top_density_songs' def generateRecord(self, fields): return ( fields.get('track_id'), fields.get('analysis_sample_rate'), fields.get('artist_7digitalid'), fields.get('artist_familiarity'), ...
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: d = {} for i in items1: d[i[0]] = i[1] for i in items2: if i[0] in d: d[i[0]] += i[1] else: d[i[0]] = i[1] ...
a, b, c = input().split() if(int(a) %2 == 0 and int(b) %2 == 0 and int(c) %2 == 0): print("NO") elif(int(a) %2 != 0 and int(b) %2 != 0 and int(c) %2 != 0): print("NO") elif(int(a) %2 == 0 and int(b) %2 != 0 and int(c) %2 != 0): print("YES") elif(int(a) %2 == 0 and int(b) %2 == 0 and int(c) %2 != 0): pri...
from queue import Queue def bfs(RG,src,sink): parent = {v:None for v in RG} dist = {v:None for v in RG} que = Queue() que.put(src) dist[src] = 0 while not que.empty(): u = que.get() if u==sink: break for v in RG[u]: if RG[u][v]==0: continue i...
# filled the empty age with median value of age data['Age'].fillna(data['Age'].median(), inplace=True) survived_sex = data[data['Survived']==1]['Sex'].value_counts() dead_sex = data[data['Survived']==0]['Sex'].value_counts() #plot the survived male , female and dead male,female df = pd.DataFrame([survived_sex,dead_...
#!/usr/bin/env python3 # Minimum missed number function def min_num(o): sort = sorted(o) # print(sorted(o)) k = 0 for i in sort: if (sort[k] in sort) and ((sort[k] + 1) in sort): k += 1 # print(sort[k], sort[k] + 1, k) # else: # print('missed number is ', min_num...
# -*- encoding: utf-8 -*- # author:virualv # date :8/27/2018 s = '特斯拉' s_to_unicode = s.decode('utf-8') unicode_to_gbk = s_to_unicode.encode('gbk') print(s_to_unicode) print(unicode_to_gbk.decode('gbk'))
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='find'), path('detail/<int:hospital_id>', views.detail, name='Hospital_detail'), ]
#!/usr/bin/env python # # Test cases for tournament.py from tournament import * def testDeleteMatches(): deleteMatches() print "1. Old matches can be deleted." def testRegister(): deleteMatches() deletePlayers() registerPlayer("Chandra Nalaar") c = 1 #countPlayers() if c != 1: ra...
#!/usr/bin/env python from functools import partial import logging import os import pickle from typing import List, Tuple import numpy as np import skimage.io as sio from divik.cluster import GAPSearch, KMeans import divik._cli._utils as scr import divik.core as u Segmentations = List[Tuple[u.IntLabels, u.Centroids...
from time import sleep import threading def scheduler(f, args, n): def worker(f, args, n): seconds = n / 1000 sleep(seconds) f(*args) t = threading.Thread(target=worker, args=(f, args, n)) t.start() return t if __name__ == "__main__": jobs = [] jobs.append(scheduler(...
import Image, ImageStat import sys import pdb import const import line_util dark_threshold = 236 light_threshold = 240 def count_lines_without_dark_pixel(im, start_x, start_y, end_x, end_y, thresh): """ Return number of lines with no dark pixel from x to x2""" dark_misses = 0 start_y, end_y = min(start_y...
from http.server import BaseHTTPRequestHandler, HTTPServer from sensors import get_all_sensor_data import json class S(BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self.do_...
#!/usr/bin/env python # Import flask and template operators from flask import Flask, render_template import flask.views # Import SQLAlchemy from flask.ext.sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from werkzeug.utils import import_string # Define the WSGI application object app = Flask(__...
import cv2 import time from deepface import DeepFace import os import numpy as np def capture_image(TIMER_READY=int(2), TIMER_COUNT=int(3)): timer_ready = TIMER_READY timer_count = TIMER_COUNT cap = cv2.VideoCapture(0) while True: prev = time.time() while timer_ready >= 0: ...
# Generated by Django 2.0.6 on 2018-07-20 19:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('team', '0001_initial'), ] operations = [ migrations.CreateModel( name='Chal...
import argparse from tools.data_io import save_object, load_object from tools.utils import get_logger, read_file_contents_list import numpy as np from scipy.stats import multivariate_normal from scipy.spatial.distance import mahalanobis import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 im...
import os def main(): cash = 5000 bank(cash) def bank(cash): print("Choose a number: ") print("1 - Withdraw") print("2 - Deposit") print("3 - Balance Inquiry") print("4 - Exit") choice = int(input("Number: ")) if (choice == 1): money = float(input("Money to withdraw: ")) cash -= money print("Money succes...
from bs4 import BeautifulSoup # 解析网页 from fake_useragent import UserAgent # 随机生成User-agent import chardet # 有时会遇到编码问题 需要检测网页编码 import re, urllib.request, socket, time, random, csv, json,requests from requests import RequestException import xlwings as xw import pandas as pd """ 网址: https://m.weibo.cn/p/searc...
import random as rnd price = [20,50,10,30,99,1,2,3] print(len(price)) for j in range(len(price)): print("iterate through the list") #loop through the list for i in range(10): print(i) print(rnd.random()) #loop 10 times for i in range(10): print(i) #loop through a list for i in range(2,10,2): ...
from info2soft import config from info2soft import https class Gauss (object): def __init__(self, auth): self.auth = auth ''' * 高斯同步规则-新建 * * @param dict $body 参数详见 API 手册 * @return list ''' def createGaussRule(self, body): url = '{0}/gauss/rule'.format(...
import json import requests requests.packages.urllib3.disable_warnings() #ISE get requires headers. AMP does not. def iseget(url, headers): try: response = requests.get(url, headers=headers, verify=False) # Consider any status other than 2xx an error if not response.status_code // 100 == 2: return "Error:...
#! /usr/bin/env python import rospy from std_msgs.msg import Header from gazebo_msgs.srv import GetModelState, GetModelStateRequest from snake_control.msg import snake_head_rel_pos import numpy as np rospy.init_node('snake_head_pos_pub') pos_pub=rospy.Publisher('/snake_head_pos', snake_head_rel_pos) rospy.wait_for_...
# -*- coding: utf-8 -*- """ Provides methods to process raw instacart data into a single datafile containing a subset of categories and products from the original file @author: Fenna ten Haaf Written for the Econometrics & Operations Research Bachelor Thesis Erasmus School of Economics """ import pand...
from neuralpy.layers import Dense from neuralpy.activation_functions import ReLU from neuralpy.loss_functions import MSELoss from neuralpy.models.model_helper import generate_layer_name, is_valid_layer def test_generate_layer_name(): assert generate_layer_name('Dense', 1) == 'dense_layer_2' assert generate_layer_nam...
import random import collections import numpy as np import pandas as pd import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import Adam from tensorflow.keras.models import Sequential from config import reward_for_eating, reward_for_dying class Agent(object): ...
from unittest.mock import patch import pytest from django.core.exceptions import ValidationError from django.test import override_settings from core.validators import dataregistry_path_validator, validate_url_or_path def test_validate_url_successful(): url = "https://www.google.com" assert validate_url_or_p...
import json import torch.optim as optim from models.train_loop import train_model from models.seq_model import SeqModel dir = "data_/" entpair2id = json.load(fp=open(dir + "entpair2id.json")) path2id = json.load(fp=open(dir + "path2id.json")) exp_dir = "experiments/" seq_model_dir = exp_dir+"seqmodel/" log = op...
import torch import torch.nn.functional as F class HingeLoss(object): def __init__(self): pass def __call__(self, logits, loss_type): assert loss_type in ['gen', 'dis_real', 'dis_fake'] if loss_type == 'gen': return -torch.mean(logits) elif loss_type == 'dis_real':...
from typing import List from off_policy_rl.config.config import Config from off_policy_rl.utils.bin import Bin from off_policy_rl.utils.types import Pose class Environment: def __init__(self, bins: List[Bin]): assert len(bins) == 2 self.bins = bins #self.current_bin = Config.current_bin ...
# -*- coding:utf-8 -*- # Author: Roc-J class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] for item in nums2: if len(nums1) == 0: return re...
import pyautogui import time pyautogui.FAILSAFE = False print("\n██╗ █████╗ ███████╗██╗ ██╗ ██╗████████╗ ██████╗ ██╗ ██╗██████╗ ███████╗\n" "██║ ██╔══██╗╚══███╔╝╚██╗ ██╔╝ ██║╚══██╔══╝ ██╔══██╗██║ ██║██╔══██╗██╔════╝\n" "██║ ███████║ ███╔╝ ╚████╔╝ ██║ ██║ ██║ ██║██║...
from app import app,db from tables import User from flask import request,abort,jsonify,url_for #to register a new user @app.route('/api/users', methods = ['POST']) def newUser(): username = request.json.get('username') password = request.json.get('password') #checking validity of entered username if us...
#!/usr/bin/python #Date: 1.23.18 import urllib2 import re import requests ## Get IP ## OPENER = urllib2.build_opener() OPENER.addheaders = [('User-agent', 'Mozilla/5.0')] MY_IP = OPENER.open('http://ipchicken.com/') MY_IP = MY_IP.read() IP = re.findall(r'[0-9]+(?:\.[0-9]+){3}', MY_IP)[0] print "IP Address: %s" % IP #...
from collections import defaultdict import re with open('/Users/joakimkoljonen/src/adventofcode/2017/22.input', 'r') as file: input = file.read() test_input = '''..# #.. ... ''' #input = test_input ROUNDS = 10000000 parsed = [line for line in input.split('\n') if line != ''] infected = set() flagged = set() weak...
# Convert all of the text columns in train to the categorical data type. # Select the Utilities column, return the categorical codes, and display the unique value counts for those codes: train['Utilities'].cat.codes.value_counts() import pandas as pd data = pd.read_csv('AmesHousing.txt', delimiter="\t") train =...
# coding: utf-8 import random from gat_games.game_engine.engine import * from gat_games.game_engine.cardgame import * # TODOs: # who wins start next round => must_start_new_cycle BUG? class TrucoPlayer(Player): def play(self, context, **kwargs): if kwargs.get('action', 'play') == 'accept_truco': ...
########################################################################### ### Chapter 17 - Projecting Major League Performance ### # Mathletics: How Gamblers, Managers, and Sports Enthusiasts # # Use Mathematics in Baseball, Basketball, and Football # ################...
import urllib2,json,codecs,string #importing necessary libraries var0="N/A" #initialise the variables with any random values var10="N/A" var12="N/A" fob=codecs.open('/Users/gudaprudhvihemanth/Desktop/ram.csv','a','utf-8') #create and open a csv file with utf-8 encoding format fob.write("E...
def is_postal_code(code): if type(code) == str: if len(code) == 7: for i in range(7): if i == 0 or i == 2 or i == 5: if not code[i].isalpha() or not code[i].isupper(): return False elif i == 1 or i == ...
from django.shortcuts import render from django.http import HttpResponse from background_task import background from django.contrib.auth.models import User from django.core.mail import send_mail from pricetracker import settings from track.models import Product from track.views import ProductCreateView @b...
#Dimensionality Reduction '''Ref: https://www.analyticsvidhya.com/blog/2018/08/dimensionality-reduction-techniques-python''' import pandas as pd import numpy as np import matplotlib.pyplot as plt train = pd.read_csv('D:\Programming Tutorials\Machine Learning\Projects\Datasets\Train_UWu5bXk.txt') #checking...
from django.urls import path from django.urls.conf import include from . import views urlpatterns = [ path('', views.index), path('new_user', views.new_user), ]
import logging import pytest from ocs_ci.framework.pytest_customization.marks import tier1, tier2 from ocs_ci.framework.testlib import MCGTest from ocs_ci.ocs import constants from ocs_ci.ocs.bucket_utils import ( compare_bucket_object_list, patch_replication_policy_to_bucket, sync_object_directory, w...
import os from flask import Flask from flask_restful import Api from flask_cors import CORS from flask_migrate import Migrate from models.db import db from models import user, item, cart, cartItem from resources import user, item, cart, cartItem app = Flask(__name__) CORS(app) api = Api(app) DATABASE_URL = os.getenv('...
class Solution(object): def partition(self, lo, hi, pivot): i0 = lo for i1 in range(lo, hi): if self.nums[i1] < pivot: self.nums[i0], self.nums[i1] = self.nums[i1], self.nums[i0] i0 += 1 return i0 def sortColors(self, nums...
# encoding: utf-8 import tool_utils import acmd.repo get_command = tool_utils.get_command get_argument = tool_utils.get_argument filter_system = tool_utils.filter_system def init_default_tools(config=None): acmd.repo.import_tools(__file__, 'acmd.tools', prefix=None, config=config)
# 'Hello world' print('Hello world \n') # '1__2__4__8__16' print(1,2,4,8,16, sep ='__' , end = '\n\n') print("#########\n#\t\t#\n#\t\t#\n#\t\t#\n#########\n\n#\t\t#\n#\t\t#\n#########\n#\t\t#\n#\t\t# \n")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 21 01:40:28 2018 @author: nick """ import shutil,os,re datePattern = re.compile(r"""^(.*?) ((0|1)?\d)- ((0|1|2|3)?\d)- ((19|20)\d\d) (.*?)$ """,re.VERBOSE) for amerFilename in os.listdir('.'): mo = datePattern.search(amerFi...
import json import requests response = requests.get( "https://www.esheba.cnsbd.com/v1/trains?journey_date=2021-02-27&from_station=DA&to_station=KFJ&class=S_CHAIR&adult=1&child=0") js = response.json() dic = json.dumps(js, indent=4) print(dic)
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from textformat import timeAndText import time, config as c # Check how to remove error messages def initalizeDriver(): timeAndText('Initalizing driver') options = webdriver.ChromeOptions() if c.optionHeadless: options....
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import copy class AbstractCodeView(QTableView): def init(self): # slot, not constructor!!! self.code_model = self.ModelClass(parent = self) self.setModel(self.code_model) # add model to set size of header self.horizontalH...
# %% import cv2 import numpy as np # %% img = cv2.imread('bookpage.jpg') retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) teval2, threshold2 = cv2.threshold(grayscaled, 12, 255, cv2.THRESH_BINARY) gaus = cv2.adaptiveThreshold( grayscaled,...
# is_male = True # is_tall = False # if is_male and is_tall: # print("you are a male") # elif is_male and not(is_tall): # print("you are not a male and you are not tall") # elif not(is_male) and is_tall: # print("blah blah") # else: # print("you are a female") def is_male(boolean): if is_male: ...
from gw_app.nas_managers.mod_mikrotik import MikrotikTransmitter from gw_app.nas_managers.core import NasNetworkError, NasFailedResult from gw_app.nas_managers.structs import SubnetQueue # Указываем какие реализации шлюзов у нас есть, это будет использоваться в # web интерфейсе NAS_TYPES = ( ('mktk', MikrotikTrans...
N = int(input()) A = list(int(x) for x in input().split()) cur = 0 s = set() s.add(0) for a in A: cur += a cur %= 360 s.add(cur) li = sorted(list(s)) li.append(360) print(max(li[i] - li[i-1] for i in range(1,len(li))))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbo...
import numpy as np from scipy.stats import multivariate_normal as mvn import matplotlib.pyplot as plt import seaborn as sns from sklearn.gaussian_process.kernels import RBF import matplotlib font = {"size": 30} matplotlib.rc("font", **font) matplotlib.rcParams["text.usetex"] = True lengthscale = 1.0 amplitude = 1.0...
def myfun(n): return lambda a:a*n mydoubler=myfun(2) print(mydoubler(11)) def myfun(n): return lambda a:a*n mydoubler=myfun(2) mytr=myfun(3) print(mydoubler(11)) print(mytr(11))
import numpy as np import torchvision.transforms as transforms import torch.utils.data as tudata from dataset.folder import ImageFolderInstance # import pdb class ToNumpy(object): def __call__(self, pic): """ Args: pic (PIL Image or numpy.ndarray): Image to be converted to numpy. R...
from django.template import Library register = Library() def admin_media_prefix(): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ try: from django.conf import settings return settings.ADMIN_MEDIA_PREFIX except ImportError: return '' admin_media_pref...
from geoserver.catalog import Catalog # Connect to Catalog, with REST URL, user and password cat = Catalog("http://tethys.icimod.org:8080/geoserver/rest/", "admin", "mapserver109#") globalsetting = Catalog("http://tethys.icimod.org:8080/geoserver/rest/settings[HTML]", "admin", "mapserver109#") # layerlist = cat.get_la...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Computes a figure showing the amount of probes Ally, RadarGun, MIDAR and TreeNET will use to # conduct alias resolution. The amounts are not necessarily the exact amount that will be used, # they are more like predicted amounts that should however be faithful to exper...
from traitlets import Bool, Float, Unicode, observe from jdaviz.core.events import AddDataMessage, RemoveDataMessage, CanvasRotationChangedMessage from jdaviz.core.registries import tray_registry from jdaviz.core.template_mixin import PluginTemplateMixin, ViewerSelectMixin from jdaviz.core.user_api import PluginU...
# -*- coding: utf-8 -*- # Generated by Django 1.11a1 on 2017-05-12 17:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.CreateModel( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # 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 ...
from tkinter import * import random from tkinter.messagebox import showinfo top = Tk() top.title("덧셈 및 뺄셈 학습") class Ed(Frame): def __init__(self, top): Frame.__init__(self, top) self.pack() self.calc = Entry(self) self.res = Entry(self) self.bt = Button(self, command=self...
from mechanics.events import Trigger from mechanics.events import DamageEvent, BuffAppliedEvent from game_objects.attributes import Bonus, Attribute from game_objects.battlefield_objects import CharAttributes as ca from mechanics.buffs import Buff def battle_rage_callback(t,e:DamageEvent): chance = t.chance ...
# calc energy of a certain configuration import numpy as np class energyCalc(): def __init__(self): self.kapa = 1.0 def createFaceList(self, vert, faces): # find all faces that contain a certain vertex faceList = [] for faceIndex in range(len(faces)): if (faces[faceIndex][0] == int(vert) or faces[faceI...
# dai = int(input("cdai:")) # rong = int(input("crong:")) # # for i in range(dai): # print(x) #can phai sua lai # # for i in range(rong): # print(x) for i in range(3): #cach 01 # print("*" * 4) #print on line for j in range(4): print("*", end="9") print()
from collections import deque def find_miner(grid): for r in range(len(grid)): for c in range(len(grid[r])): if grid[r][c] == "s": return r, c def left_coal(grid): x = 0 for r in range(len(grid)): for c in range(len(grid[r])): if grid[r][c] == "c":...
"""imports""" from django.contrib import admin from django.urls import include, path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), p...
from drink import Drink from food import Food food1 = Food('Sandwich', 5) food1.calorie_count = 330 print(food1.info()) drink1 = Drink('Coffee', 3) drink1.volume = 180 print(drink1.info())
from nvd3 import multiBarChart,multiBarHorizontalChart import json import requests import gmplot # Cumulated="https://services6.arcgis.com/bKYAIlQgwHslVRaK/arcgis/rest/services/Cumulative_Date_Grouped_ViewLayer/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json" # RdataCumulated= requests.get(Cumulated)....
# Slide 128 # Step 1: Assign a value to radius radius = 20 # Step 2: Calculate the area area = radius * radius * 3.14 # Step 3: Display the result print("The area for the circle of radius ", radius, "is", area)
from tkinter import * from tkmacosx import Button from tkinter import filedialog from tkinter import messagebox import pandas as pd import os import tkinter as tk import cmath root= Tk(className = " Receipt Scrapper") # Declared canvas canvas1 = Canvas(root , width = 300 , height = 400...
def sparse_dot_product(dict1,dict2): lista1 = list(dict1.items()) lista2 = list(dict2.items()) print(lista1) print(lista2) soma = 0 for (index1,valor1) in lista1: produto = 0 for (index2,valor2) in lista2: if index1 == index2: produto = valor1*valor2 ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # @author: Longxing Tan, tanlongxing888@163.com # @date: 2020-01 # paper: # use UniLM language model, but in time series, the feature dimension is not equally like token embedding of NLP import tensorflow as tf from ..layers.attention_layer import * class BERT(object):...
import cv2 import face_recognition import sys ''' # PIL做图比较复杂,不使用PIL库 from PIL import Image ret = Image.open('similar_two_face.jpg') print(ret) ''' ''' ret: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=440x571 at 0x7F0D5F9FD810> <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=440x571 at 0x7F0D7D201390...
from django.db import models class Articulo(models.Model): titulo = models.CharField(max_length=150) contenido = models.CharField(max_length=150) imagen = models.ImageField(upload_to = 'articulos') creted = models.DateTimeField(auto_now_add=True) updated =models.DateTimeField(auto_now_add=True) ...
import numpy as np import collections import sys import csv import keras import json from keras import initializers from keras.models import Sequential, load_model from keras.layers import Dense, Dropout, Embedding, LSTM, Bidirectional from keras.preprocessing import sequence from keras.callbacks import EarlyStopping ...
"""Module to do recommendations by user. """ import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf from pyframework.container import Container from pyframework.helpers.configuration import is_production_env from pyframework.helpers.lists import array_column from tensorflow import keras from tenso...