text
stringlengths
38
1.54M
# coding: utf-8 import itchat import re import jieba from pandas import DataFrame itchat.login() friend = itchat.get_friends(update=True)[0:] chatroom = itchat.get_chatrooms() print(chatroom) # print(friend) signatures = [] for i in friend: signature = i["Signature"].strip().replace("span","").replace("class","").r...
from flask import Flask, request, jsonify, make_response from flask_sqlalchemy import SQLAlchemy import uuid from werkzeug.security import generate_password_hash, check_password_hash import jwt from functools import wraps app = Flask(__name__) app.config['SECRET_KEY'] = '123' app.config['SQLALCHEMY_DATABASE_URI'] = '...
# METODOS MAGICOS class Empleado(object): def __new__(cls): print("El metodo magico __new__ ha sido invocado") instancia = object.__new__(cls) print(instancia) return instancia def __init__(self): print("El metodo magico __init__ ha sido invocado") def __str__(self): ...
import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DEFINITIONS_ROOT = os.path.join(PROJECT_ROOT, 'src', 'definitions')
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.metrics import classification_report from sklearn.metrics import plot_confusion_matrix from sklearn.metrics import plot_roc_curve from sklearn.model_selection import train_test_split from sklearn.utils import shuffle __all__ = ['load_d...
import numpy as np import holoviews as hv import pandas as pd from bokeh.application.handlers import FunctionHandler from bokeh.application import Application from bokeh.io import show from bokeh.layouts import layout from bokeh.plotting import curdoc from bokeh.models.widgets import Panel, Tabs, Select, RadioButtonGr...
import re s = 'A message from csev@umich.edu to cwen@iupui.edu about meeting @2PM' # \s matches all the blank characters, \S is the opposite lst = re.findall('\S+@\S+', s) print(lst)
import numpy as np from source import cdp, graph from sklearn.neighbors import NearestNeighbors class CDP(object): def __init__(self, k, th, metric='minkowski', max_sz=1000, step=0.05, debug_info=False): ''' k: k in KNN searching. th: threshold, (0, 1) metric: choose one from [ ...
""" 思路: 建立一个猫的类 里面存放这只猫的ID一个类属性 同样的建立一个狗的类 一个add类 里面用队列的方式存储想要加入的具体的狗或者猫的对象 以及一个count时间戳类属性用来存放不论猫还是狗对象进队列的时间戳 同时这个add类里有两个队列 一个猫队列一个狗队列 pollDog方法可以从狗队列取出一个狗对象 pollCat从猫队列取出猫对象 pollPet方法取出add类里时间戳属性较大的那一个对象 isEmpty、isDogEmpty与isCatEmpty分别可以查看队列中是否为空 """ import queue class Cat(object): def __init__(sel...
from django.db import models # Create your models here. class Formulario(models.Model): nombre = models.CharField(max_length=150, null=False) descripcion = models.CharField(max_length=200, null=False, blank=True) active=models.BooleanField(null=False, default=True) def __unicode__(self): return...
# Generated by Django 3.0.3 on 2020-02-25 09:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='School', fields=[ ...
#ex43 Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder. import math print "The area of rectangle is %d" % (math.sqrt(5)) print "The volume of cylinder is %d" % (math.sqrt(math.pi * 4.0)) area = 1256.66 volume = 1254.725 decimals = 2 print("The area o...
import os import cv2 import face_recognition from PIL import Image from imutils import paths import argparse import pickle #Get dataset path and encodings path as arguments obj = argparse.ArgumentParser() #Input (python_filename -i path_to_dataset )as argument obj.add_argument("-i", "--dataset", required=True,help="pa...
# Tipos de variables [Python] # Ejercicios de profundización # Autor: Inove Coding School # Version: 2.0 # NOTA: # Estos ejercicios son de mayor dificultad que los de clase y práctica. # Están pensados para aquellos con conocimientos previo o que dispongan # de mucho más tiempo para abordar estos temas por ...
from model.database import db from model.models import Session from uuid import uuid4 from datetime import date def get_all(): """Returns all of the Session objects in the database :return A list of Session objects :rtype list """ return Session.query.all() def get(session_id): """Returns t...
# -*- coding:utf-8 -*- # # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 # # Unl...
import rest_framework.serializers as serializers class EmptySerializer(serializers.Serializer): class Meta: model = None def get_model_serializer(model_arg): class GenericSerializer(serializers.ModelSerializer): class Meta: model = model_arg fields = '__all__' re...
# -*- coding: utf-8 -*- import requests from lxml import html class RedlionScraper(object): # USERNAME = 'redcat' PASSWORD = 'redcat' HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.73 Safari/537.36', 'Content-T...
# Adding a comment in the header to test forking issues from multiprocessing import Pool from mcr12 import * import subprocess import os import sys import time from firebase import firebase import datetime SHELFIE_EXE = "/home/root/smart_shelf" NUM_FORCE_SAMPLES = 5 NUM_WORKERS = 1 BASE_FORCES = [0.0, 0.0, 0.0, 0.0] ...
from django.shortcuts import render, redirect from django.http import HttpResponse from foll.forms import PartyForm, FoodForm, UserSignUpForm, LoginForm, PartyInvitationForm, PartyInvitationFormAlternative from foll.models import Party, Food, FoodRating, UserInParty, TopRatedFood, UserData from django.template import R...
# # RTEMS Tools Project (http://www.rtems.org/) # Copyright 2019, 2020 Chris Johns (chrisj@rtems.org) # All rights reserved. # # This file is part of the RTEMS Tools package in 'rtems-tools'. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, pr...
#!/usr/bin/python nucleotide_value_map = {"A":1, "T":2, "C":3, "G":4} def find_pattern(patterns, genome): tens_table = [pow(10, m) for m in xrange(len(patterns[0]))] hash_patterns = get_hashes(patterns, tens_table) index = [] for current_index in xrange(len(genome) - len(patterns[0]) +...
#!/usr/bin/env python """ Author : Rahul Patil<http://www.linuxian.com> Purpose : Send free sms using www.indyarocks.com Date : Thu Jan 2 21:36:00 IST 2014 Dependencies : 1. Your number MUST be register with indyarocks 2. Python 2.7.3 Modules can be install...
"""Discrete, linear, time-invariant Gaussian transitions.""" from typing import Optional import numpy as np from probnum.randprocs.markov.discrete import _linear_gaussian try: # functools.cached_property is only available in Python >=3.8 from functools import cached_property # pylint: disable=ungrouped-im...
def momentum_update(loss, params, grad_vel, lr=1e-3, beta=0.8): """Perform a momentum update over a collection of parameters given a loss and 'velocities' Args: loss (tensor): A scalar tensor containing the loss whose gradient will be computed params (iterable): Collection of parameters with respect to whi...
"""Utils for emencia""" from django.template import Context, Template import re from html2text import html2text as html2text_orig from StringIO import StringIO def render_string(template_string, context={}): """Shortcut for render a template string with a context""" t = Template(template_string) c = Contex...
from django.contrib import admin from django.urls import path,include from .import views urlpatterns = [ path('question2/<int:id>', views.ques2,name="ques2"), ]
def recommend(user_book, book_list): import math import collections import operator user_data = "" total_data = "" def check_iteration(book): if isinstance(book, collections.Iterable): return book else: book = (book,) return book user_boo...
import cv2 import numpy as np def filter(image, kernel): h, w, _ = image.shape size = kernel.shape[0] // 2 # padding pad = np.zeros((h + 2 * size, w + 2 * size, 3), dtype=np.float) pad[size : h + size, size : w + size, :] = image.copy().astype(np.float) # filtering result = np.zeros_like(i...
import numpy as np class Params(object): def __init__(self, speed, landing_time, takeoff_time, maximum_flight_time, # reload_time, # battery_switching_time, # total_number_of_batteries, # ...
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.preprocessing import StandardScaler from sklearn.pipeline im...
from django.shortcuts import render, redirect from django.views import View from .forms import UploadFileForm, DocumentsSaverForm, MultiFileForm from django.http import HttpResponse from .models import UploadFileModel # Create your views here. class UploadFileView(View): def get(self, request): form = Up...
# coding=utf-8 import argparse def precision(pred, std): """ 求分词结果的正确率 Args: pred: 分词结果,一个元组,其内容为各个句子的分词结果(仍为元组). std: 标准分词结果,结构与pred相同. Returns: 返回正确率,取值[0,1]. """ correct = 0 total_num = 0 for p_s, std_s in zip(pred, std): for word...
from ..global_variables import GlobalVariables as Gb from ..const import (NOT_HOME, STATIONARY, CIRCLE_LETTERS_DARK, UNKNOWN, CRLF_DOT, CRLF, ) from collections import OrderedDict import os #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # # DATA VERIFICATION FUN...
# Generated by Django 3.1.3 on 2021-01-10 05:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('restaurant', '0021_auto_20210110_1341'), ] operations = [ migrations.AlterUniqueTogether( name='menu', unique_together={('re...
## Source code by Udacity - as part of their MLND program from agent import Agent from monitor import interact import gym import numpy as np env = gym.make('Taxi-v2') agent = Agent() avg_rewards, best_avg_reward = interact(env, agent)
# coding: utf-8 import pytest @pytest.mark.parametrize('container_name', ['zoo']) def test_container_running(host, container_name): c = host.docker(container_name) # 判断容器状态是否为 running assert c.is_running # 判断容器健康状态是否为 healthy assert c.inspect()['State']['Health']['Status'] == 'healthy' # @pytest...
""" 【问题描述】组合辛普森公式求f(x)=2+sin(2*sqrt(x))的积分近似值。 【输入形式】在屏幕上依次输入积分上限、下限和等距子区间个数。 【输出形式】输出使用组合辛普森公式求得的积分近似值。 【样例1输入】 1 6 5 【样例1输出】 8.18301549 """ import numpy as np # 定义f(x) def f(x): y = 2 + np.sin(2 * x**(0.5)) return y def simprl(a, b, m): h = (b - a) / (2 * m) s1 = 0 s2 = 0 f...
import re import couponmon if not couponmon.login("gfitch@gaf3.com","navinet"): exit("Login failed") response = couponmon.opener.open("http://www.couponmom.com/restaurant-coupons-159") links = re.findall('<a.*href="(free-.*?)".*?>',response.read()) for link in links: print link
def load_data(filename): with open("C:\\Users\\Home-PC\\Desktop\\python auto notes\\jatinder.txt",'r') as f: for line in f: print(int(line)) def store_data(filename): with open("C:\\Users\\Home-PC\\Desktop\\python auto notes\\jatinder.txt",'w') as f: number =0 ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
bot = int(input("Введите прибыль:")) usd = int(input("Введите текущий курс Доллара:")) sultan = bot * (60.8 / 100) malik = bot * (39.2 / 100) sultanusd= sultan * usd malikusd = malik * usd procent_1 = sultanusd * (3.5 / 100) procent_2 = malikusd * (3.5 / 100) malik_back = malikusd - procent_2 sultan_back = s...
'''@file bottleneck_encoder.py contains the BottleneckEncoder''' import tensorflow as tf import ed_encoder import ed_encoder_factory class BottleneckEncoder(ed_encoder.EDEncoder): '''a listener object transforms input features into a high level representation''' def __init__(self, conf, constraint, name...
from scrapy import Spider, Request from yimby.items import YimbyItem import csv import re # from pandas import DataFrame,read_csv import pandas as pd from numpy import repeat,array class YimbySpider(Spider): name = 'yimby' allowed_urls = ['https://newyorkyimby.com'] start_urls = ['https://newyorkyimby.com/...
# coding: utf-8 str1 = u"パトカー" str2 = u"タクシー" res = u"" for i in range(0, len(str1)): res = res + str1[i] + str2[i] print res
from xlwt import Workbook import xlwt import os book = Workbook(encoding="utf-8") sheet1 = book.add_sheet("Sheet 0") style = xlwt.XFStyle() align = xlwt.Alignment() align.horz = xlwt.Alignment.HORZ_CENTER align.vert = xlwt.Alignment.VERT_CENTER style.alignment = align sheet1.write_merge(0, 1, 0, 0, "编号", style=style) s...
import pandas as pd from abc import ABC,abstractmethod import data_conversion import dim_reducation import feature_extraction class AbstractLoader(ABC): def __init__(self): pass @abstractmethod def __getitem__(self,pos): pass @abstractmethod def __len__(self): pass class ...
import os import re from medex.utils import sys_url import platform def build_medex_obj(input_file, remove_indices=True): """ This function parses a MedEx output file into an object slightly more friendly to work with. The output is a list where each index is mapped to a line from the file. Each l...
import glob import os import cv2 import multiprocessing import numpy as np from tensorflow.keras.utils import Sequence from tensorflow.keras.preprocessing.image import ImageDataGenerator import random from bisect import bisect_left from math import ceil import tensorflow as tf import itertools RGB_AVERAGE = np.array(...
# -*- coding: utf-8 -*- import Database from datetime import date, timedelta # Polaczenie z baza danych db = Database.Database() # Ponowne utworzenie bazy db.recreate() db.add_model("Bozenka") db.add_segment("Bozenka", "Segment 1", 1, 2, 3) db.add_segment("Bozenka", "Segment 2", 4, 5, 6) db.add_param("Bozenka", "Seg...
from datetime import datetime from django.test import TestCase from django.http import HttpRequest from students.models.students import Student from students.models.groups import Group from students.util import get_current_group class UtilTestCase(TestCase): """ Test functions from util module """ def set...
Frango='' tabla=[] Rfila=Rcolumna=mov=fil=col=0 def crearTablero(n): global tabla filas = n tabla = [0] * filas for i in range(filas): tabla[i] = [0] * n def fueraDeRango(fila,columna): global tabla global Frango if fila>=len(tabla ) or columna>=len(tabla): Frango="fuera" ...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(120), unique=True, nullable=False) last_name = db.Column(db.String(120), unique=True, nullable=False) username = db.Column(db.String(120), uniqu...
# def square_numbers(nums): # result = [] # for i in nums: # result.append(i*i) # return result # my_nums = square_numbers([1,2,3,4,5]) # print(my_nums) #[1, 4, 9, 16, 25] # Converting the above function into a generator # def square_numbers(nums): # for i in nums: # yield(i*i) # my_nums = square_numbers([...
board = [[0 ,0 ,0 , 2 ,0 ,5 ,8 ,0 ,0], [0 ,0 ,0 ,3, 8 ,0 ,0 ,4 ,0], [0 ,0 ,5 ,0, 0 ,9 ,0 ,1 ,0], [5 ,4 ,6 ,0 ,2 ,0 ,0 ,7 ,0], [0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 ,5], [0 ,0 ,3 ,0 ,5 ,4 ,6 ,0 ,0], [0 ,1 ,4 ,0 ,0 ,2 ,3 ,0 ,8], [9 ,3 ,8 ,5 ,0 ,0 , 0...
from scrapy import cmdline cmdline.execute("scrapy crawl QsbkSpider".split()) # cmdline.execute(["scrapy" "crawl" "QsbkSpider"])
#!/usr/bin/env python # coding=utf-8 ##in / not in 关键字在字符串中使用 #list1 = [1, 2, 3, 4, 5] #无法判断是否是子集 #print 1 in list1 #list2 = [1, 2, 3, 4, [1, 2, 3]] #print [1, 2, 3] in list2 #str1 = "abcdefg" #可以判断子集 #print "a" in str1 #print "bcd" in str1 # ##+拼接 *重复 #print (list1 + ["hello", "world"]) * 4 #切片传送做进阶 list1[::...
from flask import Flask from flask import request import inbound_worker import Counter from queue_manager import QueueManager from process_manager import ProcessManager app = Flask(__name__) @app.route('/') def enqueue_request(): QueueManager.enqueue(request) QueueManager.print_val() return "SUCCESS" ...
import pickle, logging, json import requests from pathlib import Path class Docuware: filecabinet_id = 'XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX' c_path = Path('cookies.bin') docuware_url = 'https://XXX.docuware.cloud' def login(self, credentials) -> None: # Session will hold the cookies s = requests.Session...
''' test issue 119 ''' #----------------------------------------------------------------------------- # :author: Pete R. Jemian # :email: prjemian@gmail.com # :copyright: (c) 2014-2019, Pete R. Jemian # # Distributed under the terms of the Creative Commons Attribution 4.0 International Public License. # # The ...
# Copyright 2018 Immuta, Inc. Licensed under the Immuta Software License # Version 0.1 (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.immuta.com/licenses/Immuta_Software_License_0.1.txt # # Unless required by applicable law o...
#!/bin/python from calculator import Count import unittest class TestAssert(unittest.TestCase): """docstring for ClassName""" def setUp(self): print("start") def test_case(self): num = 10 self.assertEqual(num,10,msg="输入的数字不等于10,测试不通过。") def test_case1(self): j = Count(9,7) self.assertTrue(j.is_prime...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-07 14:23:15 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def moveZeroes(self, nums): if not nums: return [] # zero 负责指向第一个为零的数 # right 负责...
#!/usr/bin/python """ Name : esxi_contrailvm.py Author : Prasad Miriyala, Kiran Desai Description : Start Contrail VM, utilities 1) Prepare .vmx 2) Creating networking support for contrail vm a. create vswitches b. port groups and vlans ...
# -*- coding: utf-8 -*- """ Goodreads API Client ===== Goodreads API Client is a non-official Python client for `Goodreads <http://www.goodreads.com/>`. """ import ast import re from setuptools import setup, find_packages _version_re = re.compile(r'VERSION\s+=\s+(.*)') with open('goodreads_api_client/__init__.py', '...
from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yahoo_scrapper.settings') app = Celery('yahoo_scrapper') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(['yahoo_scrapper']) @app.task(bind=True) def ...
from serialtransceiver import HandshakeSerialDevice from daqmx.task.co import GenerationStoppedException from threading import Lock from time import sleep import socket TIMEOUT_CODE = 999 class NotEnableableException(Exception): args = ['stepper motor is not enableable'] class SetPositionStoppedException(Exceptio...
## # This program draws two Italian flags using the geometric shape classes. # from ezgraphics import GraphicsWindow from shapes import Rectangle, Line, Group # Define constants for the flag size. FLAG_WIDTH = 150 FLAG_HEIGHT = FLAG_WIDTH * 2 // 3 PART_WIDTH = FLAG_WIDTH // 3 # Create the graphics window. win = Gr...
# -*- coding: utf-8 -*- import text def atbash(x): y=list(x) Datbash={'a':'z','b':'y','c':'x','d':'w','e':'v','f':'u','g':'t','h':'s','i':'r','j':'q','k':'p','l':'o','m':'n','n':'m','o':'l','p':'k','q':'j','r':'i','s':'h','t':'g','u':'f','v':'e','w':'d','x':'c','y':'b','z':'a'} n=0 while n < len(y): if y[...
#!/usr/bin/env python # encoding: utf-8 name = "Roldan_Ir111" shortDesc = u"" longDesc = u""" Based primarily on "Mechanistic study of hydrazine decomposition on Ir(111)" Alberto Roldan et al. Phys.Chem.Chem.Phys., 2020, 22, 3883 DOI: 10.1039/c9cp06525c and "Kinetic and mechanistic analysis of NH3 decomposition on...
# @Time : 2021/4/10 13:20 # __author__ = 'zhangcheng' # coding:utf-8 import pytest import yaml from Calculator import Calculator class TestCalc: def setup_class(self): self.calc = Calculator() print("开始计算") def teardown_class(self): print("计算结束") @pytest.mark.parametrize("a,b,e...
ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) z = 0 for c in range(i,j + 1): c = str(c) rev = c[::-1] c = int(c) rev = int(rev) if (rev - c) % k == 0: z += 1 print(z)
import json import time import numpy as np import requests import re class GetFunctions(): def get_port_desc(url): r = requests.get(url=url) return r.json() def get_stats_switch(url): r = requests.get(url=url) return r.json() class PostFunctions(): def change_table_entry(...
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer, Paragraph, TableStyle, Table) from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from tablaCliente import TablaCliente from sqlite3 import dbapi2 cl...
from django.db import models #models.IntegerField(), models.CharField(max_length=50) class ManiExtraArti(models.Model): codmanif = models.AutoField(primary_key=True) # código interno único para manifestación extra articular codusuario = models.IntegerField(null=True) # código interno de usuario, para saber qu...
#!/usr/bin/env python3 """ This script allows you to call other scripts located in repositories housed in the same parent folder as this script's cloned repository with a numbered menu by generating and sending your operating system's terminal/shell commands to launch them rather than you having to modify/import/co...
import hashlib import uuid def key(keyword, how_many: int): count = [] while how_many > 0: salt = uuid.uuid4().hex hash_key = hashlib.sha224(salt.encode() + keyword.encode()).hexdigest() to_str = str(hash_key) cut_str = to_str if cut_str not in count: coun...
resource_strings = {} resource_strings["DUP_EMAIL"] = "Email already in use!" resource_strings["USER_NOT_ACTIVATED"] = "Your application is pending approval. You'll receive an email shortly!"
print('Begin', __name__) import proga # nome do módulo é o nome do arquivo pq não é entry point print('Define fB') def fB(): print('Dentro fB') proga.fA() print('Chama fB') fB() print('End', __name__)
""" optics.py contains functionality related to the optical components needed to build up a proper prescription. This is a generic module containing functions that don't have a home elsewhere. It contains the class structure to make the wavefront object used in most prescriptions. """ import numpy as np import proper ...
import socket from os import path import os # Parse request header and return list def parse_header(header): sanitized_header = header.replace('\r\n', ' ') parsed_header = sanitized_header.split(' ', 3) return parsed_header # Check for valid HTTP request def valid_request(exists, protocol, method): ...
import json path = r"D:\learning\机器学习与大数据分析\project\LAB4\data\bdd100k\labels\bdd100k_labels_images_val.json" transfer_dict = [] with open(path, 'r') as load_f: load_dict = json.load(load_f) for dict in load_dict: name = dict['name'] # print(dict) # print(name) for object in dict['labels...
import tensorflow as tf import matplotlib.pyplot as plt # load the data mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() # scale the data or "normalize" it x_train = tf.keras.utils.normalize(x_train, axis = 1) x_test = tf.keras.utils.normalize(x_test, axis = 1) model = tf.keras...
__all__ = [ 'BiLSTM', 'BiGRU', ] import torch import torch.nn as nn import torch.nn.functional as F from models.utils import to_cpu # set device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class BiLSTM(nn.Module): def __init__( self, ...
# Peyton Turner # EECS 325 Project 2 # A script for loading a list of addresses stored in a file "targets.txt" and for each of those targets computing the RTT, the number of hops # between you and the destination, and the number of bytes of the original datagram included in the ICMP error message # Might also optionall...
import os, time import tensorflow as tf import numpy as np from tensor_utils import * class Policy(): def __init__(self, state_shape, n_actions, name, recover=False, act_int=False, out_dir='logs', sess=None, pull_scope='learner_global'): tf.set_random_seed(42) np.random...
import core.h_file_handling as hfh import core.h_format_manipulators as h from statsmodels.formula.api import ols from statsmodels.stats.multicomp import (pairwise_tukeyhsd) import statsmodels.api as sm from scipy.stats import chi2 import pandas as pd import os from math import pow, e from sklearn.decomposition import ...
"""dpro URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vi...
""" Interpreting hyperbole with RSA models of pragmatics. Taken from: https://gscontras.github.io/probLang/chapters/03-nonliteral.html """ import torch import collections import argparse import pyro import pyro.distributions as dist import pyro.poutine as poutine from search_inference import factor, HashingMargina...
#아스키코드 2글자 해결해야 하는 과제. ''' def solution(participant, completion): answer = '' hashlist = [] tmp2 = '' f_str = '' for i in completion: tmp = i for j in tmp: tmp2 += str(ord(j)) hashlist.append(tmp2) tmp2 = '' i = 0 while i < len(participant): ...
import sys sys.path.append("..") import os import torch import torch.nn.functional as F import torchvision import numpy as np from PIL import Image import cv2 import json import h5py import random from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.middleware.cors import CORSMiddleware from ope...
#Flujo de ejecución de un programa y estructura condicional # El flujo de ejecución de un programa es el orden con el que se ejecutan sus instrucciones. # Las estructuras de tipo condicional pueden alterar el orden natural de arriba a abajo. print("Programa de evaluación de notas") nota_alumno=int(input("Introduce l...
""" Django settings for Superdrogas project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import e...
# Based on https://gist.github.com/zed/5073409 """ Compatibility layer for Python 2 which exposes time.perf_counter and time.process_time under Python 2. This also allows us to utilize time.process_time() counter under Python 2 on CI which results in more accurate and less noisy data. """ from __future__ import abso...
# Uses python3 import sys def fibonacci_sum_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current return sum%10 def find_pisano_period_occurence(mod_list): found_...
def posibleList(list_,j): j += 1 size = len(list_) result = list_[0] for i in range(1,size): if i > 0 : if list_[i] >= result[0]: result = list_[i] + result else: result = result + list_[i] print("CASE #" + str(j) + ": " + result) n = int(input()) for i in range(n): str_ = input(...
#! /usr/bin/env python import rospy from sensor_msgs.msg import Range class SafeTeleop: def __init__(self): rospy.Subscriber('/US1', Range, self.us1_cb) self.value = 0.0 def us1_cb(self, msg): self.value = msg.range def update(self): print "Value: " + str(self.value) rosp...
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True res = [] self._inorder(root, res) for i in range(len(res) - 1): if res[i] > res[i + 1]: retur...
#import socket module from socket import * # @UnusedWildImport import sys # In order to terminate the program @Reimport serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a sever socket # Assign IP address and port number to socket serverSocket.bind(('', 12000)) serverSocket.listen(1) while True: #Est...
from resources.interface.frontpage import FrontPage from resources.interface.mainpage import MainPage from resources.interface.pages import Pages from os import path import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication, QStyleFactory, QLabel, QHBoxLayout, QS...