text
stringlengths
38
1.54M
import nacl import nacl.encoding import nacl.exceptions import nacl.signing import secrets def raw_sign(signing_key: bytes, message: bytes): sk = nacl.signing.SigningKey(seed=signing_key) sig = sk.sign(message) return sig.signature def raw_verify(verifying_key: bytes, message: bytes, signature: bytes): ...
from matplotlib import pyplot as plt # Create the plot f, axarr = plt.subplots(1) # And plot them x=[155.0624139,216.088007,216.3490667,137.6847495,185.24,171.8145028,134.8799083,87.10716925] y=["May", "Jun","July","Augest","sep","Oct","Nov","Dec"] axarr.bar(y,x) plt.xlabel('Months ') plt.ylabel('Eagle owl flig...
from . import Base from sqlalchemy import Column,String,Integer,DateTime import datetime class DsLeague(Base): __tablename__ = 'ds_league' id = Column(Integer,primary_key=True) name = Column(String(45)) name_short = Column(String(45)) url = Column(String(400)) created_time = Column(DateTime,nul...
#!/usr/bin/env python from json import loads import mechanize import cookielib from os import path from urllib import urlencode from sploitego.config import config from sploitego.maltego.utils import debug from sploitego.framework import configure from sploitego.maltego.message import EmailAddress, AffiliationFacebook...
import powertb powertb.enable() def my_func(x): y = x + 200 print(y) if x > 0: my_func(x-1) else: return 1 / x my_func(2)
from flask import Flask, jsonify, abort, request, render_template from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import asc from marshmallow import Serializer class TodoSerializer(Serializer): class Meta: fields = ('id', 'todo', 'done', 'order') def get_todos_serialized(todo): return Todo...
""" Copyright (C) 2018-2020 Intel Corporation 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 i...
from flask import Blueprint from flask import flash from flask import g from flask import redirect from flask import render_template from flask import request from flask import url_for from werkzeug.exceptions import abort from coolspace.auth import login_required from coolspace.db import get_db # The following impor...
import cv2 import numpy as np from numpy.linalg import inv class Transform: # Create the perspective mapping at init time instead of run time. def __init__(self, src, from_size=(1280, 720), to_size=(800, 600)): self.src = src # Definable sizes for the new images self.from_size = from_...
class Shape: def what_am_i(self): print("I am a shape") class Rectangle(Shape): # Inherit Shape class pass class Square(Shape): # Inherit Shape class pass rectangle = Rectangle() rectangle.what_am_i() # call the Shape class method square = Square() square.what_am_i() # call the Shape class metho...
import keras from keras.models import Sequential from keras.layers import Dense classifier = Sequential() classifier.add(Dense(output_dim = 6, init = "uniform", activation = 'relu',input_dim = 11 )) classifier.add(Dense(output_dim = 6, init = "uniform", activation = 'relu' )) classifier.add(Dense(output_dim = 1, in...
#!/usr/bin/env python # -*- coding: utf-8 -*- # django import from django import forms from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.utils.encoding import ...
from StudentRepoClass import * from StudentClass import Student from ExceptionsClass import * class StudentTextFileModificationsRepository(StudentRepo): def __init__(self, fileName, auxiliaryFileName): StudentRepo.__init__(self) self._fileName = fileName self._auxiliaryFileName = auxiliaryF...
import os import xml.etree.ElementTree as ET import sys import shutil currentDir = os.getcwd() userAppDir = sys.argv[1] # 1. Copying needed files in the right directories localMacroDir = os.path.join(currentDir,'Macros') localIconDir = os.path.join(currentDir,'icons') localFontsDir = os.path.join(curr...
#!/usr/bin/env python import rospy import tf_conversions import tf2_ros import geometry_msgs.msg import turtlesim.msg import math from nav_msgs.msg import Odometry from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped import copy import numpy as np class TfForExperiment: def __init__(self): ...
import Tkinter as tk from Tkinter import * import ttk import tkMessageBox from threading import Timer import ctypes from ctypes import cdll from ctypes import c_byte from ctypes import c_int import re cCanvasWidth = 640 cCanvasHeight = 480 cCanvasGrid = 10 cTimePeriod = 1 cBufferLen = 1024 def StartTimerTask(): ...
import os import numpy as np import scipy.io import glob from helpers import util, visualize import sklearn.metrics from globals import class_names import torch import exp_mill_bl as emb from debugging_graph import readTrainTestFile from sklearn.cluster import KMeans from sklearn.externals import joblib def make_clu...
#-*- coding:utf-8 -*- from flask import Flask,session,redirect,url_for,escape,request import json, urllib import config def auth_sso(): token = request.cookies.get(config.SSO_TOKEN) url = "https://sso.jk.cn/auth/auth_sso_token_api?token_cookie=%s" % token result = urllib.urlopen(url) json_data=json.lo...
from numpy import ndarray, array from mdtraj import Topology, Trajectory def write_bonds_tcl(bond_idxs, outfile="bonds.tcl"): bond_idxs = check_bond_idxs(bond_idxs) molid = 0 bondstring = lambda molid, idx1, idx2: \ '''set sel [atomselect {0} "index {1} {2}"] lassign [$sel getbonds] bond1 bond2 set id [l...
from trading.signal.base_signal import BaseSignal from datetime import datetime, timedelta import rqdatac as rqd from util.selectstock import filter_stock_pool from pymongo import UpdateOne rqd.init() class DailyUpBreakMa10(BaseSignal): def __init__(self): BaseSignal.__init__(self, 'daily_up_break_ma10')...
import cv2 import numpy as np import imutils pts=[] cap= cv2.VideoCapture(0) while True: ret, frame= cap.read() r1= np.array([29,86,6]) r2= np.array([64,255,255]) hsv= cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask= cv2.inRange(hsv,r1,r2) mask= cv2.erode(mask, None, iterations=2) mask=cv2.d...
from urllib.parse import parse_qs, urlencode, urlparse from django.template import Library register = Library() @register.simple_tag def set_url_param(full_path, param, value): if '?' not in full_path: full_path += "{}{}={}".format('?', param, value) return full_path base = full_path.split(...
from __future__ import division from __future__ import print_function import time import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random import sys sys.path.append('pygcn/pygcn') from utils import load_data, accuracy from layers...
name = 'stevesie' from stevesie.resources.proxies import Proxies from stevesie.resources.proxy import Proxy from stevesie.resources.task import Task from stevesie.resources.task_collection import TaskCollection from stevesie.resources.task_collection_field import TaskCollectionField from stevesie.resources.task_collec...
from django.contrib.auth.views import LoginView from django.urls import path from .views import * urlpatterns = [ path('signup' , SignUp.as_view()), path('login' , LoginView.as_view()) ]
from enum import Enum class UnitRegion(Enum): US = 1 EU = 2 class UnitController: def __init__(self, region=UnitRegion.US): self.region = region @staticmethod def convert_c_to_f(temp_c): temp_f = temp_c * (9/5) temp_f = temp_f + 32 return temp_f @staticme...
import argparse import os import socket import sys import time from glob import glob import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from scipy import spatial from tqdm import tqdm BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import data_provider impo...
from vm_spawner import VMSpawner from threading import Thread import glob, json, os def second_pass(vms): for configPath in sorted(glob.glob('./vm_config_*')): with open(configPath, 'r') as f: aVMConfig = json.loads(f.read()) Thread(target= vms.execute_commands_at, args=( \ aVMConfig['username'], \ ...
import TileArea as ta class CentralArea(ta.TileArea): """ Central area - area in the middle of all the pads, where the unselected tiles go when a player selects a given color. Also contains the 1st player tile, which goes to the first player to draw out of the middle. >>> ca = CentralArea() >>...
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Chrome() browser.get("http://www.baidu.com") # 在输入框输入内容 browser.find_element_by_id("kw").send_keys("selenium") # 删除多输入的内容 browser.find_element_by_id("kw").send_keys(Keys.BACK_SPACE) ...
x0=1.3 x1=1.6 x2=1.9 f0=0.6200860 f1=0.4554022 f2=0.2818186 df0=-0.5220232 df1=-0.5698959 df2=-0.5811571 x=[x0,x1,x2] f=[f0,f1,f2] df=[df0,df1,df2] z=[0,0,0,0,0,0] Q=[[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] for i in range(len(x)): z[2*i]=x[i] z[2*i+1]=x[i] Q[2*i]...
# !/usr/bin/env python # _*_ coding:utf-8 _*_ # 查询 数据库goods--中students的所有数据 # 1.导包 import pymysql try: # 2.连接mysql数据库的服务 connc = pymysql.Connect( # mysql服务端的IP 默认127.0.0.1/localhost-真实IP host='192.168.90.172', user='root', password="mysql", ...
import os import py from pypy.translator.test import snippet from pypy.translator.squeak.test.runtest import compile_function class TestGenSqueak: def test_while(self): def addon(i): while not i == 1: i -= 1 return i fn = compile_function(addon, [int]) ...
# pylint: disable=protected-access # This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is licensed under the Apache License 2.0. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the m...
# -*- coding: utf-8 -*- """Datacenter topology. Consists of two core switches, one switch of access layer and leaf one switch per segment _________terminate_switch_____________________ | | core_sw----------------core_sw | | -----------...
from typing import List class Solution: def sortEvenOdd(self, nums: List[int]) -> List[int]: index_odd = [] index_even = [] for index, val in enumerate(nums): if index & 1: index_odd.append(val) else: index_even.append(val) i...
"""Test that feature spec objects work as intended.""" from typing import List import numpy as np from timeseriesflattener.aggregation_fns import maximum from timeseriesflattener.feature_specs.group_specs import ( NamedDataframe, OutcomeGroupSpec, PredictorGroupSpec, ) def test_skip_all_if_no_need_to_...
''' Copyright (c) 2017, Megat Harun Al Rashid bin Megat Ahmad, Suhairy bin Sani and Shukri bin Mohd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the ab...
n1 = 8 n2 = 5 result = n1 > n2 print("n1 > n2:", result) result = n1 == n2 # 赋值运算的优先级较低,先判断n1==n2 print("n1 == n2", result) m1 = "hello" m2 = "hello" result = m1 == m2 print("m1==m2:", result) # username = input("输入用户名:") # uname = "admin123" # result = username != uname # 如果两个不相等时返回True,相等时返回False # print("用户名...
# Generated by Django 3.0.7 on 2020-06-20 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_app', '0002_details_employee_skill'), ] operations = [ migrations.CreateModel( name='Person', fields=[ ...
import time import pandas as pd def load_user_info_data(df, col_val): return df.loc[df['e_id'] == col_val] def load_all_user_info_data(size=1.0): t_start = time.time() data = pd.read_csv("raw_data/user_info.txt", names = ['e_id','e_tag','w_id','c_id'], delim_whitespace = True) data = data.sample(frac = size) t...
from functions import * # create chatbot home_bot = create_bot('Jordan') # train all data train_all_data(home_bot) # check identity identity = input("State your identity please: ") # rules for responding to different identities if identity == "Mark": print("Welcome, Mark. Happy to have you at home.") elif ide...
import pandas as pd import statsmodels.api as sm import pylab as pl import numpy as np # read the data in df = pd.read_json("dataset.json") # df.convert_objects(convert_numeric=True) print df.head() print df.describe() data = df[['cancelled', 'amount', 'cab_service_req', 'is_phone_booking', 'made_on_behalf', 'number_...
import random import math class CombatEngine: def __init__(self,die_mode,sided_die,board,game): self.board=board self.die_mode=die_mode self.sided_die=sided_die self.rolls=[] self.roll_die() self.game=game def roll_die(self): if self.die_mode=="random": for n ...
# Django settings for ntucker project. from __future__ import unicode_literals import posixpath import os.path import urlparse import dj_database_url PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) try: from local_settings import DEBUG except ImportError: DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS...
import cv2, cv, numpy as np,time, pickle def main(): #fname = "ft_video3.wmv" fname = "pass3.mpg" videoProc(fname) def nothing(args): pass def settingUpdate(hsvL,hsvU,blurRad,rgbLim): hsvL[0] = cv2.getTrackbarPos('hLower','sliders1') hsvL[1] = cv2.getTrackbarPos('sLower','sliders1') hsvL[...
from sklearn import tree # Collect data # 0 = bumpy # 1 = smooth features = [[140, 1], [130, 1], [150, 0], [170, 0]] # 0 = apple # 1 = orange labels = ["apple", "apple", "orange", "orange"] # Train classifier clf = tree.DecisionTreeClassifier() clf = clf.fit(features, labels) #for each set of data we define a s...
from __future__ import absolute_import # import everything from the fortran object from ._rrtmg_sw import *
import argparse from pdfminer.high_level import extract_text_to_fp import datetime import io import os import sys import csv import statistics # global variables subject_map = {} keyword_score = {} keyword_id = {} subjects = [] keywords = [] if __name__ == '__main__': parser = argparse.ArgumentParser() parse...
import datetime import math import multiprocessing def main(): do_computation(1) t0 = datetime.datetime.now() print(f"Doing math on {multiprocessing.cpu_count():,} processors.") processor_count = multiprocessing.cpu_count() pool = multiprocessing.Pool() for n in range(1, processor_count +...
import requests from config_bw import * import json from bs4 import BeautifulSoup headers = { 'Accept': 'application/json, text/javascript', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urle...
from brownie import accounts from brownie import ConfigContract from brownie import KeyBroadcastContract def main(): acc = accounts.load("ganache9") print("Starting deployment") cc = ConfigContract.deploy(5, {"from": acc}) KeyBroadcastContract.deploy(cc.address, {"from": acc})
scores = [ "accuracy_score", "balanced_accuracy_score", "average_precision_score", "f1_score", "precision_score", "recall_score", "jaccard_score", "roc_auc_score", "explained_variance_score", "r2_score", ] losses = [ "brier_score_loss", "log_loss", "max_error", "...
# import import random import time from tkinter import * from PIL import Image, ImageTk import glob # constant INCOME_TAX = 100 SIZE_OF_DICEimg = 70 AMMOUNT_IN_STARTING = 25000 MINIMUM_BANK_BALLANCE = -1000 BANK = - MINIMUM_BANK_BALLANCE * 12 FINE_FOR_JAIL = 500 player_colours = ['#808080', '#ff0000', '#...
import time import random def brute_force_validator(A): n = len(A) A.sort() result = 0 for z in range(2, n): for y in range(1, z): for x in range(0, y): if A[x]+A[y] > A[z]: result += 1 return result def ncr(r, n): if r == n: retu...
import os import re # Hello, Welcome to this script! This script was made by Andreas Eike. This script will rename your movie files and # directory name for each movie automatically, in the specified path. You can safely run this script without any options # if this script is placed in a folder which contains folders,...
#Preço = a #Pagamento = b a = float(input("Preco sugerido: ")) b = float(input("Pagamento proposto: ")) if (a > b): x = a - b round(x, 2) msg = "Falta " else: x = b - a round(x, 2) msg = "Troco de " print(msg, x)
import logging, errno, time class setlogger(): #Root Logger rootLogger = logging.getLogger('') rootLogger.setLevel(logging.DEBUG) # log file handler fh = logging.FileHandler('LOG_WT_SENSORS.txt') # Format the log message formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s...
#!usr/bin/python3 #-*- coding:utf-8 -*- """ 创建正则表达式,使用前瞻和后顾来保证手机号前后不应该出现数字 version:1.0 date:2019\5\30 """ import re def main(): pattern=re.compile(r'(?<=\D)(1[38]\d{9}|14[57]\d{8}|15[0-35-9]\d{8}|17[678]\d{8})(?=\D)') sentence=''' 重要的事说8140123456789遍, 文档手机号是13512346789这个号,不是15600998765,也不是110或119, ...
from django.contrib import admin from . models import Trail, Item, Location, Game, Action, Event, Context # Register your models here. class ItemAdmin(admin.ModelAdmin): list_display = ('id', 'item_name', 'item_description') class LocationAdmin(admin.ModelAdmin): list_display = ('id', 'location_name', 'loc...
import pandas as pd import matplotlib import matplotlib.pyplot as plt import numpy as np import turicreate from surprise import NormalPredictor from surprise import Dataset from surprise import Reader from surprise.model_selection import cross_validate from surprise import SVD from collections import defaultdict def p...
from django import template from viewer.views.shared_code import glob_manager_data from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag(takes_context=True) def get_urls_header(context): try: id_corpus = context.request.session['viewer__viewer__current_corpus']...
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin __copyright__ = "Copyright 2011 Red Robot Studios Ltd." __license__ = "GPL v3.0 http://www.gnu.org/licenses/gpl.html" admin.autodiscover() urlpatterns = patterns('', (r'', include('openelm.public.urls')),...
from distutils.core import setup setup( name= 'pyfinder', version='0.5', description= ' Look for files and text inside files', long_description= open('README').read(), py_modules= ['pyfinder'], author= 'Giovanni C. Oberti', # Tratto da "Python Gioda completa" di Marco Buttu author_email=...
def calculate(): operation = input(''' add for addition sub for subtraction mul for multiplication div for division ''') num_1 = int(input()) num_2 = int(input()) if operation == 'add': print('{} + {} = {}'.format(num_1, num_2,num_1 + num_2)) elif operation == 'sub': print...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-03-29 05:54 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_models', '0014_auto_20180329_0544'), ] operations = [ ...
# Generated by Django 3.0 on 2021-04-06 13:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('cadastro', '0002_auto_20210405_1130'), ] operations = [ migrations.CreateModel( ...
class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ no_circle_course = set() temp_visited = set() def is_circle_course(n): if n in temp_vis...
#!/bin/python3 # link problem: https://www.hackerrank.com/challenges/non-divisible-subset/problem import math import os import random import re import sys # # Complete the 'nonDivisibleSubset' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER...
import numpy as np import scipy.stats as stats import matplotlib as plt def calculate_covariance(x1, x2, length_scale): """ Input: x1, x2 (numpy vectors), length_scale (float, representing length_scale Output: S, covariance matrix, representing the covariance of x1,x2 """ nrows = len(x1) ncols...
""" COMP 208 - Assignment 4 """ import skimage.io as i import numpy as np image_path = input('Please enter the path to the saved "mountain.png" image: ') #The user is asked to give the file location in order to be able to locate mountain.png. if image_path[-1] != "\\": #This adds the \\ necessary a...
from socket import socket, AF_INET, SOCK_STREAM server = socket(AF_INET, SOCK_STREAM) server.bind(('', 1234)) server.listen(5) HEADERSIZE = 10 client, address = server.accept() # Connection acknowledgement print(f"Connection with {address} has been established") msg = "Congratulations you have connected with the se...
import hail as hl import scipy.stats as spst import pytest def test_deprecated_binom_test(): assert hl.eval(hl.binom_test(2, 10, 0.5, 'two.sided')) == \ pytest.approx(spst.binom_test(2, 10, 0.5, 'two-sided')) def test_binom_test(): arglists = [[2, 10, 0.5, 'two-sided'], [4, 10, 0.5, ...
# coding: utf-8 # In[59]: # Import modules into namespace import pandas as pd import numpy as np # In[66]: # Read xlsx doc filepath = r'C:\Users\brandon.terrebonne\Desktop\organization_gen\albertsons_dsd_spend_20160624.xlsx' df = pd.read_excel(filepath) # In[67]: # Add missing columns, which will now have null...
s = int(input("초를 입력하세요 :")) h = s//3600 m = (s%3600)//60 t = (s%3600)%60 print(s, "초는", h, "시간", m, "분", t, "초입니다.")
# -*-coding: utf-8-*- # Author : Christopher Lee # License: Apache License # File : test_query_cache.py # Date : 2017-05-18 09-08 # Version: 0.0.1 # Description: description of this file. import logging import datetime from db_util import mysql_query, mysql_execute from werkzeug.contrib.cache import RedisCache f...
import time from selenium import webdriver from selenium.webdriver import DesiredCapabilities class TestDemo: def setup(self): url = "http://127.0.0.1:5001/wd/hub" url1 = "http://193.112.47.128:5001/wd/hub" chrome_options = webdriver.ChromeOptions() # 解决DevToolsActivePort文件不存在的报错 ...
# -*- coding: utf-8 -*- """ Canny 边缘检测 蒋小军 """ import cv2 import numpy as np from matplotlib import pyplot as plt def nothing(x): pass img = cv2.imread(r"C:/users/public/pictures/Sample Pictures/shapessm.jpg") cv2.namedWindow('edges') L = 80 H = 200 cv2.createTrackbar('L','edges',0,255,nothing) cv2.createTra...
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved. # -*- coding: utf-8 -*- # pragma pylint: disable=unused-argument, no-self-use """Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from resilient_circuits.util import get_config_data, get_function_definition from resi...
from unittest import TestCase, main from unittest.mock import Mock, MagicMock from mck import Foo class TestMck(TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): pass def tearDown(self): pass def test_foo(self): foo = Foo() foo.bar = Ma...
#!/usr/bin/env python import sys, os sys.path.append('../lib') import osutils as utils try: from wia import Wia except: utils.install_pip('wia') from wia import Wia try: from sense_hat import SenseHat except: utils.install_pkg('sense-hat') from sense_hat import SenseHat def install(): ut...
# Довженко Віталій # Лабораторна робота №3_2 # from PyQt5 import QtWidgets from PyQt5.uic import loadUi import sys class mywindow(QtWidgets.QMainWindow): def __init__(self): super(__class__, self).__init__() loadUi("Lab3_2_view.ui", self) self.horizontalSlider.valueChanged.connect(self...
# A lambda function is a small anonymous function. # A lambda function can take any number of arguments, but can only have one expression. # A lambda function that adds 10 to the number passed in as an argument, and print the result: x = lambda a : a + 10 print(x(5)) # A lambda function that multiplies argument a w...
# Write a python program to check whether a number is even or odd without using modulus (%) #operator. n=int(input("Enter a Number:\t")) if n&1==1: print('Number is Odd') else: print('Number is Even')
# estParam.py - functions to estimate hull parameters from principal characteristics import math # --------- def displacement(Cb, T, L, B) : # inputs in unitless, meters, meters, meters # constants rho = 1026 #kg/m^3 g = 9.81 #m/s^2 # calculate displacement nabla = Cb*T*L*B # volume displacement ...
import torch import torch.nn as nn import torch.nn.functional as F import pdb class BidirectionalLSTM(nn.Module): def __init__(self, nIn, nHidden, nOut): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True) self.embedding = nn.Linear(nHidden * 2, n...
import io import os import json from packaging import version import numpy as np import onnx import onnx.numpy_helper import pytest import torch import torch.nn as nn import torch.nn.functional as F from torch.onnx.symbolic_helper import _default_onnx_opset_version from pytorch_pfn_extras.onnx import export from pyto...
import xml.sax import re import pdb import sys import os #THIS CODE IS MADE FOR PYTHON 3.0+ #get link probabilities for anchor texts #NEEDS #anchors_anum #anchors_tally #OUTPUT #anchors_link_prob #FORMAT #anchor_text<>num_links<>num_occurences anchors = {} for fname in os.listdir('../anchors_anum/'): for line i...
# -*- coding: utf-8 -*- ''' Created on 2018年2月2日 @author: Administrator ''' import csv import numpy as np from sklearn import svm def get_data(path): with open(path) as fn: readers=csv.reader(fn) rows=[row for row in readers] rows.pop(0) return np.array(rows) def trans_data(train_data): ...
from sys import argv #Here we import a module from sys to keep code small. #argv is the "argument variable" which holds arguments you pass to Python script #when you run it. script, first, second, third = argv #Assigning argv to four variables to unpack argv in each variable print "The script is called: ", script pri...
import torch from utils.data_reader import get_train_dev_test_data from utils.train_helper import load_model, eval_model, get_data_loader train_data, dev_data, test_data = get_train_dev_test_data() model = load_model("model/checkpoints/DeepCoNN_20200601215955.pt") model.to(model.config.device) loss = torch.nn.MSELoss...
t=int(input()) for I in range(t): n=int(input()) a=list(map(int,input().split(" "))) print(len(set(a))) '''if(len(b)==1): print('1') else: count=0 for i in range(len(b)-1,0,-1): count+=(b[i]-b[i-1]) print(count+1)'''
# base imports import tkinter as tk from tkinter import ttk # relative module imports for all the frames from .manageusers import ManageUsers from .employees import Employees from .payments import Payments from .tenants import Tenants from .apartments import Apartments # A master frame [contained by the root Applica...
# Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: # a) tamanho da lista # b) maior valor da lista # c) menor valor da lista # d) soma de todos os elementos da lista # e) lista em ordem crescente # f) lista em ordem decrescente Lista = [5, 7, 2, 9, 4, 1, 3] print("A sua...
# --------------------------------------------------------- #Name: # #Author:Tory Stietz # #Date created: # #Script Function: # #Script References: # #Special Instructions: # #**************************** import requests import json def getVlanBrief(VlanIP) """ Be sure t...
# -*- coding: utf-8 -*- """ Created on Mon Jun 3 14:01:13 2019 @author: lenovo """ newstr="RESTART" #define the value txt=newstr.replace("R",'$') #it is use for replace the value of R as $ print(txt) #it print the value of txt apr=txt.replace("$",'R',1) #It defines that left the first R print(apr)
import os import inspect import app # Values for server paths # appRoot = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) appRoot = os.path.dirname(inspect.getfile(app)) appConfigRoot = os.path.join(appRoot, 'Config') webRoot = os.path.join(appRoot, 'wwwroot') loginRoot = r'http://cs302.pythonanywhere.com' # ...
import random try: filepath="monster_list.txt" count = len(open(filepath,encoding="utf-8").readlines()) a=random.randint(0,count) f = open(filepath,"r",encoding="utf-8")# 返回一個檔案物件 line = f.readline()# 呼叫檔案的 readline()方法 for i in range(a): line = f.readline() ...
import rasterio, os, shutil, glob import numpy as np ### # REQUIRES GDAL 1.8.0 + # # This is more of a roadmap to how we got to specific mask results than it is a script. # Keep this in mind when reading the processes used to get to the needed masks. ### input_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/p...
from flask import Flask, render_template, redirect, request, send_from_directory from linode_api4 import LinodeLoginClient, OAuthScopes from keys import LINODE_API_KEY, LINODE_CLIENT_ID from setup_vpn import create_vpn from constants import LINODE_REGIONS app = Flask(__name__) @app.route("/") def hello(): return...